diff --git "a/swift/bitchat_function_bench.jsonl" "b/swift/bitchat_function_bench.jsonl" new file mode 100644--- /dev/null +++ "b/swift/bitchat_function_bench.jsonl" @@ -0,0 +1,3 @@ +{"repo_name": "bitchat", "file_name": "/bitchat/bitchat/ViewModels/ChatViewModel.swift", "inference_info": {"prefix_code": "//\n// ChatViewModel.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # ChatViewModel\n///\n/// The central business logic and state management component for BitChat.\n/// Coordinates between the UI layer and the networking/encryption services.\n///\n/// ## Overview\n/// ChatViewModel implements the MVVM pattern, serving as the binding layer between\n/// SwiftUI views and the underlying BitChat services. It manages:\n/// - Message state and delivery\n/// - Peer connections and presence\n/// - Private chat sessions\n/// - Command processing\n/// - UI state like autocomplete and notifications\n///\n/// ## Architecture\n/// The ViewModel acts as:\n/// - **BitchatDelegate**: Receives messages and events from BluetoothMeshService\n/// - **State Manager**: Maintains all UI-relevant state with @Published properties\n/// - **Command Processor**: Handles IRC-style commands (/msg, /who, etc.)\n/// - **Message Router**: Directs messages to appropriate chats (public/private)\n///\n/// ## Key Features\n///\n/// ### Message Management\n/// - Batches incoming messages for performance (100ms window)\n/// - Maintains separate public and private message queues\n/// - Limits message history to prevent memory issues (1337 messages)\n/// - Tracks delivery and read receipts\n///\n/// ### Privacy Features\n/// - Ephemeral by design - no persistent message storage\n/// - Supports verified fingerprints for secure communication\n/// - Blocks messages from blocked users\n/// - Emergency wipe capability (triple-tap)\n///\n/// ### User Experience\n/// - Smart autocomplete for mentions and commands\n/// - Unread message indicators\n/// - Connection status tracking\n/// - Favorite peers management\n///\n/// ## Command System\n/// Supports IRC-style commands:\n/// - `/nick `: Change nickname\n/// - `/msg `: Send private message\n/// - `/who`: List connected peers\n/// - `/slap `: Fun interaction\n/// - `/clear`: Clear message history\n/// - `/help`: Show available commands\n///\n/// ## Performance Optimizations\n/// - Message batching reduces UI updates\n/// - Caches expensive computations (RSSI colors, encryption status)\n/// - Debounces autocomplete suggestions\n/// - Efficient peer list management\n///\n/// ## Thread Safety\n/// - All @Published properties trigger UI updates on main thread\n/// - Background operations use proper queue management\n/// - Atomic operations for critical state updates\n///\n/// ## Usage Example\n/// ```swift\n/// let viewModel = ChatViewModel()\n/// viewModel.nickname = \"Alice\"\n/// viewModel.startServices()\n/// viewModel.sendMessage(\"Hello, mesh network!\")\n/// ```\n///\n\nimport Foundation\nimport SwiftUI\nimport Combine\nimport CryptoKit\nimport CommonCrypto\n#if os(iOS)\nimport UIKit\n#endif\n\n/// Manages the application state and business logic for BitChat.\n/// Acts as the primary coordinator between UI components and backend services,\n/// implementing the BitchatDelegate protocol to handle network events.\nclass ChatViewModel: ObservableObject {\n // MARK: - Published Properties\n \n @Published var messages: [BitchatMessage] = []\n private let maxMessages = 1337 // Maximum messages before oldest are removed\n @Published var connectedPeers: [String] = []\n \n // MARK: - Message Batching Properties\n \n // Message batching for performance\n private var pendingMessages: [BitchatMessage] = []\n private var pendingPrivateMessages: [String: [BitchatMessage]] = [:] // peerID -> messages\n private var messageBatchTimer: Timer?\n private let messageBatchInterval: TimeInterval = 0.1 // 100ms batching window\n @Published var nickname: String = \"\" {\n didSet {\n // Trim whitespace whenever nickname is set\n let trimmed = nickname.trimmingCharacters(in: .whitespacesAndNewlines)\n if trimmed != nickname {\n nickname = trimmed\n }\n }\n }\n @Published var isConnected = false\n @Published var privateChats: [String: [BitchatMessage]] = [:] // peerID -> messages\n @Published var selectedPrivateChatPeer: String? = nil\n private var selectedPrivateChatFingerprint: String? = nil // Track by fingerprint for persistence across reconnections\n @Published var unreadPrivateMessages: Set = []\n @Published var autocompleteSuggestions: [String] = []\n @Published var showAutocomplete: Bool = false\n @Published var autocompleteRange: NSRange? = nil\n @Published var selectedAutocompleteIndex: Int = 0\n \n // MARK: - Autocomplete Properties\n \n // Autocomplete optimization\n private let mentionRegex = try? NSRegularExpression(pattern: \"@([a-zA-Z0-9_]*)$\", options: [])\n private var cachedNicknames: [String] = []\n private var lastNicknameUpdate: Date = .distantPast\n \n // Temporary property to fix compilation\n @Published var showPasswordPrompt = false\n \n // MARK: - Services and Storage\n \n var meshService = BluetoothMeshService()\n private let userDefaults = UserDefaults.standard\n private let nicknameKey = \"bitchat.nickname\"\n \n // MARK: - Caches\n \n // Caches for expensive computations\n private var rssiColorCache: [String: Color] = [:] // key: \"\\(rssi)_\\(isDark)\"\n private var encryptionStatusCache: [String: EncryptionStatus] = [:] // key: peerID\n \n // MARK: - Social Features\n \n @Published var favoritePeers: Set = [] // Now stores public key fingerprints instead of peer IDs\n private var peerIDToPublicKeyFingerprint: [String: String] = [:] // Maps ephemeral peer IDs to persistent fingerprints\n private var blockedUsers: Set = [] // Stores public key fingerprints of blocked users\n \n // MARK: - Encryption and Security\n \n // Noise Protocol encryption status\n @Published var peerEncryptionStatus: [String: EncryptionStatus] = [:] // peerID -> encryption status\n @Published var verifiedFingerprints: Set = [] // Set of verified fingerprints\n @Published var showingFingerprintFor: String? = nil // Currently showing fingerprint sheet for peer\n \n // Messages are naturally ephemeral - no persistent storage\n \n // MARK: - Message Delivery Tracking\n \n // Delivery tracking\n private var deliveryTrackerCancellable: AnyCancellable?\n \n // Track sent read receipts to avoid duplicates\n private var sentReadReceipts: Set = [] // messageID set\n \n // MARK: - Initialization\n \n init() {\n loadNickname()\n loadFavorites()\n loadBlockedUsers()\n loadVerifiedFingerprints()\n meshService.delegate = self\n \n // Log startup info\n \n // Log fingerprint after a delay to ensure encryption service is ready\n DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in\n if let self = self {\n _ = self.getMyFingerprint()\n }\n }\n \n // Start mesh service immediately\n meshService.startServices()\n \n // Set up message retry service\n MessageRetryService.shared.meshService = meshService\n \n // Set up Noise encryption callbacks\n setupNoiseCallbacks()\n \n // Request notification permission\n NotificationService.shared.requestAuthorization()\n \n // Subscribe to delivery status updates\n deliveryTrackerCancellable = DeliveryTracker.shared.deliveryStatusUpdated\n .receive(on: DispatchQueue.main)\n .sink { [weak self] (messageID, status) in\n self?.updateMessageDeliveryStatus(messageID, status: status)\n }\n \n // Listen for retry notifications\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(handleRetryMessage),\n name: Notification.Name(\"bitchat.retryMessage\"),\n object: nil\n )\n \n // When app becomes active, send read receipts for visible messages\n #if os(macOS)\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appDidBecomeActive),\n name: NSApplication.didBecomeActiveNotification,\n object: nil\n )\n \n // Add app lifecycle observers to save data\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillResignActive),\n name: NSApplication.willResignActiveNotification,\n object: nil\n )\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillTerminate),\n name: NSApplication.willTerminateNotification,\n object: nil\n )\n #else\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appDidBecomeActive),\n name: UIApplication.didBecomeActiveNotification,\n object: nil\n )\n \n // Add screenshot detection for iOS\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(userDidTakeScreenshot),\n name: UIApplication.userDidTakeScreenshotNotification,\n object: nil\n )\n \n // Add app lifecycle observers to save data\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillResignActive),\n name: UIApplication.willResignActiveNotification,\n object: nil\n )\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillTerminate),\n name: UIApplication.willTerminateNotification,\n object: nil\n )\n #endif\n }\n \n // MARK: - Deinitialization\n \n deinit {\n // Clean up timer\n messageBatchTimer?.invalidate()\n \n // Force immediate save\n userDefaults.synchronize()\n }\n \n // MARK: - Nickname Management\n \n private func loadNickname() {\n if let savedNickname = userDefaults.string(forKey: nicknameKey) {\n // Trim whitespace when loading\n nickname = savedNickname.trimmingCharacters(in: .whitespacesAndNewlines)\n } else {\n nickname = \"anon\\(Int.random(in: 1000...9999))\"\n saveNickname()\n }\n }\n \n func saveNickname() {\n userDefaults.set(nickname, forKey: nicknameKey)\n userDefaults.synchronize() // Force immediate save\n \n // Send announce with new nickname to all peers\n meshService.sendBroadcastAnnounce()\n }\n \n func validateAndSaveNickname() {\n // Trim whitespace from nickname\n let trimmed = nickname.trimmingCharacters(in: .whitespacesAndNewlines)\n \n // Check if nickname is empty after trimming\n if trimmed.isEmpty {\n nickname = \"anon\\(Int.random(in: 1000...9999))\"\n } else {\n nickname = trimmed\n }\n saveNickname()\n }\n \n // MARK: - Favorites Management\n \n private func loadFavorites() {\n // Load favorites from secure storage\n favoritePeers = SecureIdentityStateManager.shared.getFavorites()\n }\n \n private func saveFavorites() {\n // Favorites are now saved automatically in SecureIdentityStateManager\n // This method is kept for compatibility\n }\n \n // MARK: - Blocked Users Management\n \n private func loadBlockedUsers() {\n // Load blocked users from secure storage\n let allIdentities = SecureIdentityStateManager.shared.getAllSocialIdentities()\n blockedUsers = Set(allIdentities.filter { $0.isBlocked }.map { $0.fingerprint })\n }\n \n private func saveBlockedUsers() {\n // Blocked users are now saved automatically in SecureIdentityStateManager\n // This method is kept for compatibility\n }\n \n \n func toggleFavorite(peerID: String) {\n // First try to get fingerprint from mesh service (supports peer ID rotation)\n var fingerprint: String? = meshService.getFingerprint(for: peerID)\n \n // Fallback to local mapping if not found in mesh service\n if fingerprint == nil {\n fingerprint = peerIDToPublicKeyFingerprint[peerID]\n }\n \n guard let fp = fingerprint else {\n return\n }\n \n let isFavorite = SecureIdentityStateManager.shared.isFavorite(fingerprint: fp)\n SecureIdentityStateManager.shared.setFavorite(fp, isFavorite: !isFavorite)\n \n // Update local set for UI\n if isFavorite {\n favoritePeers.remove(fp)\n } else {\n favoritePeers.insert(fp)\n }\n }\n \n func isFavorite(peerID: String) -> Bool {\n // First try to get fingerprint from mesh service (supports peer ID rotation)\n var fingerprint: String? = meshService.getFingerprint(for: peerID)\n \n // Fallback to local mapping if not found in mesh service\n if fingerprint == nil {\n fingerprint = peerIDToPublicKeyFingerprint[peerID]\n }\n \n guard let fp = fingerprint else {\n return false\n }\n \n return SecureIdentityStateManager.shared.isFavorite(fingerprint: fp)\n }\n \n // MARK: - Public Key and Identity Management\n \n // Called when we receive a peer's public key\n func registerPeerPublicKey(peerID: String, publicKeyData: Data) {\n // Create a fingerprint from the public key (full SHA256, not truncated)\n let fingerprintStr = SHA256.hash(data: publicKeyData)\n .compactMap { String(format: \"%02x\", $0) }\n .joined()\n \n // Only register if not already registered\n if peerIDToPublicKeyFingerprint[peerID] != fingerprintStr {\n peerIDToPublicKeyFingerprint[peerID] = fingerprintStr\n }\n \n // Update identity state manager with handshake completion\n SecureIdentityStateManager.shared.updateHandshakeState(peerID: peerID, state: .completed(fingerprint: fingerprintStr))\n \n // Update encryption status now that we have the fingerprint\n updateEncryptionStatus(for: peerID)\n \n // Check if we have a claimed nickname for this peer\n let peerNicknames = meshService.getPeerNicknames()\n if let nickname = peerNicknames[peerID], nickname != \"Unknown\" && nickname != \"anon\\(peerID.prefix(4))\" {\n // Update or create social identity with the claimed nickname\n if var identity = SecureIdentityStateManager.shared.getSocialIdentity(for: fingerprintStr) {\n identity.claimedNickname = nickname\n SecureIdentityStateManager.shared.updateSocialIdentity(identity)\n } else {\n let newIdentity = SocialIdentity(\n fingerprint: fingerprintStr,\n localPetname: nil,\n claimedNickname: nickname,\n trustLevel: .casual,\n isFavorite: false,\n isBlocked: false,\n notes: nil\n )\n SecureIdentityStateManager.shared.updateSocialIdentity(newIdentity)\n }\n }\n \n // Check if this peer is the one we're in a private chat with\n updatePrivateChatPeerIfNeeded()\n }\n \n private func isPeerBlocked(_ peerID: String) -> Bool {\n // Check if we have the public key fingerprint for this peer\n if let fingerprint = peerIDToPublicKeyFingerprint[peerID] {\n return SecureIdentityStateManager.shared.isBlocked(fingerprint: fingerprint)\n }\n \n // Try to get fingerprint from mesh service\n if let fingerprint = meshService.getPeerFingerprint(peerID) {\n return SecureIdentityStateManager.shared.isBlocked(fingerprint: fingerprint)\n }\n \n return false\n }\n \n // Helper method to find current peer ID for a fingerprint\n private func getCurrentPeerIDForFingerprint(_ fingerprint: String) -> String? {\n // Search through all connected peers to find the one with matching fingerprint\n for peerID in connectedPeers {\n if let mappedFingerprint = peerIDToPublicKeyFingerprint[peerID],\n mappedFingerprint == fingerprint {\n return peerID\n }\n }\n return nil\n }\n \n // Helper method to update selectedPrivateChatPeer if fingerprint matches\n private func updatePrivateChatPeerIfNeeded() {\n guard let chatFingerprint = selectedPrivateChatFingerprint else { return }\n \n // Find current peer ID for the fingerprint\n if let currentPeerID = getCurrentPeerIDForFingerprint(chatFingerprint) {\n // Update the selected peer if it's different\n if let oldPeerID = selectedPrivateChatPeer, oldPeerID != currentPeerID {\n // Migrate messages from old peer ID to new peer ID\n if let oldMessages = privateChats[oldPeerID] {\n if privateChats[currentPeerID] == nil {\n privateChats[currentPeerID] = []\n }\n privateChats[currentPeerID]?.append(contentsOf: oldMessages)\n trimPrivateChatMessagesIfNeeded(for: currentPeerID)\n privateChats.removeValue(forKey: oldPeerID)\n }\n \n // Migrate unread status\n if unreadPrivateMessages.contains(oldPeerID) {\n unreadPrivateMessages.remove(oldPeerID)\n unreadPrivateMessages.insert(currentPeerID)\n }\n \n selectedPrivateChatPeer = currentPeerID\n } else if selectedPrivateChatPeer == nil {\n // Just set the peer ID if we don't have one\n selectedPrivateChatPeer = currentPeerID\n }\n \n // Clear unread messages for the current peer ID\n unreadPrivateMessages.remove(currentPeerID)\n }\n }\n \n // MARK: - Message Sending\n \n /// Sends a message through the BitChat network.\n /// - Parameter content: The message content to send\n /// - Note: Automatically handles command processing if content starts with '/'\n /// Routes to private chat if one is selected, otherwise broadcasts\n func sendMessage(_ content: String) {\n guard !content.isEmpty else { return }\n \n // Check for commands\n if content.hasPrefix(\"/\") {\n handleCommand(content)\n return\n }\n \n if selectedPrivateChatPeer != nil {\n // Update peer ID in case it changed due to reconnection\n updatePrivateChatPeerIfNeeded()\n \n if let selectedPeer = selectedPrivateChatPeer {\n // Send as private message\n sendPrivateMessage(content, to: selectedPeer)\n } else {\n }\n } else {\n // Parse mentions from the content\n let mentions = parseMentions(from: content)\n \n // Add message to local display\n let message = BitchatMessage(\n sender: nickname,\n content: content,\n timestamp: Date(),\n isRelay: false,\n originalSender: nil,\n isPrivate: false,\n recipientNickname: nil,\n senderPeerID: meshService.myPeerID,\n mentions: mentions.isEmpty ? nil : mentions\n )\n \n // Add to main messages immediately for user feedback\n messages.append(message)\n trimMessagesIfNeeded()\n \n // Force immediate UI update for user's own messages\n objectWillChange.send()\n \n // Send via mesh with mentions\n meshService.sendMessage(content, mentions: mentions)\n }\n }\n \n /// Sends an encrypted private message to a specific peer.\n /// - Parameters:\n /// - content: The message content to encrypt and send\n /// - peerID: The recipient's peer ID\n /// - Note: Automatically establishes Noise encryption if not already active\n func sendPrivateMessage(_ content: String, to peerID: String) {\n guard !content.isEmpty else { return }\n guard let recipientNickname = meshService.getPeerNicknames()[peerID] else { \n return \n }\n \n // Check if the recipient is blocked\n if isPeerBlocked(peerID) {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot send message to \\(recipientNickname): user is blocked.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n return\n }\n \n // IMPORTANT: When sending a message, it means we're viewing this chat\n // Send read receipts for any delivered messages from this peer\n markPrivateMessagesAsRead(from: peerID)\n \n // Create the message locally\n let message = BitchatMessage(\n sender: nickname,\n content: content,\n timestamp: Date(),\n isRelay: false,\n originalSender: nil,\n isPrivate: true,\n recipientNickname: recipientNickname,\n senderPeerID: meshService.myPeerID,\n deliveryStatus: .sending\n )\n \n // Add to our private chat history\n if privateChats[peerID] == nil {\n privateChats[peerID] = []\n }\n privateChats[peerID]?.append(message)\n trimPrivateChatMessagesIfNeeded(for: peerID)\n \n // Track the message for delivery confirmation\n let isFavorite = isFavorite(peerID: peerID)\n DeliveryTracker.shared.trackMessage(message, recipientID: peerID, recipientNickname: recipientNickname, isFavorite: isFavorite)\n \n // Immediate UI update for user's own messages\n objectWillChange.send()\n \n // Send via mesh with the same message ID\n meshService.sendPrivateMessage(content, to: peerID, recipientNickname: recipientNickname, messageID: message.id)\n }\n \n // MARK: - Private Chat Management\n \n /// Initiates a private chat session with a peer.\n /// - Parameter peerID: The peer's ID to start chatting with\n /// - Note: Switches the UI to private chat mode and loads message history\n func startPrivateChat(with peerID: String) {\n let peerNickname = meshService.getPeerNicknames()[peerID] ?? \"unknown\"\n \n // Check if the peer is blocked\n if isPeerBlocked(peerID) {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot start chat with \\(peerNickname): user is blocked.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n return\n }\n \n // Trigger handshake if we don't have a session yet\n let sessionState = meshService.getNoiseSessionState(for: peerID)\n switch sessionState {\n case .none, .failed:\n // Initiate handshake when opening PM\n meshService.triggerHandshake(with: peerID)\n default:\n break\n }\n \n selectedPrivateChatPeer = peerID\n // Also track by fingerprint for persistence across reconnections\n selectedPrivateChatFingerprint = peerIDToPublicKeyFingerprint[peerID]\n unreadPrivateMessages.remove(peerID)\n \n // Check if we need to migrate messages from an old peer ID\n // This happens when peer IDs change between sessions\n if privateChats[peerID] == nil || privateChats[peerID]?.isEmpty == true {\n \n // Look for messages from this nickname under other peer IDs\n var migratedMessages: [BitchatMessage] = []\n var oldPeerIDsToRemove: [String] = []\n \n for (oldPeerID, messages) in privateChats {\n if oldPeerID != peerID {\n // Check if any messages in this chat are from the peer's nickname\n // Check if this chat contains messages with this peer\n let messagesWithPeer = messages.filter { msg in\n // Message is FROM the peer to us\n (msg.sender == peerNickname && msg.sender != nickname) ||\n // OR message is FROM us TO the peer\n (msg.sender == nickname && (msg.recipientNickname == peerNickname || \n // Also check if this was a private message in a chat that only has us and one other person\n (msg.isPrivate && messages.allSatisfy { m in \n m.sender == nickname || m.sender == peerNickname \n })))\n }\n \n if !messagesWithPeer.isEmpty {\n \n // Check if ALL messages in this chat are between us and this peer\n let allMessagesAreWithPeer = messages.allSatisfy { msg in\n (msg.sender == peerNickname || msg.sender == nickname) &&\n (msg.recipientNickname == nil || msg.recipientNickname == peerNickname || msg.recipientNickname == nickname)\n }\n \n if allMessagesAreWithPeer {\n // This entire chat history belongs to this peer, migrate it all\n migratedMessages.append(contentsOf: messages)\n oldPeerIDsToRemove.append(oldPeerID)\n }\n }\n }\n }\n \n // Remove old peer ID entries that were fully migrated\n for oldPeerID in oldPeerIDsToRemove {\n privateChats.removeValue(forKey: oldPeerID)\n unreadPrivateMessages.remove(oldPeerID)\n }\n \n // Initialize chat history with migrated messages if any\n if !migratedMessages.isEmpty {\n privateChats[peerID] = migratedMessages.sorted { $0.timestamp < $1.timestamp }\n trimPrivateChatMessagesIfNeeded(for: peerID)\n } else {\n privateChats[peerID] = []\n }\n }\n \n _ = privateChats[peerID] ?? []\n \n // Send read receipts for unread messages from this peer\n // Add a small delay to ensure UI has updated\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [weak self] in\n self?.markPrivateMessagesAsRead(from: peerID)\n }\n \n // Also try immediately in case messages are already there\n markPrivateMessagesAsRead(from: peerID)\n }\n \n func endPrivateChat() {\n selectedPrivateChatPeer = nil\n selectedPrivateChatFingerprint = nil\n }\n \n // MARK: - Message Retry Handling\n \n @objc private func handleRetryMessage(_ notification: Notification) {\n guard let messageID = notification.userInfo?[\"messageID\"] as? String else { return }\n \n // Find the message to retry\n if let message = messages.first(where: { $0.id == messageID }) {\n SecureLogger.log(\"Retrying message \\(messageID) to \\(message.recipientNickname ?? \"unknown\")\", \n category: SecureLogger.session, level: .info)\n \n // Resend the message through mesh service\n if message.isPrivate,\n let peerID = getPeerIDForNickname(message.recipientNickname ?? \"\") {\n // Update status to sending\n updateMessageDeliveryStatus(messageID, status: .sending)\n \n // Resend via mesh service\n meshService.sendMessage(message.content, \n mentions: message.mentions ?? [], \n to: peerID,\n messageID: messageID,\n timestamp: message.timestamp)\n }\n }\n }\n \n // MARK: - App Lifecycle\n \n @objc private func appDidBecomeActive() {\n // When app becomes active, send read receipts for visible private chat\n if let peerID = selectedPrivateChatPeer {\n // Try immediately\n self.markPrivateMessagesAsRead(from: peerID)\n // And again with a delay\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {\n self.markPrivateMessagesAsRead(from: peerID)\n }\n }\n }\n \n @objc private func userDidTakeScreenshot() {\n // Send screenshot notification based on current context\n let screenshotMessage = \"* \\(nickname) took a screenshot *\"\n \n if let peerID = selectedPrivateChatPeer {\n // In private chat - send to the other person\n if let peerNickname = meshService.getPeerNicknames()[peerID] {\n // Only send screenshot notification if we have an established session\n // This prevents triggering handshake requests for screenshot notifications\n let sessionState = meshService.getNoiseSessionState(for: peerID)\n switch sessionState {\n case .established:\n // Send the message directly without going through sendPrivateMessage to avoid local echo\n meshService.sendPrivateMessage(screenshotMessage, to: peerID, recipientNickname: peerNickname)\n default:\n // Don't send screenshot notification if no session exists\n SecureLogger.log(\"Skipping screenshot notification to \\(peerID) - no established session\", category: SecureLogger.security, level: .debug)\n }\n }\n \n // Show local notification immediately as system message\n let localNotification = BitchatMessage(\n sender: \"system\",\n content: \"you took a screenshot\",\n timestamp: Date(),\n isRelay: false,\n originalSender: nil,\n isPrivate: true,\n recipientNickname: meshService.getPeerNicknames()[peerID],\n senderPeerID: meshService.myPeerID\n )\n if privateChats[peerID] == nil {\n privateChats[peerID] = []\n }\n privateChats[peerID]?.append(localNotification)\n trimPrivateChatMessagesIfNeeded(for: peerID)\n \n } else {\n // In public chat - send to everyone\n meshService.sendMessage(screenshotMessage, mentions: [])\n \n // Show local notification immediately as system message\n let localNotification = BitchatMessage(\n sender: \"system\",\n content: \"you took a screenshot\",\n timestamp: Date(),\n isRelay: false\n )\n // System messages can be batched\n addMessageToBatch(localNotification)\n }\n }\n \n @objc private func appWillResignActive() {\n // Flush any pending messages when app goes to background\n flushMessageBatchImmediately()\n \n userDefaults.synchronize()\n }\n \n @objc func applicationWillTerminate() {\n // Flush any pending messages immediately\n flushMessageBatchImmediately()\n \n // Force save any pending identity changes (verifications, favorites, etc)\n SecureIdentityStateManager.shared.forceSave()\n \n // Verify identity key is still there\n _ = KeychainManager.shared.verifyIdentityKeyExists()\n \n userDefaults.synchronize()\n \n // Verify identity key after save\n _ = KeychainManager.shared.verifyIdentityKeyExists()\n }\n \n @objc private func appWillTerminate() {\n // Flush any pending messages immediately\n flushMessageBatchImmediately()\n \n userDefaults.synchronize()\n }\n \n func markPrivateMessagesAsRead(from peerID: String) {\n // Get the nickname for this peer\n let peerNickname = meshService.getPeerNicknames()[peerID] ?? \"\"\n \n // First ensure we have the latest messages (in case of migration)\n if let messages = privateChats[peerID], !messages.isEmpty {\n } else {\n \n // Look through ALL private chats to find messages from this nickname\n for (_, chatMessages) in privateChats {\n let relevantMessages = chatMessages.filter { msg in\n msg.sender == peerNickname && msg.sender != nickname\n }\n if !relevantMessages.isEmpty {\n }\n }\n }\n \n guard let messages = privateChats[peerID], !messages.isEmpty else { \n return \n }\n \n \n // Find messages from the peer that haven't been read yet\n var readReceiptsSent = 0\n for (_, message) in messages.enumerated() {\n // Only send read receipts for messages from the other peer (not our own)\n // Check multiple conditions to ensure we catch all messages from the peer\n let isOurMessage = message.sender == nickname\n let isFromPeerByNickname = !peerNickname.isEmpty && message.sender == peerNickname\n let isFromPeerByID = message.senderPeerID == peerID\n let isPrivateToUs = message.isPrivate && message.recipientNickname == nickname\n \n // This is a message FROM the peer if it's not from us AND (matches nickname OR peer ID OR is private to us)\n let isFromPeer = !isOurMessage && (isFromPeerByNickname || isFromPeerByID || isPrivateToUs)\n \n if message.id == message.id { // Always true, for debugging\n }\n \n if isFromPeer {\n if let status = message.deliveryStatus {\n switch status {\n case .sent, .delivered:\n // Create and send read receipt for sent or delivered messages\n // Check if we've already sent a receipt for this message\n if !sentReadReceipts.contains(message.id) {\n // Send to the CURRENT peer ID, not the old senderPeerID which may have changed\n let receipt = ReadReceipt(\n originalMessageID: message.id,\n readerID: meshService.myPeerID,\n readerNickname: nickname\n )\n meshService.sendReadReceipt(receipt, to: peerID)\n sentReadReceipts.insert(message.id)\n readReceiptsSent += 1\n } else {\n }\n case .read:\n // Already read, no need to send another receipt\n break\n default:\n // Message not yet delivered, can't mark as read\n break\n }\n } else {\n // No delivery status - this might be an older message\n // Send read receipt anyway for backwards compatibility\n if !sentReadReceipts.contains(message.id) {\n let receipt = ReadReceipt(\n originalMessageID: message.id,\n readerID: meshService.myPeerID,\n readerNickname: nickname\n )\n meshService.sendReadReceipt(receipt, to: peerID)\n sentReadReceipts.insert(message.id)\n readReceiptsSent += 1\n } else {\n }\n }\n } else {\n }\n }\n \n }\n \n func getPrivateChatMessages(for peerID: String) -> [BitchatMessage] {\n let messages = privateChats[peerID] ?? []\n if !messages.isEmpty {\n }\n return messages\n }\n \n func getPeerIDForNickname(_ nickname: String) -> String? {\n let nicknames = meshService.getPeerNicknames()\n return nicknames.first(where: { $0.value == nickname })?.key\n }\n \n \n // MARK: - Emergency Functions\n \n // PANIC: Emergency data clearing for activist safety\n func panicClearAllData() {\n // Flush any pending messages immediately before clearing\n flushMessageBatchImmediately()\n \n // Clear all messages\n messages.removeAll()\n privateChats.removeAll()\n unreadPrivateMessages.removeAll()\n \n // First run aggressive cleanup to get rid of all legacy items\n _ = KeychainManager.shared.aggressiveCleanupLegacyItems()\n \n // Then delete all current keychain data\n _ = KeychainManager.shared.deleteAllKeychainData()\n \n // Clear UserDefaults identity fallbacks\n userDefaults.removeObject(forKey: \"bitchat.noiseIdentityKey\")\n userDefaults.removeObject(forKey: \"bitchat.messageRetentionKey\")\n \n // Clear verified fingerprints\n verifiedFingerprints.removeAll()\n // Verified fingerprints are cleared when identity data is cleared below\n \n // Clear message retry queue\n MessageRetryService.shared.clearRetryQueue()\n \n \n // Reset nickname to anonymous\n nickname = \"anon\\(Int.random(in: 1000...9999))\"\n saveNickname()\n \n // Clear favorites\n favoritePeers.removeAll()\n peerIDToPublicKeyFingerprint.removeAll()\n \n // Clear identity data from secure storage\n SecureIdentityStateManager.shared.clearAllIdentityData()\n \n // Clear autocomplete state\n autocompleteSuggestions.removeAll()\n showAutocomplete = false\n autocompleteRange = nil\n selectedAutocompleteIndex = 0\n \n // Clear selected private chat\n selectedPrivateChatPeer = nil\n selectedPrivateChatFingerprint = nil\n \n // Clear read receipt tracking\n sentReadReceipts.removeAll()\n \n // Clear all caches\n invalidateEncryptionCache()\n invalidateRSSIColorCache()\n \n // Disconnect from all peers and clear persistent identity\n // This will force creation of a new identity (new fingerprint) on next launch\n meshService.emergencyDisconnectAll()\n \n // Force immediate UserDefaults synchronization\n userDefaults.synchronize()\n \n // Force UI update\n objectWillChange.send()\n \n }\n \n \n \n // MARK: - Formatting Helpers\n \n func formatTimestamp(_ date: Date) -> String {\n let formatter = DateFormatter()\n formatter.dateFormat = \"HH:mm:ss\"\n return formatter.string(from: date)\n }\n \n func getRSSIColor(rssi: Int, colorScheme: ColorScheme) -> Color {\n let isDark = colorScheme == .dark\n let cacheKey = \"\\(rssi)_\\(isDark)\"\n \n // Check cache first\n if let cachedColor = rssiColorCache[cacheKey] {\n return cachedColor\n }\n \n // RSSI typically ranges from -30 (excellent) to -90 (poor)\n // We'll map this to colors from green (strong) to red (weak)\n \n let color: Color\n if rssi >= -50 {\n // Excellent signal: bright green\n color = isDark ? Color(red: 0.0, green: 1.0, blue: 0.0) : Color(red: 0.0, green: 0.7, blue: 0.0)\n } else if rssi >= -60 {\n // Good signal: green-yellow\n color = isDark ? Color(red: 0.5, green: 1.0, blue: 0.0) : Color(red: 0.3, green: 0.7, blue: 0.0)\n } else if rssi >= -70 {\n // Fair signal: yellow\n color = isDark ? Color(red: 1.0, green: 1.0, blue: 0.0) : Color(red: 0.7, green: 0.7, blue: 0.0)\n } else if rssi >= -80 {\n // Weak signal: orange\n color = isDark ? Color(red: 1.0, green: 0.6, blue: 0.0) : Color(red: 0.8, green: 0.4, blue: 0.0)\n } else {\n // Poor signal: red\n color = isDark ? Color(red: 1.0, green: 0.2, blue: 0.2) : Color(red: 0.8, green: 0.0, blue: 0.0)\n }\n \n // Cache the result\n rssiColorCache[cacheKey] = color\n return color\n }\n \n // MARK: - Autocomplete\n \n func updateAutocomplete(for text: String, cursorPosition: Int) {\n // Quick early exit for empty text\n guard cursorPosition > 0 else {\n if showAutocomplete {\n showAutocomplete = false\n autocompleteSuggestions = []\n autocompleteRange = nil\n }\n return\n }\n \n // Find @ symbol before cursor\n let beforeCursor = String(text.prefix(cursorPosition))\n \n // Use cached regex\n guard let regex = mentionRegex,\n let match = regex.firstMatch(in: beforeCursor, options: [], range: NSRange(location: 0, length: beforeCursor.count)) else {\n if showAutocomplete {\n showAutocomplete = false\n autocompleteSuggestions = []\n autocompleteRange = nil\n }\n return\n }\n \n // Extract the partial nickname\n let partialRange = match.range(at: 1)\n guard let range = Range(partialRange, in: beforeCursor) else {\n if showAutocomplete {\n showAutocomplete = false\n autocompleteSuggestions = []\n autocompleteRange = nil\n }\n return\n }\n \n let partial = String(beforeCursor[range]).lowercased()\n \n // Update cached nicknames only if peer list changed (check every 1 second max)\n let now = Date()\n if now.timeIntervalSince(lastNicknameUpdate) > 1.0 || cachedNicknames.isEmpty {\n let peerNicknames = meshService.getPeerNicknames()\n cachedNicknames = Array(peerNicknames.values).sorted()\n lastNicknameUpdate = now\n }\n \n // Filter suggestions using cached nicknames\n let suggestions = cachedNicknames.filter { nick in\n nick.lowercased().hasPrefix(partial)\n }\n \n // Batch UI updates\n if !suggestions.isEmpty {\n // Only update if suggestions changed\n if autocompleteSuggestions != suggestions {\n autocompleteSuggestions = suggestions\n }\n if !showAutocomplete {\n showAutocomplete = true\n }\n if autocompleteRange != match.range(at: 0) {\n autocompleteRange = match.range(at: 0)\n }\n selectedAutocompleteIndex = 0\n } else {\n if showAutocomplete {\n showAutocomplete = false\n autocompleteSuggestions = []\n autocompleteRange = nil\n selectedAutocompleteIndex = 0\n }\n }\n }\n \n func completeNickname(_ nickname: String, in text: inout String) -> Int {\n guard let range = autocompleteRange else { return text.count }\n \n // Replace the @partial with @nickname\n let nsText = text as NSString\n let newText = nsText.replacingCharacters(in: range, with: \"@\\(nickname) \")\n text = newText\n \n // Hide autocomplete\n showAutocomplete = false\n autocompleteSuggestions = []\n autocompleteRange = nil\n selectedAutocompleteIndex = 0\n \n // Return new cursor position (after the space)\n return range.location + nickname.count + 2\n }\n \n // MARK: - Message Formatting\n \n func getSenderColor(for message: BitchatMessage, colorScheme: ColorScheme) -> Color {\n let isDark = colorScheme == .dark\n let primaryColor = isDark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n \n // Always use the same color for all senders - no RSSI-based coloring\n return primaryColor\n }\n \n \n func formatMessageContent(_ message: BitchatMessage, colorScheme: ColorScheme) -> AttributedString {\n let isDark = colorScheme == .dark\n let contentText = message.content\n var processedContent = AttributedString()\n \n // Regular expressions for mentions and hashtags\n let mentionPattern = \"@([a-zA-Z0-9_]+)\"\n let hashtagPattern = \"#([a-zA-Z0-9_]+)\"\n \n let mentionRegex = try? NSRegularExpression(pattern: mentionPattern, options: [])\n let hashtagRegex = try? NSRegularExpression(pattern: hashtagPattern, options: [])\n \n let mentionMatches = mentionRegex?.matches(in: contentText, options: [], range: NSRange(location: 0, length: contentText.count)) ?? []\n let hashtagMatches = hashtagRegex?.matches(in: contentText, options: [], range: NSRange(location: 0, length: contentText.count)) ?? []\n \n // Combine and sort all matches\n var allMatches: [(range: NSRange, type: String)] = []\n for match in mentionMatches {\n allMatches.append((match.range(at: 0), \"mention\"))\n }\n for match in hashtagMatches {\n allMatches.append((match.range(at: 0), \"hashtag\"))\n }\n allMatches.sort { $0.range.location < $1.range.location }\n \n var lastEndIndex = contentText.startIndex\n \n for (matchRange, matchType) in allMatches {\n // Add text before the match\n if let range = Range(matchRange, in: contentText) {\n let beforeText = String(contentText[lastEndIndex.. AttributedString {\n // Check cache first\n let isDark = colorScheme == .dark\n if let cachedText = message.getCachedFormattedText(isDark: isDark) {\n return cachedText\n }\n \n // Not cached, format the message\n var result = AttributedString()\n \n let primaryColor = isDark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n let secondaryColor = primaryColor.opacity(0.7)\n \n // Timestamp\n let timestamp = AttributedString(\"[\\(formatTimestamp(message.timestamp))] \")\n var timestampStyle = AttributeContainer()\n timestampStyle.foregroundColor = message.sender == \"system\" ? Color.gray : secondaryColor\n timestampStyle.font = .system(size: 12, design: .monospaced)\n result.append(timestamp.mergingAttributes(timestampStyle))\n \n if message.sender != \"system\" {\n // Sender\n let sender = AttributedString(\"<@\\(message.sender)> \")\n var senderStyle = AttributeContainer()\n \n // Use consistent color for all senders\n senderStyle.foregroundColor = primaryColor\n // Bold the user's own nickname\n let fontWeight: Font.Weight = message.sender == nickname ? .bold : .medium\n senderStyle.font = .system(size: 14, weight: fontWeight, design: .monospaced)\n result.append(sender.mergingAttributes(senderStyle))\n \n // Process content with hashtags and mentions\n let content = message.content\n \n let hashtagPattern = \"#([a-zA-Z0-9_]+)\"\n let mentionPattern = \"@([a-zA-Z0-9_]+)\"\n \n let hashtagRegex = try? NSRegularExpression(pattern: hashtagPattern, options: [])\n let mentionRegex = try? NSRegularExpression(pattern: mentionPattern, options: [])\n \n // Use NSDataDetector for URL detection\n let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)\n \n let hashtagMatches = hashtagRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n let mentionMatches = mentionRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n let urlMatches = detector?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n \n // Combine and sort matches\n var allMatches: [(range: NSRange, type: String)] = []\n for match in hashtagMatches {\n allMatches.append((match.range(at: 0), \"hashtag\"))\n }\n for match in mentionMatches {\n allMatches.append((match.range(at: 0), \"mention\"))\n }\n for match in urlMatches {\n allMatches.append((match.range, \"url\"))\n }\n allMatches.sort { $0.range.location < $1.range.location }\n \n // Build content with styling\n var lastEnd = content.startIndex\n let isMentioned = message.mentions?.contains(nickname) ?? false\n \n for (range, type) in allMatches {\n // Add text before match\n if let nsRange = Range(range, in: content) {\n let beforeText = String(content[lastEnd.. AttributedString {\n var result = AttributedString()\n \n let isDark = colorScheme == .dark\n let primaryColor = isDark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n let secondaryColor = primaryColor.opacity(0.7)\n \n let timestamp = AttributedString(\"[\\(formatTimestamp(message.timestamp))] \")\n var timestampStyle = AttributeContainer()\n timestampStyle.foregroundColor = message.sender == \"system\" ? Color.gray : secondaryColor\n timestampStyle.font = .system(size: 12, design: .monospaced)\n result.append(timestamp.mergingAttributes(timestampStyle))\n \n if message.sender == \"system\" {\n let content = AttributedString(\"* \\(message.content) *\")\n var contentStyle = AttributeContainer()\n contentStyle.foregroundColor = Color.gray\n contentStyle.font = .system(size: 12, design: .monospaced).italic()\n result.append(content.mergingAttributes(contentStyle))\n } else {\n let sender = AttributedString(\"<\\(message.sender)> \")\n var senderStyle = AttributeContainer()\n \n // Use consistent color for all senders\n senderStyle.foregroundColor = primaryColor\n // Bold the user's own nickname\n let fontWeight: Font.Weight = message.sender == nickname ? .bold : .medium\n senderStyle.font = .system(size: 12, weight: fontWeight, design: .monospaced)\n result.append(sender.mergingAttributes(senderStyle))\n \n \n // Process content to highlight mentions\n let contentText = message.content\n var processedContent = AttributedString()\n \n // Regular expression to find @mentions\n let pattern = \"@([a-zA-Z0-9_]+)\"\n let regex = try? NSRegularExpression(pattern: pattern, options: [])\n let matches = regex?.matches(in: contentText, options: [], range: NSRange(location: 0, length: contentText.count)) ?? []\n \n var lastEndIndex = contentText.startIndex\n \n for match in matches {\n // Add text before the mention\n if let range = Range(match.range(at: 0), in: contentText) {\n let beforeText = String(contentText[lastEndIndex.. EncryptionStatus {\n // Check cache first\n if let cachedStatus = encryptionStatusCache[peerID] {\n return cachedStatus\n }\n \n // This must be a pure function - no state mutations allowed\n // to avoid SwiftUI update loops\n \n let sessionState = meshService.getNoiseSessionState(for: peerID)\n let storedStatus = peerEncryptionStatus[peerID]\n \n let status: EncryptionStatus\n \n // Determine status based on session state\n switch sessionState {\n case .established:\n // We have encryption, now check if it's verified\n if let fingerprint = getFingerprint(for: peerID) {\n if verifiedFingerprints.contains(fingerprint) {\n status = .noiseVerified\n } else {\n status = .noiseSecured\n }\n } else {\n // We have a session but no fingerprint yet - still secured\n status = .noiseSecured\n }\n case .handshaking, .handshakeQueued:\n // Currently establishing encryption\n status = .noiseHandshaking\n case .none:\n // No handshake attempted\n status = .noHandshake\n case .failed:\n // Handshake failed - show broken lock\n status = .none\n }\n \n // Cache the result\n encryptionStatusCache[peerID] = status\n \n // Only log occasionally to avoid spam\n if Int.random(in: 0..<100) == 0 {\n SecureLogger.log(\"getEncryptionStatus for \\(peerID): sessionState=\\(sessionState), stored=\\(String(describing: storedStatus)), final=\\(status)\", category: SecureLogger.security, level: .debug)\n }\n \n return status\n }\n \n // Clear caches when data changes\n private func invalidateEncryptionCache(for peerID: String? = nil) {\n if let peerID = peerID {\n encryptionStatusCache.removeValue(forKey: peerID)\n } else {\n encryptionStatusCache.removeAll()\n }\n }\n \n private func invalidateRSSIColorCache() {\n rssiColorCache.removeAll()\n }\n \n // MARK: - Message Batching\n \n private func trimMessagesIfNeeded() {\n if messages.count > maxMessages {\n let removeCount = messages.count - maxMessages\n messages.removeFirst(removeCount)\n }\n }\n \n private func trimPrivateChatMessagesIfNeeded(for peerID: String) {\n if let count = privateChats[peerID]?.count, count > maxMessages {\n let removeCount = count - maxMessages\n privateChats[peerID]?.removeFirst(removeCount)\n }\n }\n \n private func addMessageToBatch(_ message: BitchatMessage) {\n pendingMessages.append(message)\n scheduleBatchFlush()\n }\n \n private func addPrivateMessageToBatch(_ message: BitchatMessage, for peerID: String) {\n if pendingPrivateMessages[peerID] == nil {\n pendingPrivateMessages[peerID] = []\n }\n pendingPrivateMessages[peerID]?.append(message)\n scheduleBatchFlush()\n }\n \n private func scheduleBatchFlush() {\n // Cancel existing timer\n messageBatchTimer?.invalidate()\n \n // Schedule new flush\n messageBatchTimer = Timer.scheduledTimer(withTimeInterval: messageBatchInterval, repeats: false) { [weak self] _ in\n self?.flushMessageBatch()\n }\n }\n \n ", "suffix_code": "\n \n // Force immediate flush for high-priority messages\n private func flushMessageBatchImmediately() {\n messageBatchTimer?.invalidate()\n flushMessageBatch()\n }\n \n // Update encryption status in appropriate places, not during view updates\n private func updateEncryptionStatus(for peerID: String) {\n let noiseService = meshService.getNoiseService()\n \n if noiseService.hasEstablishedSession(with: peerID) {\n if let fingerprint = getFingerprint(for: peerID) {\n if verifiedFingerprints.contains(fingerprint) {\n peerEncryptionStatus[peerID] = .noiseVerified\n } else {\n peerEncryptionStatus[peerID] = .noiseSecured\n }\n } else {\n // Session established but no fingerprint yet\n peerEncryptionStatus[peerID] = .noiseSecured\n }\n } else if noiseService.hasSession(with: peerID) {\n peerEncryptionStatus[peerID] = .noiseHandshaking\n } else {\n peerEncryptionStatus[peerID] = Optional.none\n }\n \n // Invalidate cache when encryption status changes\n invalidateEncryptionCache(for: peerID)\n \n // Trigger UI update\n DispatchQueue.main.async { [weak self] in\n self?.objectWillChange.send()\n }\n }\n \n // MARK: - Fingerprint Management\n \n func showFingerprint(for peerID: String) {\n showingFingerprintFor = peerID\n }\n \n func getFingerprint(for peerID: String) -> String? {\n // Remove debug logging to prevent console spam during view updates\n \n // First try to get fingerprint from mesh service's peer ID rotation mapping\n if let fingerprint = meshService.getFingerprint(for: peerID) {\n return fingerprint\n }\n \n // Fallback to noise service (direct Noise session fingerprint)\n if let fingerprint = meshService.getNoiseService().getPeerFingerprint(peerID) {\n return fingerprint\n }\n \n // Last resort: check local mapping\n if let fingerprint = peerIDToPublicKeyFingerprint[peerID] {\n return fingerprint\n }\n \n return nil\n }\n \n // Helper to resolve nickname for a peer ID through various sources\n func resolveNickname(for peerID: String) -> String {\n // Guard against empty or very short peer IDs\n guard !peerID.isEmpty else {\n return \"unknown\"\n }\n \n // Check if this might already be a nickname (not a hex peer ID)\n // Peer IDs are hex strings, so they only contain 0-9 and a-f\n let isHexID = peerID.allSatisfy { $0.isHexDigit }\n if !isHexID {\n // If it's already a nickname, just return it\n return peerID\n }\n \n // First try direct peer nicknames from mesh service\n let peerNicknames = meshService.getPeerNicknames()\n if let nickname = peerNicknames[peerID] {\n return nickname\n }\n \n // Try to resolve through fingerprint and social identity\n if let fingerprint = getFingerprint(for: peerID) {\n if let identity = SecureIdentityStateManager.shared.getSocialIdentity(for: fingerprint) {\n // Prefer local petname if set\n if let petname = identity.localPetname {\n return petname\n }\n // Otherwise use their claimed nickname\n return identity.claimedNickname\n }\n }\n \n // Fallback to anonymous with shortened peer ID\n // Ensure we have at least 4 characters for the prefix\n let prefixLength = min(4, peerID.count)\n let prefix = String(peerID.prefix(prefixLength))\n \n // Avoid \"anonanon\" by checking if ID already starts with \"anon\"\n if prefix.starts(with: \"anon\") {\n return \"peer\\(prefix)\"\n }\n return \"anon\\(prefix)\"\n }\n \n func getMyFingerprint() -> String {\n let fingerprint = meshService.getNoiseService().getIdentityFingerprint()\n return fingerprint\n }\n \n func verifyFingerprint(for peerID: String) {\n guard let fingerprint = getFingerprint(for: peerID) else { return }\n \n // Update secure storage with verified status\n SecureIdentityStateManager.shared.setVerified(fingerprint: fingerprint, verified: true)\n \n // Update local set for UI\n verifiedFingerprints.insert(fingerprint)\n \n // Update encryption status after verification\n updateEncryptionStatus(for: peerID)\n }\n \n func loadVerifiedFingerprints() {\n // Load verified fingerprints directly from secure storage\n verifiedFingerprints = SecureIdentityStateManager.shared.getVerifiedFingerprints()\n }\n \n private func setupNoiseCallbacks() {\n let noiseService = meshService.getNoiseService()\n \n // Set up authentication callback\n noiseService.onPeerAuthenticated = { [weak self] peerID, fingerprint in\n DispatchQueue.main.async {\n guard let self = self else { return }\n \n SecureLogger.log(\"ChatViewModel: Peer authenticated - \\(peerID), fingerprint: \\(fingerprint)\", category: SecureLogger.security, level: .info)\n \n // Update encryption status\n if self.verifiedFingerprints.contains(fingerprint) {\n self.peerEncryptionStatus[peerID] = .noiseVerified\n SecureLogger.log(\"ChatViewModel: Setting encryption status to noiseVerified for \\(peerID)\", category: SecureLogger.security, level: .info)\n } else {\n self.peerEncryptionStatus[peerID] = .noiseSecured\n SecureLogger.log(\"ChatViewModel: Setting encryption status to noiseSecured for \\(peerID)\", category: SecureLogger.security, level: .info)\n }\n \n // Invalidate cache when encryption status changes\n self.invalidateEncryptionCache(for: peerID)\n \n // Force UI update\n self.objectWillChange.send()\n }\n }\n \n // Set up handshake required callback\n noiseService.onHandshakeRequired = { [weak self] peerID in\n DispatchQueue.main.async {\n guard let self = self else { return }\n self.peerEncryptionStatus[peerID] = .noiseHandshaking\n \n // Invalidate cache when encryption status changes\n self.invalidateEncryptionCache(for: peerID)\n \n // Force UI update\n self.objectWillChange.send()\n }\n }\n }\n}\n\n// MARK: - BitchatDelegate\n\nextension ChatViewModel: BitchatDelegate {\n \n // MARK: - Command Handling\n \n /// Processes IRC-style commands starting with '/'.\n /// - Parameter command: The full command string including the leading slash\n /// - Note: Supports commands like /nick, /msg, /who, /slap, /clear, /help\n private func handleCommand(_ command: String) {\n let parts = command.split(separator: \" \")\n guard let cmd = parts.first else { return }\n \n switch cmd {\n case \"/m\", \"/msg\":\n if parts.count > 1 {\n let targetName = String(parts[1])\n // Remove @ if present\n let nickname = targetName.hasPrefix(\"@\") ? String(targetName.dropFirst()) : targetName\n \n // Find peer ID for this nickname\n if let peerID = getPeerIDForNickname(nickname) {\n startPrivateChat(with: peerID)\n \n // If there's a message after the nickname, send it\n if parts.count > 2 {\n let messageContent = parts[2...].joined(separator: \" \")\n sendPrivateMessage(messageContent, to: peerID)\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"started private chat with \\(nickname)\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"user '\\(nickname)' not found. they may be offline or using a different nickname.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"usage: /m @nickname [message] or /m nickname [message]\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n case \"/w\":\n let peerNicknames = meshService.getPeerNicknames()\n if connectedPeers.isEmpty {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"no one else is online right now.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n } else {\n let onlineList = connectedPeers.compactMap { peerID in\n peerNicknames[peerID]\n }.sorted().joined(separator: \", \")\n \n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"online users: \\(onlineList)\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n case \"/clear\":\n // Clear messages based on current context\n if let peerID = selectedPrivateChatPeer {\n // Clear private chat\n privateChats[peerID]?.removeAll()\n } else {\n // Clear main messages\n messages.removeAll()\n }\n case \"/hug\":\n if parts.count > 1 {\n let targetName = String(parts[1])\n // Remove @ if present\n let nickname = targetName.hasPrefix(\"@\") ? String(targetName.dropFirst()) : targetName\n \n // Check if target exists in connected peers\n if let targetPeerID = getPeerIDForNickname(nickname) {\n // Create hug message\n let hugMessage = BitchatMessage(\n sender: \"system\",\n content: \"🫂 \\(self.nickname) hugs \\(nickname)\",\n timestamp: Date(),\n isRelay: false,\n isPrivate: false,\n recipientNickname: nickname,\n senderPeerID: meshService.myPeerID\n )\n \n // Send as a regular message but it will be displayed as system message due to content\n let hugContent = \"* 🫂 \\(self.nickname) hugs \\(nickname) *\"\n if selectedPrivateChatPeer != nil {\n // In private chat, send as private message\n if let peerNickname = meshService.getPeerNicknames()[targetPeerID] {\n meshService.sendPrivateMessage(\"* 🫂 \\(self.nickname) hugs you *\", to: targetPeerID, recipientNickname: peerNickname)\n }\n } else {\n // In public chat\n meshService.sendMessage(hugContent)\n messages.append(hugMessage)\n }\n } else {\n let errorMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot hug \\(nickname): user not found.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(errorMessage)\n }\n } else {\n let usageMessage = BitchatMessage(\n sender: \"system\",\n content: \"usage: /hug \",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(usageMessage)\n }\n \n case \"/slap\":\n if parts.count > 1 {\n let targetName = String(parts[1])\n // Remove @ if present\n let nickname = targetName.hasPrefix(\"@\") ? String(targetName.dropFirst()) : targetName\n \n // Check if target exists in connected peers\n if let targetPeerID = getPeerIDForNickname(nickname) {\n // Create slap message\n let slapMessage = BitchatMessage(\n sender: \"system\",\n content: \"🐟 \\(self.nickname) slaps \\(nickname) around a bit with a large trout\",\n timestamp: Date(),\n isRelay: false,\n isPrivate: false,\n recipientNickname: nickname,\n senderPeerID: meshService.myPeerID\n )\n \n // Send as a regular message but it will be displayed as system message due to content\n let slapContent = \"* 🐟 \\(self.nickname) slaps \\(nickname) around a bit with a large trout *\"\n if selectedPrivateChatPeer != nil {\n // In private chat, send as private message\n if let peerNickname = meshService.getPeerNicknames()[targetPeerID] {\n meshService.sendPrivateMessage(\"* 🐟 \\(self.nickname) slaps you around a bit with a large trout *\", to: targetPeerID, recipientNickname: peerNickname)\n }\n } else {\n // In public chat\n meshService.sendMessage(slapContent)\n messages.append(slapMessage)\n }\n } else {\n let errorMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot slap \\(nickname): user not found.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(errorMessage)\n }\n } else {\n let usageMessage = BitchatMessage(\n sender: \"system\",\n content: \"usage: /slap \",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(usageMessage)\n }\n \n case \"/block\":\n if parts.count > 1 {\n let targetName = String(parts[1])\n // Remove @ if present\n let nickname = targetName.hasPrefix(\"@\") ? String(targetName.dropFirst()) : targetName\n \n // Find peer ID for this nickname\n if let peerID = getPeerIDForNickname(nickname) {\n // Get fingerprint for persistent blocking\n if let fingerprintStr = meshService.getPeerFingerprint(peerID) {\n \n if SecureIdentityStateManager.shared.isBlocked(fingerprint: fingerprintStr) {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"\\(nickname) is already blocked.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n } else {\n // Update or create social identity with blocked status\n if var identity = SecureIdentityStateManager.shared.getSocialIdentity(for: fingerprintStr) {\n identity.isBlocked = true\n identity.isFavorite = false // Remove from favorites if blocked\n SecureIdentityStateManager.shared.updateSocialIdentity(identity)\n } else {\n let blockedIdentity = SocialIdentity(\n fingerprint: fingerprintStr,\n localPetname: nil,\n claimedNickname: nickname,\n trustLevel: .unknown,\n isFavorite: false,\n isBlocked: true,\n notes: nil\n )\n SecureIdentityStateManager.shared.updateSocialIdentity(blockedIdentity)\n }\n \n // Update local sets for UI\n blockedUsers.insert(fingerprintStr)\n favoritePeers.remove(fingerprintStr)\n \n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"blocked \\(nickname). you will no longer receive messages from them.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot block \\(nickname): unable to verify identity.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot block \\(nickname): user not found.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n // List blocked users\n if blockedUsers.isEmpty {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"no blocked peers.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n } else {\n // Find nicknames for blocked users\n var blockedNicknames: [String] = []\n for (peerID, _) in meshService.getPeerNicknames() {\n if let fingerprintStr = meshService.getPeerFingerprint(peerID) {\n if blockedUsers.contains(fingerprintStr) {\n if let nickname = meshService.getPeerNicknames()[peerID] {\n blockedNicknames.append(nickname)\n }\n }\n }\n }\n \n let blockedList = blockedNicknames.isEmpty ? \"blocked peers (not currently online)\" : blockedNicknames.sorted().joined(separator: \", \")\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"blocked peers: \\(blockedList)\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n }\n \n case \"/unblock\":\n if parts.count > 1 {\n let targetName = String(parts[1])\n // Remove @ if present\n let nickname = targetName.hasPrefix(\"@\") ? String(targetName.dropFirst()) : targetName\n \n // Find peer ID for this nickname\n if let peerID = getPeerIDForNickname(nickname) {\n // Get fingerprint\n if let fingerprintStr = meshService.getPeerFingerprint(peerID) {\n \n if SecureIdentityStateManager.shared.isBlocked(fingerprint: fingerprintStr) {\n // Update social identity to unblock\n SecureIdentityStateManager.shared.setBlocked(fingerprintStr, isBlocked: false)\n \n // Update local set for UI\n blockedUsers.remove(fingerprintStr)\n \n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"unblocked \\(nickname).\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"\\(nickname) is not blocked.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot unblock \\(nickname): unable to verify identity.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot unblock \\(nickname): user not found.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"usage: /unblock \",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n \n default:\n // Unknown command\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"unknown command: \\(cmd).\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n }\n \n // MARK: - Message Reception\n \n func handleHandshakeRequest(from peerID: String, nickname: String, pendingCount: UInt8) {\n // Create a notification message\n let notificationMessage = BitchatMessage(\n sender: \"system\",\n content: \"📨 \\(nickname) wants to send you \\(pendingCount) message\\(pendingCount == 1 ? \"\" : \"s\"). Open the conversation to receive.\",\n timestamp: Date(),\n isRelay: false,\n originalSender: nil,\n isPrivate: false,\n recipientNickname: nil,\n senderPeerID: \"system\",\n mentions: nil\n )\n \n // Add to messages\n messages.append(notificationMessage)\n trimMessagesIfNeeded()\n \n // Show system notification\n if let fingerprint = getFingerprint(for: peerID) {\n let isFavorite = favoritePeers.contains(fingerprint)\n if isFavorite {\n // Send favorite notification\n NotificationService.shared.sendPrivateMessageNotification(\n from: nickname,\n message: \"\\(pendingCount) message\\(pendingCount == 1 ? \"\" : \"s\") pending\",\n peerID: peerID\n )\n } else {\n // Send regular notification\n NotificationService.shared.sendMentionNotification(\n from: nickname,\n message: \"\\(pendingCount) message\\(pendingCount == 1 ? \"\" : \"s\") pending. Open conversation to receive.\"\n )\n }\n }\n }\n \n func didReceiveMessage(_ message: BitchatMessage) {\n \n \n // Check if sender is blocked (for both private and public messages)\n if let senderPeerID = message.senderPeerID {\n if isPeerBlocked(senderPeerID) {\n // Silently ignore messages from blocked users\n return\n }\n } else if let peerID = getPeerIDForNickname(message.sender) {\n if isPeerBlocked(peerID) {\n // Silently ignore messages from blocked users\n return\n }\n }\n \n if message.isPrivate {\n // Handle private message\n \n // Use the senderPeerID from the message if available\n let senderPeerID = message.senderPeerID ?? getPeerIDForNickname(message.sender)\n \n if let peerID = senderPeerID {\n // Message from someone else\n \n // First check if we need to migrate existing messages from this sender\n let senderNickname = message.sender\n if privateChats[peerID] == nil || privateChats[peerID]?.isEmpty == true {\n // Check if we have messages from this nickname under a different peer ID\n var migratedMessages: [BitchatMessage] = []\n var oldPeerIDsToRemove: [String] = []\n \n for (oldPeerID, messages) in privateChats {\n if oldPeerID != peerID {\n // Check if this chat contains messages with this sender\n let isRelevantChat = messages.contains { msg in\n (msg.sender == senderNickname && msg.sender != nickname) ||\n (msg.sender == nickname && msg.recipientNickname == senderNickname)\n }\n \n if isRelevantChat {\n migratedMessages.append(contentsOf: messages)\n oldPeerIDsToRemove.append(oldPeerID)\n }\n }\n }\n \n // Remove old peer ID entries\n for oldPeerID in oldPeerIDsToRemove {\n privateChats.removeValue(forKey: oldPeerID)\n unreadPrivateMessages.remove(oldPeerID)\n }\n \n // Initialize with migrated messages\n privateChats[peerID] = migratedMessages\n trimPrivateChatMessagesIfNeeded(for: peerID)\n }\n \n if privateChats[peerID] == nil {\n privateChats[peerID] = []\n }\n \n // Fix delivery status for incoming messages\n var messageToStore = message\n if message.sender != nickname {\n // This is an incoming message - it should NOT have \"sending\" status\n if messageToStore.deliveryStatus == nil || messageToStore.deliveryStatus == .sending {\n // Mark it as delivered since we received it\n messageToStore.deliveryStatus = .delivered(to: nickname, at: Date())\n }\n }\n \n // Check if this is an action that should be converted to system message\n let isActionMessage = messageToStore.content.hasPrefix(\"* \") && messageToStore.content.hasSuffix(\" *\") &&\n (messageToStore.content.contains(\"🫂\") || messageToStore.content.contains(\"🐟\") || \n messageToStore.content.contains(\"took a screenshot\"))\n \n if isActionMessage {\n // Convert to system message\n messageToStore = BitchatMessage(\n id: messageToStore.id,\n sender: \"system\",\n content: String(messageToStore.content.dropFirst(2).dropLast(2)), // Remove * * wrapper\n timestamp: messageToStore.timestamp,\n isRelay: messageToStore.isRelay,\n originalSender: messageToStore.originalSender,\n isPrivate: messageToStore.isPrivate,\n recipientNickname: messageToStore.recipientNickname,\n senderPeerID: messageToStore.senderPeerID,\n mentions: messageToStore.mentions,\n deliveryStatus: messageToStore.deliveryStatus\n )\n }\n \n // Use batching for private messages\n addPrivateMessageToBatch(messageToStore, for: peerID)\n \n // Debug logging\n \n // Check if we're in a private chat with this peer's fingerprint\n // This handles reconnections with new peer IDs\n if let chatFingerprint = selectedPrivateChatFingerprint,\n let senderFingerprint = peerIDToPublicKeyFingerprint[peerID],\n chatFingerprint == senderFingerprint && selectedPrivateChatPeer != peerID {\n // Update our private chat peer to the new ID\n selectedPrivateChatPeer = peerID\n }\n \n // Mark as unread if not currently viewing this chat\n if selectedPrivateChatPeer != peerID {\n unreadPrivateMessages.insert(peerID)\n \n } else {\n // We're viewing this chat, make sure unread is cleared\n unreadPrivateMessages.remove(peerID)\n \n // Send read receipt immediately since we're viewing the chat\n // Send to the current peer ID since peer IDs change between sessions\n if !sentReadReceipts.contains(message.id) {\n let receipt = ReadReceipt(\n originalMessageID: message.id,\n readerID: meshService.myPeerID,\n readerNickname: nickname\n )\n meshService.sendReadReceipt(receipt, to: peerID)\n sentReadReceipts.insert(message.id)\n }\n \n // Also check if there are other unread messages from this peer\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in\n self?.markPrivateMessagesAsRead(from: peerID)\n }\n }\n } else if message.sender == nickname {\n // Our own message that was echoed back - ignore it since we already added it locally\n }\n } else {\n // Regular public message (main chat)\n \n // Check if this is an action that should be converted to system message\n let isActionMessage = message.content.hasPrefix(\"* \") && message.content.hasSuffix(\" *\") &&\n (message.content.contains(\"🫂\") || message.content.contains(\"🐟\") || \n message.content.contains(\"took a screenshot\"))\n \n let finalMessage: BitchatMessage\n if isActionMessage {\n // Convert to system message\n finalMessage = BitchatMessage(\n sender: \"system\",\n content: String(message.content.dropFirst(2).dropLast(2)), // Remove * * wrapper\n timestamp: message.timestamp,\n isRelay: message.isRelay,\n originalSender: message.originalSender,\n isPrivate: false,\n recipientNickname: message.recipientNickname,\n senderPeerID: message.senderPeerID,\n mentions: message.mentions\n )\n } else {\n finalMessage = message\n }\n \n // Check if this is our own message being echoed back\n if finalMessage.sender != nickname && finalMessage.sender != \"system\" {\n // Skip empty or whitespace-only messages\n if !finalMessage.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {\n addMessageToBatch(finalMessage)\n }\n } else if finalMessage.sender != \"system\" {\n // Our own message - check if we already have it (by ID and content)\n let messageExists = messages.contains { existingMsg in\n // Check by ID first\n if existingMsg.id == finalMessage.id {\n return true\n }\n // Check by content and sender with time window (within 1 second)\n if existingMsg.content == finalMessage.content && \n existingMsg.sender == finalMessage.sender {\n let timeDiff = abs(existingMsg.timestamp.timeIntervalSince(finalMessage.timestamp))\n return timeDiff < 1.0\n }\n return false\n }\n if !messageExists {\n // This is a message we sent from another device or it's missing locally\n // Skip empty or whitespace-only messages\n if !finalMessage.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {\n addMessageToBatch(finalMessage)\n }\n }\n } else {\n // System message - check for empty content before adding\n if !finalMessage.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {\n addMessageToBatch(finalMessage)\n }\n }\n }\n \n // Check if we're mentioned\n let isMentioned = message.mentions?.contains(nickname) ?? false\n \n // Send notifications for mentions and private messages when app is in background\n if isMentioned && message.sender != nickname {\n NotificationService.shared.sendMentionNotification(from: message.sender, message: message.content)\n } else if message.isPrivate && message.sender != nickname {\n // Only send notification if the private chat is not currently open\n if selectedPrivateChatPeer != message.senderPeerID {\n NotificationService.shared.sendPrivateMessageNotification(from: message.sender, message: message.content, peerID: message.senderPeerID ?? \"\")\n }\n }\n \n #if os(iOS)\n // Haptic feedback for iOS only\n guard UIApplication.shared.applicationState == .active else {\n return\n }\n // Check if this is a hug message directed at the user\n let isHugForMe = message.content.contains(\"🫂\") && \n (message.content.contains(\"hugs \\(nickname)\") ||\n message.content.contains(\"hugs you\"))\n \n // Check if this is a slap message directed at the user\n let isSlapForMe = message.content.contains(\"🐟\") && \n (message.content.contains(\"slaps \\(nickname) around\") ||\n message.content.contains(\"slaps you around\"))\n \n if isHugForMe && message.sender != nickname {\n // Long warm haptic for hugs - continuous gentle vibration\n let impactFeedback = UIImpactFeedbackGenerator(style: .medium)\n impactFeedback.prepare()\n \n // Create a warm, sustained haptic pattern\n for i in 0..<8 {\n DispatchQueue.main.asyncAfter(deadline: .now() + Double(i) * 0.15) {\n impactFeedback.impactOccurred()\n }\n }\n \n // Add a final stronger pulse\n DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {\n let strongFeedback = UIImpactFeedbackGenerator(style: .heavy)\n strongFeedback.prepare()\n strongFeedback.impactOccurred()\n }\n } else if isSlapForMe && message.sender != nickname {\n // Very harsh, fast, strong haptic for slaps - multiple sharp impacts\n let impactFeedback = UIImpactFeedbackGenerator(style: .heavy)\n impactFeedback.prepare()\n \n // Rapid-fire heavy impacts to simulate a hard slap\n impactFeedback.impactOccurred()\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) {\n impactFeedback.impactOccurred()\n }\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.06) {\n impactFeedback.impactOccurred()\n }\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.09) {\n impactFeedback.impactOccurred()\n }\n \n // Final extra heavy impact\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {\n let finalImpact = UIImpactFeedbackGenerator(style: .heavy)\n finalImpact.prepare()\n finalImpact.impactOccurred()\n }\n } else if isMentioned && message.sender != nickname {\n // Very prominent haptic for @mentions - triple tap with heavy impact\n let impactFeedback = UIImpactFeedbackGenerator(style: .heavy)\n impactFeedback.prepare()\n impactFeedback.impactOccurred()\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {\n impactFeedback.impactOccurred()\n }\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {\n impactFeedback.impactOccurred()\n }\n } else if message.isPrivate && message.sender != nickname {\n // Heavy haptic for private messages - more pronounced\n let impactFeedback = UIImpactFeedbackGenerator(style: .heavy)\n impactFeedback.prepare()\n impactFeedback.impactOccurred()\n \n // Double tap for extra emphasis\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {\n impactFeedback.impactOccurred()\n }\n } else if message.sender != nickname {\n // Light haptic for public messages from others\n let impactFeedback = UIImpactFeedbackGenerator(style: .light)\n impactFeedback.impactOccurred()\n }\n #endif\n }\n \n // MARK: - Peer Connection Events\n \n func didConnectToPeer(_ peerID: String) {\n isConnected = true\n \n // Register ephemeral session with identity manager\n SecureIdentityStateManager.shared.registerEphemeralSession(peerID: peerID)\n \n // Resolve nickname using helper\n let displayName = resolveNickname(for: peerID)\n \n // Ensure we have a valid display name\n let finalDisplayName = displayName.isEmpty ? \"peer\" : displayName\n \n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"\\(finalDisplayName) connected\",\n timestamp: Date(),\n isRelay: false,\n originalSender: nil\n )\n // Batch system messages\n addMessageToBatch(systemMessage)\n }\n \n func didDisconnectFromPeer(_ peerID: String) {\n // Remove ephemeral session from identity manager\n SecureIdentityStateManager.shared.removeEphemeralSession(peerID: peerID)\n \n // Clear sent read receipts for this peer since they'll need to be resent after reconnection\n // Only clear receipts for messages from this specific peer\n if let messages = privateChats[peerID] {\n for message in messages {\n // Remove read receipts for messages FROM this peer (not TO this peer)\n if message.senderPeerID == peerID {\n sentReadReceipts.remove(message.id)\n }\n }\n }\n \n // Resolve nickname using helper\n let displayName = resolveNickname(for: peerID)\n \n // Ensure we have a valid display name\n let finalDisplayName = displayName.isEmpty ? \"peer\" : displayName\n \n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"\\(finalDisplayName) disconnected\",\n timestamp: Date(),\n isRelay: false,\n originalSender: nil\n )\n // Batch system messages\n addMessageToBatch(systemMessage)\n }\n \n func didUpdatePeerList(_ peers: [String]) {\n // UI updates must run on the main thread.\n // The delegate callback is not guaranteed to be on the main thread.\n DispatchQueue.main.async {\n self.connectedPeers = peers\n self.isConnected = !peers.isEmpty\n \n // Register ephemeral sessions for all connected peers\n for peerID in peers {\n SecureIdentityStateManager.shared.registerEphemeralSession(peerID: peerID)\n }\n \n // Update encryption status for all peers\n self.updateEncryptionStatusForPeers()\n \n // Invalidate RSSI cache since peer data may have changed\n self.invalidateRSSIColorCache()\n\n // Explicitly notify SwiftUI that the object has changed.\n self.objectWillChange.send()\n \n // Check if we need to update private chat peer after reconnection\n if self.selectedPrivateChatFingerprint != nil {\n self.updatePrivateChatPeerIfNeeded()\n }\n \n // Only end private chat if we can't find the peer by fingerprint\n if let currentChatPeer = self.selectedPrivateChatPeer,\n !peers.contains(currentChatPeer),\n self.selectedPrivateChatFingerprint != nil {\n // Try one more time to find by fingerprint\n if self.getCurrentPeerIDForFingerprint(self.selectedPrivateChatFingerprint!) == nil {\n self.endPrivateChat()\n }\n }\n }\n }\n \n // MARK: - Helper Methods\n \n private func parseMentions(from content: String) -> [String] {\n let pattern = \"@([a-zA-Z0-9_]+)\"\n let regex = try? NSRegularExpression(pattern: pattern, options: [])\n let matches = regex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n \n var mentions: [String] = []\n let peerNicknames = meshService.getPeerNicknames()\n let allNicknames = Set(peerNicknames.values).union([nickname]) // Include self\n \n for match in matches {\n if let range = Range(match.range(at: 1), in: content) {\n let mentionedName = String(content[range])\n // Only include if it's a valid nickname\n if allNicknames.contains(mentionedName) {\n mentions.append(mentionedName)\n }\n }\n }\n \n return Array(Set(mentions)) // Remove duplicates\n }\n \n func isFavorite(fingerprint: String) -> Bool {\n return SecureIdentityStateManager.shared.isFavorite(fingerprint: fingerprint)\n }\n \n // MARK: - Delivery Tracking\n \n func didReceiveDeliveryAck(_ ack: DeliveryAck) {\n // Find the message and update its delivery status\n updateMessageDeliveryStatus(ack.originalMessageID, status: .delivered(to: ack.recipientNickname, at: ack.timestamp))\n }\n \n func didReceiveReadReceipt(_ receipt: ReadReceipt) {\n // Find the message and update its read status\n updateMessageDeliveryStatus(receipt.originalMessageID, status: .read(by: receipt.readerNickname, at: receipt.timestamp))\n \n // Clear delivery tracking since the message has been read\n // This prevents the timeout from marking it as failed\n DeliveryTracker.shared.clearDeliveryStatus(for: receipt.originalMessageID)\n }\n \n func didUpdateMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) {\n updateMessageDeliveryStatus(messageID, status: status)\n }\n \n private func updateMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) {\n SecureLogger.log(\"Updating UI delivery status for message \\(messageID): \\(status)\", category: SecureLogger.session, level: .debug)\n \n // Helper function to check if we should skip this update\n func shouldSkipUpdate(currentStatus: DeliveryStatus?, newStatus: DeliveryStatus) -> Bool {\n guard let current = currentStatus else { return false }\n \n // Don't downgrade from read to delivered\n switch (current, newStatus) {\n case (.read, .delivered):\n return true\n case (.read, .sent):\n return true\n default:\n return false\n }\n }\n \n // Update in main messages\n if let index = messages.firstIndex(where: { $0.id == messageID }) {\n let currentStatus = messages[index].deliveryStatus\n if !shouldSkipUpdate(currentStatus: currentStatus, newStatus: status) {\n messages[index].deliveryStatus = status\n }\n }\n \n // Update in private chats\n var updatedPrivateChats = privateChats\n for (peerID, chatMessages) in updatedPrivateChats {\n if let index = chatMessages.firstIndex(where: { $0.id == messageID }) {\n let currentStatus = chatMessages[index].deliveryStatus\n if !shouldSkipUpdate(currentStatus: currentStatus, newStatus: status) {\n chatMessages[index].deliveryStatus = status\n updatedPrivateChats[peerID] = chatMessages\n }\n }\n }\n \n // Force complete reassignment to trigger SwiftUI update\n DispatchQueue.main.async { [weak self] in\n guard let self = self else { return }\n self.privateChats = updatedPrivateChats\n self.objectWillChange.send()\n }\n \n }\n \n \n}\n", "middle_code": "private func flushMessageBatch() {\n DispatchQueue.main.async { [weak self] in\n guard let self = self else { return }\n if !self.pendingMessages.isEmpty {\n let messagesToAdd = self.pendingMessages\n self.pendingMessages.removeAll()\n self.messages.append(contentsOf: messagesToAdd)\n self.messages.sort { $0.timestamp < $1.timestamp }\n self.trimMessagesIfNeeded()\n }\n if !self.pendingPrivateMessages.isEmpty {\n let privateMessageBatches = self.pendingPrivateMessages\n self.pendingPrivateMessages.removeAll()\n for (peerID, messagesToAdd) in privateMessageBatches {\n if self.privateChats[peerID] == nil {\n self.privateChats[peerID] = []\n }\n self.privateChats[peerID]?.append(contentsOf: messagesToAdd)\n self.privateChats[peerID]?.sort { $0.timestamp < $1.timestamp }\n self.trimPrivateChatMessagesIfNeeded(for: peerID)\n }\n }\n self.objectWillChange.send()\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/bitchat/bitchat/Services/BluetoothMeshService.swift", "//\n// BluetoothMeshService.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # BluetoothMeshService\n///\n/// The core networking component that manages peer-to-peer Bluetooth LE connections\n/// and implements the BitChat mesh networking protocol.\n///\n/// ## Overview\n/// This service is the heart of BitChat's decentralized architecture. It manages all\n/// Bluetooth LE communications, enabling devices to form an ad-hoc mesh network without\n/// any infrastructure. The service handles:\n/// - Peer discovery and connection management\n/// - Message routing and relay functionality\n/// - Protocol version negotiation\n/// - Connection state tracking and recovery\n/// - Integration with the Noise encryption layer\n///\n/// ## Architecture\n/// The service operates in a dual mode:\n/// - **Central Mode**: Scans for and connects to other BitChat devices\n/// - **Peripheral Mode**: Advertises its presence and accepts connections\n///\n/// This dual-mode operation enables true peer-to-peer connectivity where any device\n/// can initiate or accept connections, forming a resilient mesh topology.\n///\n/// ## Mesh Networking\n/// Messages are relayed through the mesh using a TTL (Time To Live) mechanism:\n/// - Each message has a TTL that decrements at each hop\n/// - Messages are cached to prevent loops (via Bloom filters)\n/// - Store-and-forward ensures delivery to temporarily offline peers\n///\n/// ## Connection Lifecycle\n/// 1. **Discovery**: Devices scan and advertise simultaneously\n/// 2. **Connection**: BLE connection established\n/// 3. **Version Negotiation**: Ensure protocol compatibility\n/// 4. **Authentication**: Noise handshake for encrypted channels\n/// 5. **Message Exchange**: Bidirectional communication\n/// 6. **Disconnection**: Graceful cleanup and state preservation\n///\n/// ## Security Integration\n/// - Coordinates with NoiseEncryptionService for private messages\n/// - Maintains peer identity mappings\n/// - Handles lazy handshake initiation\n/// - Ensures message authenticity\n///\n/// ## Performance Optimizations\n/// - Connection pooling and reuse\n/// - Adaptive scanning based on battery level\n/// - Message batching for efficiency\n/// - Smart retry logic with exponential backoff\n///\n/// ## Thread Safety\n/// All public methods are thread-safe. The service uses:\n/// - Serial queues for Core Bluetooth operations\n/// - Thread-safe collections for peer management\n/// - Atomic operations for state updates\n///\n/// ## Error Handling\n/// - Automatic reconnection for lost connections\n/// - Graceful degradation when Bluetooth is unavailable\n/// - Clear error reporting through BitchatDelegate\n///\n/// ## Usage Example\n/// ```swift\n/// let meshService = BluetoothMeshService()\n/// meshService.delegate = self\n/// meshService.localUserID = \"user123\"\n/// meshService.startMeshService()\n/// ```\n///\n\nimport Foundation\nimport CoreBluetooth\nimport Combine\nimport CryptoKit\nimport os.log\n#if os(macOS)\nimport AppKit\nimport IOKit.ps\n#else\nimport UIKit\n#endif\n\n// Hex encoding/decoding is now in BinaryEncodingUtils.swift\n\n// Extension for TimeInterval to Data conversion\nextension TimeInterval {\n var data: Data {\n var value = self\n return Data(bytes: &value, count: MemoryLayout.size)\n }\n}\n\n// Version negotiation state\nenum VersionNegotiationState {\n case none\n case helloSent\n case ackReceived(version: UInt8)\n case failed(reason: String)\n}\n\n// Peer connection state tracking\nenum PeerConnectionState: CustomStringConvertible {\n case disconnected\n case connecting\n case connected // BLE connected but not authenticated\n case authenticating // Performing handshake\n case authenticated // Handshake complete, ready for messages\n \n var isAvailable: Bool {\n switch self {\n case .authenticated:\n return true\n default:\n return false\n }\n }\n \n var description: String {\n switch self {\n case .disconnected: return \"disconnected\"\n case .connecting: return \"connecting\"\n case .connected: return \"connected\"\n case .authenticating: return \"authenticating\"\n case .authenticated: return \"authenticated\"\n }\n }\n}\n\n/// Manages all Bluetooth LE networking operations for the BitChat mesh network.\n/// This class handles peer discovery, connection management, message routing,\n/// and protocol negotiation. It acts as both a BLE central (scanner) and\n/// peripheral (advertiser) simultaneously to enable true peer-to-peer connectivity.\nclass BluetoothMeshService: NSObject {\n // MARK: - Constants\n \n static let serviceUUID = CBUUID(string: \"F47B5E2D-4A9E-4C5A-9B3F-8E1D2C3A4B5C\")\n static let characteristicUUID = CBUUID(string: \"A1B2C3D4-E5F6-4A5B-8C9D-0E1F2A3B4C5D\")\n \n // MARK: - Core Bluetooth Properties\n \n private var centralManager: CBCentralManager?\n private var peripheralManager: CBPeripheralManager?\n private var discoveredPeripherals: [CBPeripheral] = []\n private var connectedPeripherals: [String: CBPeripheral] = [:]\n private var peripheralCharacteristics: [CBPeripheral: CBCharacteristic] = [:]\n \n // MARK: - Connection Tracking\n \n private var lastConnectionTime: [String: Date] = [:] // Track when peers last connected\n private var lastSuccessfulMessageTime: [String: Date] = [:] // Track last successful message exchange\n private var lastHeardFromPeer: [String: Date] = [:] // Track last time we received ANY packet from peer\n \n // MARK: - Peer Availability\n \n // Peer availability tracking\n private var peerAvailabilityState: [String: Bool] = [:] // true = available, false = unavailable\n private let peerAvailabilityTimeout: TimeInterval = 30.0 // Mark unavailable after 30s of no response\n private var availabilityCheckTimer: Timer?\n \n // MARK: - Peripheral Management\n \n private var characteristic: CBMutableCharacteristic?\n private var subscribedCentrals: [CBCentral] = []\n \n // MARK: - Thread-Safe Collections\n \n private let collectionsQueue = DispatchQueue(label: \"bitchat.collections\", attributes: .concurrent)\n private var peerNicknames: [String: String] = [:]\n private var activePeers: Set = [] // Track all active peers\n private var peerRSSI: [String: NSNumber] = [:] // Track RSSI values for peers\n private var peripheralRSSI: [String: NSNumber] = [:] // Track RSSI by peripheral ID during discovery\n private var rssiRetryCount: [String: Int] = [:] // Track RSSI retry attempts per peripheral\n \n // MARK: - Encryption Queues\n \n // Per-peer encryption queues to prevent nonce desynchronization\n private var peerEncryptionQueues: [String: DispatchQueue] = [:]\n private let encryptionQueuesLock = NSLock()\n \n // MARK: - Peer Identity Rotation\n // Mappings between ephemeral peer IDs and permanent fingerprints\n private var peerIDToFingerprint: [String: String] = [:] // PeerID -> Fingerprint\n private var fingerprintToPeerID: [String: String] = [:] // Fingerprint -> Current PeerID\n private var peerIdentityBindings: [String: PeerIdentityBinding] = [:] // Fingerprint -> Full binding\n private var previousPeerID: String? // Our previous peer ID for grace period\n private var rotationTimestamp: Date? // When we last rotated\n private let rotationGracePeriod: TimeInterval = 60.0 // 1 minute grace period\n private var rotationLocked = false // Prevent rotation during critical operations\n private var rotationTimer: Timer? // Timer for scheduled rotations\n \n // MARK: - Identity Cache\n // In-memory cache for peer public keys to avoid keychain lookups\n private var peerPublicKeyCache: [String: Data] = [:] // PeerID -> Public Key Data\n private var peerSigningKeyCache: [String: Data] = [:] // PeerID -> Signing Key Data\n private let identityCacheTTL: TimeInterval = 3600.0 // 1 hour TTL\n private var identityCacheTimestamps: [String: Date] = [:] // Track when entries were cached\n \n // MARK: - Delegates and Services\n \n weak var delegate: BitchatDelegate?\n private let noiseService = NoiseEncryptionService()\n private let handshakeCoordinator = NoiseHandshakeCoordinator()\n \n // MARK: - Protocol Version Negotiation\n \n // Protocol version negotiation state\n private var versionNegotiationState: [String: VersionNegotiationState] = [:]\n private var negotiatedVersions: [String: UInt8] = [:] // peerID -> agreed version\n \n // MARK: - Write Queue for Disconnected Peripherals\n private struct QueuedWrite {\n let data: Data\n let peripheralID: String\n let peerID: String?\n let timestamp: Date\n let retryCount: Int\n }\n \n private var writeQueue: [String: [QueuedWrite]] = [:] // PeripheralID -> Queue of writes\n private let writeQueueLock = NSLock()\n private let maxWriteQueueSize = 50 // Max queued writes per peripheral\n private let maxWriteRetries = 3\n private let writeQueueTTL: TimeInterval = 60.0 // Expire queued writes after 1 minute\n private var writeQueueTimer: Timer? // Timer for processing expired writes\n \n // MARK: - Connection Pooling\n private let maxConnectedPeripherals = 10 // Limit simultaneous connections\n private let maxScanningDuration: TimeInterval = 5.0 // Stop scanning after 5 seconds to save battery\n \n func getNoiseService() -> NoiseEncryptionService {\n return noiseService\n }\n \n \n private func cleanExpiredIdentityCache() {\n collectionsQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n let now = Date()\n var expiredPeerIDs: [String] = []\n \n for (peerID, timestamp) in self.identityCacheTimestamps {\n if now.timeIntervalSince(timestamp) >= self.identityCacheTTL {\n expiredPeerIDs.append(peerID)\n }\n }\n \n for peerID in expiredPeerIDs {\n self.peerPublicKeyCache.removeValue(forKey: peerID)\n self.peerSigningKeyCache.removeValue(forKey: peerID)\n self.identityCacheTimestamps.removeValue(forKey: peerID)\n }\n \n if !expiredPeerIDs.isEmpty {\n SecureLogger.log(\"Cleaned \\(expiredPeerIDs.count) expired identity cache entries\", \n category: SecureLogger.session, level: .debug)\n }\n }\n }\n \n // MARK: - Write Queue Management\n \n private func writeToPeripheral(_ data: Data, peripheral: CBPeripheral, characteristic: CBCharacteristic, peerID: String? = nil) {\n let peripheralID = peripheral.identifier.uuidString\n \n // Double check the peripheral state to avoid API misuse\n guard peripheral.state == .connected else {\n // Queue write for disconnected peripheral\n queueWrite(data: data, peripheralID: peripheralID, peerID: peerID)\n return\n }\n \n // Verify characteristic is valid and writable\n guard characteristic.properties.contains(.write) || characteristic.properties.contains(.writeWithoutResponse) else {\n SecureLogger.log(\"Characteristic does not support writing for peripheral \\(peripheralID)\", \n category: SecureLogger.session, level: .warning)\n return\n }\n \n // Direct write if connected\n let writeType: CBCharacteristicWriteType = data.count > 512 ? .withResponse : .withoutResponse\n peripheral.writeValue(data, for: characteristic, type: writeType)\n \n // Update activity tracking\n updatePeripheralActivity(peripheralID)\n }\n \n private func queueWrite(data: Data, peripheralID: String, peerID: String?) {\n writeQueueLock.lock()\n defer { writeQueueLock.unlock() }\n \n // Check backpressure - drop oldest if queue is full\n var queue = writeQueue[peripheralID] ?? []\n \n if queue.count >= maxWriteQueueSize {\n // Remove oldest entries\n let removeCount = queue.count - maxWriteQueueSize + 1\n queue.removeFirst(removeCount)\n SecureLogger.log(\"Write queue full for \\(peripheralID), dropped \\(removeCount) oldest writes\", \n category: SecureLogger.session, level: .warning)\n }\n \n let queuedWrite = QueuedWrite(\n data: data,\n peripheralID: peripheralID,\n peerID: peerID,\n timestamp: Date(),\n retryCount: 0\n )\n \n queue.append(queuedWrite)\n writeQueue[peripheralID] = queue\n \n SecureLogger.log(\"Queued write for disconnected peripheral \\(peripheralID), queue size: \\(queue.count)\", \n category: SecureLogger.session, level: .debug)\n }\n \n private func processWriteQueue(for peripheral: CBPeripheral) {\n guard peripheral.state == .connected,\n let characteristic = peripheralCharacteristics[peripheral] else { return }\n \n let peripheralID = peripheral.identifier.uuidString\n \n writeQueueLock.lock()\n let queue = writeQueue[peripheralID] ?? []\n writeQueue[peripheralID] = []\n writeQueueLock.unlock()\n \n if !queue.isEmpty {\n SecureLogger.log(\"Processing \\(queue.count) queued writes for \\(peripheralID)\", \n category: SecureLogger.session, level: .info)\n }\n \n // Process queued writes with small delay between them\n for (index, queuedWrite) in queue.enumerated() {\n DispatchQueue.main.asyncAfter(deadline: .now() + Double(index) * 0.01) { [weak self] in\n guard let self = self,\n peripheral.state == .connected,\n characteristic.properties.contains(.write) || characteristic.properties.contains(.writeWithoutResponse) else { \n return \n }\n \n let writeType: CBCharacteristicWriteType = queuedWrite.data.count > 512 ? .withResponse : .withoutResponse\n peripheral.writeValue(queuedWrite.data, for: characteristic, type: writeType)\n \n // Update activity tracking\n self.updatePeripheralActivity(peripheralID)\n }\n }\n }\n \n private func cleanExpiredWriteQueues() {\n writeQueueLock.lock()\n defer { writeQueueLock.unlock() }\n \n let now = Date()\n var expiredWrites = 0\n \n for (peripheralID, queue) in writeQueue {\n let filteredQueue = queue.filter { write in\n now.timeIntervalSince(write.timestamp) < writeQueueTTL\n }\n \n expiredWrites += queue.count - filteredQueue.count\n \n if filteredQueue.isEmpty {\n writeQueue.removeValue(forKey: peripheralID)\n } else {\n writeQueue[peripheralID] = filteredQueue\n }\n }\n \n if expiredWrites > 0 {\n SecureLogger.log(\"Cleaned \\(expiredWrites) expired queued writes\", \n category: SecureLogger.session, level: .debug)\n }\n }\n // MARK: - Message Processing\n \n private let messageQueue = DispatchQueue(label: \"bitchat.messageQueue\", attributes: .concurrent) // Concurrent queue with barriers\n \n // Message state tracking for better duplicate detection\n private struct MessageState {\n let firstSeen: Date\n var lastSeen: Date\n var seenCount: Int\n var relayed: Bool\n var acknowledged: Bool\n \n mutating func updateSeen() {\n lastSeen = Date()\n seenCount += 1\n }\n }\n \n private var processedMessages = [String: MessageState]() // Track full message state\n private let processedMessagesLock = NSLock()\n private let maxProcessedMessages = 10000\n \n // Special handling for identity announces to prevent duplicates\n private var recentIdentityAnnounces = [String: Date]() // peerID -> last seen time\n private let identityAnnounceDuplicateWindow: TimeInterval = 30.0 // 30 second window\n \n // MARK: - Network State Management\n \n private let maxTTL: UInt8 = 7 // Maximum hops for long-distance delivery\n private var announcedToPeers = Set() // Track which peers we've announced to\n private var announcedPeers = Set() // Track peers who have already been announced\n private var hasNotifiedNetworkAvailable = false // Track if we've notified about network availability\n private var lastNetworkNotificationTime: Date? // Track when we last sent a network notification\n private var networkBecameEmptyTime: Date? // Track when the network became empty\n private let networkNotificationCooldown: TimeInterval = 300 // 5 minutes between notifications\n private let networkEmptyResetDelay: TimeInterval = 60 // 1 minute before resetting notification flag\n private var intentionalDisconnects = Set() // Track peripherals we're disconnecting intentionally\n private var gracefullyLeftPeers = Set() // Track peers that sent leave messages\n private var gracefulLeaveTimestamps: [String: Date] = [:] // Track when peers left\n private let gracefulLeaveExpirationTime: TimeInterval = 300.0 // 5 minutes\n private var peerLastSeenTimestamps = LRUCache(maxSize: 100) // Bounded cache for peer timestamps\n private var cleanupTimer: Timer? // Timer to clean up stale peers\n \n // MARK: - Store-and-Forward Cache\n \n // Store-and-forward message cache\n private struct StoredMessage {\n let packet: BitchatPacket\n let timestamp: Date\n let messageID: String\n let isForFavorite: Bool // Messages for favorites stored indefinitely\n }\n private var messageCache: [StoredMessage] = []\n private let messageCacheTimeout: TimeInterval = 43200 // 12 hours for regular peers\n private let maxCachedMessages = 100 // For regular peers\n private let maxCachedMessagesForFavorites = 1000 // Much larger cache for favorites\n private var favoriteMessageQueue: [String: [StoredMessage]] = [:] // Per-favorite message queues\n private let deliveredMessages = BoundedSet(maxSize: 5000) // Bounded to prevent memory growth\n private var cachedMessagesSentToPeer = Set() // Track which peers have already received cached messages\n private let receivedMessageTimestamps = LRUCache(maxSize: 1000) // Bounded cache\n private let recentlySentMessages = BoundedSet(maxSize: 500) // Short-term bounded cache\n private let lastMessageFromPeer = LRUCache(maxSize: 100) // Bounded cache\n private let processedNoiseMessages = BoundedSet(maxSize: 1000) // Bounded cache\n \n // MARK: - Battery and Performance Optimization\n \n // Battery and range optimizations\n private var scanDutyCycleTimer: Timer?\n private var isActivelyScanning = true\n private var activeScanDuration: TimeInterval = 5.0 // will be adjusted based on battery\n private var scanPauseDuration: TimeInterval = 10.0 // will be adjusted based on battery\n private var lastRSSIUpdate: [String: Date] = [:] // Throttle RSSI updates\n private var batteryMonitorTimer: Timer?\n private var currentBatteryLevel: Float = 1.0 // Default to full battery\n \n // Battery optimizer integration\n private let batteryOptimizer = BatteryOptimizer.shared\n private var batteryOptimizerCancellables = Set()\n \n // Peer list update debouncing\n private var peerListUpdateTimer: Timer?\n private let peerListUpdateDebounceInterval: TimeInterval = 0.1 // 100ms debounce for more responsive updates\n \n // Track when we last sent identity announcements to prevent flooding\n private var lastIdentityAnnounceTimes: [String: Date] = [:]\n private let identityAnnounceMinInterval: TimeInterval = 10.0 // Minimum 10 seconds between announcements per peer\n \n // Track handshake attempts to handle timeouts\n private var handshakeAttemptTimes: [String: Date] = [:]\n private let handshakeTimeout: TimeInterval = 5.0 // 5 seconds before retrying\n \n // Pending private messages waiting for handshake\n private var pendingPrivateMessages: [String: [(content: String, recipientNickname: String, messageID: String)]] = [:]\n \n // MARK: - Noise Protocol State\n \n // Noise session state tracking for lazy handshakes\n private var noiseSessionStates: [String: LazyHandshakeState] = [:]\n \n // MARK: - Cover Traffic\n \n // Cover traffic for privacy\n private var coverTrafficTimer: Timer?\n private let coverTrafficPrefix = \"☂DUMMY☂\" // Prefix to identify dummy messages after decryption\n private var lastCoverTrafficTime = Date()\n \n // MARK: - Connection State\n \n // Connection state tracking\n private var peerConnectionStates: [String: PeerConnectionState] = [:]\n private let connectionStateQueue = DispatchQueue(label: \"chat.bitchat.connectionState\", attributes: .concurrent)\n \n // MARK: - Protocol ACK Tracking\n \n // Protocol-level ACK tracking\n private var pendingAcks: [String: (packet: BitchatPacket, timestamp: Date, retries: Int)] = [:]\n private let ackTimeout: TimeInterval = 5.0 // 5 seconds to receive ACK\n private let maxAckRetries = 3\n private var ackTimer: Timer?\n private var advertisingTimer: Timer? // Timer for interval-based advertising\n private var connectionKeepAliveTimer: Timer? // Timer to send keepalive pings\n private let keepAliveInterval: TimeInterval = 20.0 // Send keepalive every 20 seconds\n \n // MARK: - Timing and Delays\n \n // Timing randomization for privacy (now with exponential distribution)\n private let minMessageDelay: TimeInterval = 0.01 // 10ms minimum for faster sync\n private let maxMessageDelay: TimeInterval = 0.1 // 100ms maximum for faster sync\n \n // MARK: - RSSI Management\n \n // Dynamic RSSI threshold based on network size (smart compromise)\n private var dynamicRSSIThreshold: Int {\n let peerCount = activePeers.count\n if peerCount < 5 {\n return -95 // Maximum range when network is small\n } else if peerCount < 10 {\n return -92 // Slightly reduced range\n } else {\n return -90 // Conservative for larger networks\n }\n }\n \n // MARK: - Fragment Handling\n \n // Fragment handling with security limits\n private var incomingFragments: [String: [Int: Data]] = [:] // fragmentID -> [index: data]\n private var fragmentMetadata: [String: (originalType: UInt8, totalFragments: Int, timestamp: Date)] = [:]\n private let maxFragmentSize = 469 // 512 bytes max MTU - 43 bytes for headers and metadata\n private let maxConcurrentFragmentSessions = 20 // Limit concurrent fragment sessions to prevent DoS\n private let fragmentTimeout: TimeInterval = 30 // 30 seconds timeout for incomplete fragments\n \n // MARK: - Peer Identity\n \n var myPeerID: String\n \n // MARK: - Scaling Optimizations\n \n // Connection pooling\n private var connectionPool: [String: CBPeripheral] = [:]\n private var connectionAttempts: [String: Int] = [:]\n private var connectionBackoff: [String: TimeInterval] = [:]\n private var lastActivityByPeripheralID: [String: Date] = [:] // Track last activity for LRU\n private var peerIDByPeripheralID: [String: String] = [:] // Map peripheral ID to peer ID\n private let maxConnectionAttempts = 3\n private let baseBackoffInterval: TimeInterval = 1.0\n \n // MARK: - Peripheral Mapping\n \n // Simplified peripheral mapping system\n private struct PeripheralMapping {\n let peripheral: CBPeripheral\n var peerID: String? // nil until we receive announce\n var rssi: NSNumber?\n var lastActivity: Date\n \n var isIdentified: Bool { peerID != nil }\n }\n private var peripheralMappings: [String: PeripheralMapping] = [:] // peripheralID -> mapping\n \n // Helper methods for peripheral mapping\n private func registerPeripheral(_ peripheral: CBPeripheral) {\n let peripheralID = peripheral.identifier.uuidString\n peripheralMappings[peripheralID] = PeripheralMapping(\n peripheral: peripheral,\n peerID: nil,\n rssi: nil,\n lastActivity: Date()\n )\n }\n \n private func updatePeripheralMapping(peripheralID: String, peerID: String) {\n guard var mapping = peripheralMappings[peripheralID] else { return }\n \n // Remove old temp mapping if it exists\n let tempID = peripheralID\n if connectedPeripherals[tempID] != nil {\n connectedPeripherals.removeValue(forKey: tempID)\n }\n \n mapping.peerID = peerID\n mapping.lastActivity = Date()\n peripheralMappings[peripheralID] = mapping\n \n // Update legacy mappings\n peerIDByPeripheralID[peripheralID] = peerID\n connectedPeripherals[peerID] = mapping.peripheral\n \n // Transfer RSSI\n if let rssi = mapping.rssi {\n peerRSSI[peerID] = rssi\n }\n }\n \n private func updatePeripheralRSSI(peripheralID: String, rssi: NSNumber) {\n guard var mapping = peripheralMappings[peripheralID] else { return }\n mapping.rssi = rssi\n mapping.lastActivity = Date()\n peripheralMappings[peripheralID] = mapping\n \n // Update peer RSSI if we have the peer ID\n if let peerID = mapping.peerID {\n peerRSSI[peerID] = rssi\n }\n }\n \n private func findPeripheralForPeerID(_ peerID: String) -> CBPeripheral? {\n for (_, mapping) in peripheralMappings {\n if mapping.peerID == peerID {\n return mapping.peripheral\n }\n }\n return nil\n }\n \n // MARK: - Probabilistic Flooding\n \n // Probabilistic flooding\n private var relayProbability: Double = 1.0 // Start at 100%, decrease with peer count\n private let minRelayProbability: Double = 0.4 // Minimum 40% relay chance - ensures coverage\n \n // MARK: - Message Aggregation\n \n // Message aggregation\n private var pendingMessages: [(message: BitchatPacket, destination: String?)] = []\n private var aggregationTimer: Timer?\n private var aggregationWindow: TimeInterval = 0.1 // 100ms window\n private let maxAggregatedMessages = 5\n \n // MARK: - Bloom Filter\n \n // Optimized Bloom filter for efficient duplicate detection\n private var messageBloomFilter = OptimizedBloomFilter(expectedItems: 2000, falsePositiveRate: 0.01)\n private var bloomFilterResetTimer: Timer?\n \n // MARK: - Network Size Estimation\n \n // Network size estimation\n private var estimatedNetworkSize: Int {\n return max(activePeers.count, connectedPeripherals.count)\n }\n \n // Adaptive parameters based on network size\n private var adaptiveTTL: UInt8 {\n // Keep TTL high enough for messages to travel far\n let networkSize = estimatedNetworkSize\n if networkSize <= 20 {\n return 6 // Small networks: max distance\n } else if networkSize <= 50 {\n return 5 // Medium networks: still good reach\n } else if networkSize <= 100 {\n return 4 // Large networks: reasonable reach\n } else {\n return 3 // Very large networks: minimum viable\n }\n }\n \n private var adaptiveRelayProbability: Double {\n // Adjust relay probability based on network size\n // Small networks don't need 100% relay - RSSI will handle edge nodes\n let networkSize = estimatedNetworkSize\n if networkSize <= 2 {\n return 0.0 // 0% for 2 nodes - no relay needed with only 2 peers\n } else if networkSize <= 5 {\n return 0.5 // 50% for very small networks\n } else if networkSize <= 10 {\n return 0.6 // 60% for small networks\n } else if networkSize <= 30 {\n return 0.7 // 70% for medium networks\n } else if networkSize <= 50 {\n return 0.6 // 60% for larger networks\n } else if networkSize <= 100 {\n return 0.5 // 50% for big networks\n } else {\n return 0.4 // 40% minimum for very large networks\n }\n }\n \n // MARK: - Relay Cancellation\n \n // Relay cancellation mechanism to prevent duplicate relays\n private var pendingRelays: [String: DispatchWorkItem] = [:] // messageID -> relay task\n private let pendingRelaysLock = NSLock()\n private let relayCancellationWindow: TimeInterval = 0.05 // 50ms window to detect other relays\n \n // MARK: - Memory Management\n \n // Global memory limits to prevent unbounded growth\n private let maxPendingPrivateMessages = 100\n private let maxCachedMessagesSentToPeer = 1000\n private let maxMemoryUsageBytes = 50 * 1024 * 1024 // 50MB limit\n private var memoryCleanupTimer: Timer?\n \n // Track acknowledged packets to prevent unnecessary retries\n private var acknowledgedPackets = Set()\n private let acknowledgedPacketsLock = NSLock()\n \n // MARK: - Rate Limiting\n \n // Rate limiting for flood control with separate limits for different message types\n private var messageRateLimiter: [String: [Date]] = [:] // peerID -> recent message timestamps\n private var protocolMessageRateLimiter: [String: [Date]] = [:] // peerID -> protocol msg timestamps\n private let rateLimiterLock = NSLock()\n private let rateLimitWindow: TimeInterval = 60.0 // 1 minute window\n private let maxChatMessagesPerPeerPerMinute = 300 // Allow fast typing (5 msgs/sec)\n private let maxProtocolMessagesPerPeerPerMinute = 100 // Protocol messages\n private let maxTotalMessagesPerMinute = 2000 // Increased for legitimate use\n private var totalMessageTimestamps: [Date] = []\n \n // MARK: - BLE Advertisement\n \n // BLE advertisement for lightweight presence\n private var advertisementData: [String: Any] = [:]\n private var isAdvertising = false\n \n // MARK: - Message Aggregation Implementation\n \n private func startAggregationTimer() {\n aggregationTimer?.invalidate()\n aggregationTimer = Timer.scheduledTimer(withTimeInterval: aggregationWindow, repeats: false) { [weak self] _ in\n self?.flushPendingMessages()\n }\n }\n \n private func flushPendingMessages() {\n guard !pendingMessages.isEmpty else { return }\n \n messageQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Group messages by destination\n var messagesByDestination: [String?: [BitchatPacket]] = [:]\n \n for (message, destination) in self.pendingMessages {\n if messagesByDestination[destination] == nil {\n messagesByDestination[destination] = []\n }\n messagesByDestination[destination]?.append(message)\n }\n \n // Send aggregated messages\n for (destination, messages) in messagesByDestination {\n if messages.count == 1 {\n // Single message, send normally\n if destination == nil {\n self.broadcastPacket(messages[0])\n } else if let dest = destination,\n let peripheral = self.connectedPeripherals[dest],\n let characteristic = self.peripheralCharacteristics[peripheral] {\n if let data = messages[0].toBinaryData() {\n self.writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: dest)\n }\n }\n } else {\n // Multiple messages - could aggregate into a single packet\n // For now, send with minimal delay between them\n for (index, message) in messages.enumerated() {\n let delay = Double(index) * 0.02 // 20ms between messages\n DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in\n if destination == nil {\n self?.broadcastPacket(message)\n } else if let dest = destination,\n let peripheral = self?.connectedPeripherals[dest],\n peripheral.state == .connected,\n let characteristic = self?.peripheralCharacteristics[peripheral] {\n if let data = message.toBinaryData() {\n self?.writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: dest)\n }\n }\n }\n }\n }\n }\n \n // Clear pending messages\n self.pendingMessages.removeAll()\n }\n }\n \n // Removed getPublicKeyFingerprint - no longer needed with Noise\n \n // MARK: - Peer Identity Mapping\n \n /// Retrieves the cryptographic fingerprint for a given peer.\n /// - Parameter peerID: The ephemeral peer ID\n /// - Returns: The peer's Noise static key fingerprint if known, nil otherwise\n /// - Note: This fingerprint remains stable across peer ID rotations\n func getPeerFingerprint(_ peerID: String) -> String? {\n return noiseService.getPeerFingerprint(peerID)\n }\n \n // Get fingerprint for a peer ID\n func getFingerprint(for peerID: String) -> String? {\n return collectionsQueue.sync {\n peerIDToFingerprint[peerID]\n }\n }\n \n /// Checks if a given peer ID belongs to the local device.\n /// - Parameter peerID: The peer ID to check\n /// - Returns: true if this is our current or recent peer ID, false otherwise\n /// - Note: Accounts for grace period during peer ID rotation\n func isPeerIDOurs(_ peerID: String) -> Bool {\n if peerID == myPeerID {\n return true\n }\n \n // Check if it's our previous ID within grace period\n if let previousID = previousPeerID,\n peerID == previousID,\n let rotationTime = rotationTimestamp,\n Date().timeIntervalSince(rotationTime) < rotationGracePeriod {\n return true\n }\n \n return false\n }\n \n /// Updates the identity binding for a peer when they rotate their ephemeral ID.\n /// - Parameters:\n /// - newPeerID: The peer's new ephemeral ID\n /// - fingerprint: The peer's stable cryptographic fingerprint\n /// - binding: The complete identity binding information\n /// - Note: This maintains continuity of identity across peer ID rotations\n func updatePeerBinding(_ newPeerID: String, fingerprint: String, binding: PeerIdentityBinding) {\n // Use async to ensure we're not blocking during view updates\n collectionsQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n var oldPeerID: String? = nil\n \n // Remove old peer ID mapping if exists\n if let existingPeerID = self.fingerprintToPeerID[fingerprint], existingPeerID != newPeerID {\n oldPeerID = existingPeerID\n SecureLogger.log(\"Peer ID rotation detected: \\(existingPeerID) -> \\(newPeerID) for fingerprint \\(fingerprint)\", category: SecureLogger.security, level: .info)\n \n // Transfer gracefullyLeftPeers state from old to new peer ID\n if self.gracefullyLeftPeers.contains(existingPeerID) {\n self.gracefullyLeftPeers.remove(existingPeerID)\n self.gracefullyLeftPeers.insert(newPeerID)\n SecureLogger.log(\"Transferred gracefullyLeft state from \\(existingPeerID) to \\(newPeerID)\", \n category: SecureLogger.session, level: .debug)\n }\n \n self.peerIDToFingerprint.removeValue(forKey: existingPeerID)\n \n // Transfer nickname if known\n if let nickname = self.peerNicknames[existingPeerID] {\n self.peerNicknames[newPeerID] = nickname\n self.peerNicknames.removeValue(forKey: existingPeerID)\n }\n \n // Update active peers set - always remove old peer ID\n self.activePeers.remove(existingPeerID)\n // Don't pre-insert the new peer ID - let the announce packet handle it\n // This ensures the connect message logic works properly\n \n // Transfer any connected peripherals\n if let peripheral = self.connectedPeripherals[existingPeerID] {\n self.connectedPeripherals.removeValue(forKey: existingPeerID)\n self.connectedPeripherals[newPeerID] = peripheral\n }\n \n // Transfer RSSI data\n if let rssi = self.peerRSSI[existingPeerID] {\n self.peerRSSI.removeValue(forKey: existingPeerID)\n self.peerRSSI[newPeerID] = rssi\n }\n \n // Transfer lastHeardFromPeer tracking\n if let lastHeard = self.lastHeardFromPeer[existingPeerID] {\n self.lastHeardFromPeer.removeValue(forKey: existingPeerID)\n self.lastHeardFromPeer[newPeerID] = lastHeard\n }\n \n // Clean up connection state for old peer ID\n self.peerConnectionStates.removeValue(forKey: existingPeerID)\n // Don't transfer connection state - let it be re-established naturally\n \n // Clean up any pending messages for old peer ID\n self.pendingPrivateMessages.removeValue(forKey: existingPeerID)\n // Don't transfer pending messages - they would be stale anyway\n }\n \n // Add new mapping\n self.peerIDToFingerprint[newPeerID] = fingerprint\n self.fingerprintToPeerID[fingerprint] = newPeerID\n self.peerIdentityBindings[fingerprint] = binding\n \n // Cache public keys to avoid keychain lookups\n self.peerPublicKeyCache[newPeerID] = binding.publicKey\n self.peerSigningKeyCache[newPeerID] = binding.signingPublicKey\n self.identityCacheTimestamps[newPeerID] = Date()\n \n // Also update nickname from binding\n self.peerNicknames[newPeerID] = binding.nickname\n \n // Notify about the change if it's a rotation\n if let oldID = oldPeerID {\n // Clear the old session instead of migrating it\n // This ensures both peers do a fresh handshake after ID rotation\n self.cleanupPeerCryptoState(oldID)\n self.handshakeCoordinator.resetHandshakeState(for: newPeerID)\n \n // Log the peer ID rotation\n SecureLogger.log(\"Cleared session for peer ID rotation: \\(oldID) -> \\(newPeerID), will establish fresh handshake\", \n category: SecureLogger.handshake, level: .info)\n \n self.notifyPeerIDChange(oldPeerID: oldID, newPeerID: newPeerID, fingerprint: fingerprint)\n \n // Lazy handshake: No longer initiate handshake on peer ID rotation\n // Handshake will be initiated when first private message is sent\n }\n }\n }\n \n // Public method to get current peer ID for a fingerprint\n func getCurrentPeerIDForFingerprint(_ fingerprint: String) -> String? {\n return collectionsQueue.sync {\n return fingerprintToPeerID[fingerprint]\n }\n }\n \n // Public method to get all current peer IDs for known fingerprints\n func getCurrentPeerIDs() -> [String: String] {\n return collectionsQueue.sync {\n return fingerprintToPeerID\n }\n }\n \n // Notify delegate when peer ID changes\n private func notifyPeerIDChange(oldPeerID: String, newPeerID: String, fingerprint: String) {\n DispatchQueue.main.async { [weak self] in\n // Remove old peer ID from active peers and announcedPeers\n self?.collectionsQueue.sync(flags: .barrier) {\n _ = self?.activePeers.remove(oldPeerID)\n // Don't pre-insert the new peer ID - let the announce packet handle it\n // This ensures the connect message logic works properly\n }\n \n // Also remove from announcedPeers so the new ID can trigger a connect message\n self?.announcedPeers.remove(oldPeerID)\n \n // Update peer list\n self?.notifyPeerListUpdate(immediate: true)\n \n // Don't send disconnect/connect messages for peer ID rotation\n // The peer didn't actually disconnect, they just rotated their ID\n // This prevents confusing messages like \"3a7e1c2c0d8943b9 disconnected\"\n \n // Instead, notify the delegate about the peer ID change if needed\n // (Could add a new delegate method for this in the future)\n }\n }\n \n // MARK: - Peer Connection Management\n \n func getCachedPublicKey(for peerID: String) -> Data? {\n return collectionsQueue.sync {\n // Check if cache entry exists and is not expired\n if let timestamp = identityCacheTimestamps[peerID],\n Date().timeIntervalSince(timestamp) < identityCacheTTL {\n return peerPublicKeyCache[peerID]\n }\n return nil\n }\n }\n \n func getCachedSigningKey(for peerID: String) -> Data? {\n return collectionsQueue.sync {\n // Check if cache entry exists and is not expired\n if let timestamp = identityCacheTimestamps[peerID],\n Date().timeIntervalSince(timestamp) < identityCacheTTL {\n return peerSigningKeyCache[peerID]\n }\n return nil\n }\n }\n \n private func updatePeerConnectionState(_ peerID: String, state: PeerConnectionState) {\n connectionStateQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n let previousState = self.peerConnectionStates[peerID]\n self.peerConnectionStates[peerID] = state\n \n SecureLogger.log(\"Peer \\(peerID) connection state: \\(previousState?.description ?? \"nil\") -> \\(state)\", \n category: SecureLogger.session, level: .debug)\n \n // Update activePeers based on authentication state\n self.collectionsQueue.async(flags: .barrier) {\n switch state {\n case .authenticated:\n if !self.activePeers.contains(peerID) {\n self.activePeers.insert(peerID)\n SecureLogger.log(\"Added \\(peerID) to activePeers (authenticated)\", \n category: SecureLogger.session, level: .info)\n }\n case .disconnected:\n if self.activePeers.contains(peerID) {\n self.activePeers.remove(peerID)\n SecureLogger.log(\"Removed \\(peerID) from activePeers (disconnected)\", \n category: SecureLogger.session, level: .info)\n }\n default:\n break\n }\n \n // Always notify peer list update when connection state changes\n DispatchQueue.main.async {\n self.notifyPeerListUpdate(immediate: true)\n }\n }\n }\n }\n \n // Get peer connection state\n func getPeerConnectionState(_ peerID: String) -> PeerConnectionState {\n return connectionStateQueue.sync {\n peerConnectionStates[peerID] ?? .disconnected\n }\n }\n \n // MARK: - Peer ID Rotation\n \n private func generateNewPeerID() -> String {\n // Generate 8 random bytes (64 bits) for strong collision resistance\n var randomBytes = [UInt8](repeating: 0, count: 8)\n let result = SecRandomCopyBytes(kSecRandomDefault, 8, &randomBytes)\n \n // If SecRandomCopyBytes fails, use alternative randomization\n if result != errSecSuccess {\n for i in 0..<8 {\n randomBytes[i] = UInt8.random(in: 0...255)\n }\n }\n \n // Add timestamp entropy to ensure uniqueness\n // Use lower 32 bits of timestamp in milliseconds to avoid overflow\n let timestampMs = UInt64(Date().timeIntervalSince1970 * 1000)\n let timestamp = UInt32(timestampMs & 0xFFFFFFFF)\n randomBytes[4] = UInt8((timestamp >> 24) & 0xFF)\n randomBytes[5] = UInt8((timestamp >> 16) & 0xFF)\n randomBytes[6] = UInt8((timestamp >> 8) & 0xFF)\n randomBytes[7] = UInt8(timestamp & 0xFF)\n \n return randomBytes.map { String(format: \"%02x\", $0) }.joined()\n }\n \n func rotatePeerID() {\n guard !rotationLocked else {\n // Schedule rotation for later\n scheduleRotation(delay: 30.0)\n return\n }\n \n collectionsQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n // Save current peer ID as previous\n let oldID = self.myPeerID\n self.previousPeerID = oldID\n self.rotationTimestamp = Date()\n \n // Generate new peer ID\n self.myPeerID = self.generateNewPeerID()\n \n SecureLogger.log(\"Peer ID rotated from \\(oldID) to \\(self.myPeerID)\", category: SecureLogger.security, level: .info)\n \n // Update advertising with new peer ID\n DispatchQueue.main.async { [weak self] in\n self?.updateAdvertisement()\n }\n \n // Send identity announcement with new peer ID\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n self?.sendNoiseIdentityAnnounce()\n }\n \n // Schedule next rotation\n self.scheduleNextRotation()\n }\n }\n \n private func scheduleRotation(delay: TimeInterval) {\n DispatchQueue.main.async { [weak self] in\n self?.rotationTimer?.invalidate()\n self?.rotationTimer = Timer.scheduledTimer(withTimeInterval: delay, repeats: false) { _ in\n self?.rotatePeerID()\n }\n }\n }\n \n private func scheduleNextRotation() {\n // Base interval: 1-6 hours\n let baseInterval = TimeInterval.random(in: 3600...21600)\n \n // Add jitter: ±30 minutes\n let jitter = TimeInterval.random(in: -1800...1800)\n \n // Additional random delay to prevent synchronization\n let networkDelay = TimeInterval.random(in: 0...300) // 0-5 minutes\n \n let nextRotation = baseInterval + jitter + networkDelay\n \n scheduleRotation(delay: nextRotation)\n }\n \n private func updateAdvertisement() {\n guard isAdvertising else { return }\n \n peripheralManager?.stopAdvertising()\n \n // Update advertisement data with new peer ID\n advertisementData = [\n CBAdvertisementDataServiceUUIDsKey: [BluetoothMeshService.serviceUUID],\n CBAdvertisementDataLocalNameKey: myPeerID\n ]\n \n peripheralManager?.startAdvertising(advertisementData)\n }\n \n func lockRotation() {\n rotationLocked = true\n }\n \n func unlockRotation() {\n rotationLocked = false\n }\n \n // MARK: - Initialization\n \n override init() {\n // Generate ephemeral peer ID for each session to prevent tracking\n self.myPeerID = \"\"\n super.init()\n self.myPeerID = generateNewPeerID()\n \n centralManager = CBCentralManager(delegate: self, queue: nil)\n peripheralManager = CBPeripheralManager(delegate: self, queue: nil)\n \n // Start bloom filter reset timer (reset every 5 minutes)\n bloomFilterResetTimer = Timer.scheduledTimer(withTimeInterval: 300.0, repeats: true) { [weak self] _ in\n self?.messageQueue.async(flags: .barrier) {\n guard let self = self else { return }\n \n // Adapt Bloom filter size based on network size\n let networkSize = self.estimatedNetworkSize\n self.messageBloomFilter = OptimizedBloomFilter.adaptive(for: networkSize)\n \n // Clear other duplicate detection sets\n self.processedMessagesLock.lock()\n self.processedMessages.removeAll()\n self.processedMessagesLock.unlock()\n \n }\n }\n \n // Start stale peer cleanup timer (every 30 seconds)\n cleanupTimer = Timer.scheduledTimer(withTimeInterval: 60.0, repeats: true) { [weak self] _ in\n self?.cleanupStalePeers()\n }\n \n // Start ACK timeout checking timer (every 2 seconds for timely retries)\n Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { [weak self] _ in\n self?.checkAckTimeouts()\n }\n \n // Start peer availability checking timer (every 15 seconds)\n availabilityCheckTimer = Timer.scheduledTimer(withTimeInterval: 15.0, repeats: true) { [weak self] _ in\n self?.checkPeerAvailability()\n }\n \n // Start RSSI update timer (every 10 seconds)\n Timer.scheduledTimer(withTimeInterval: 10.0, repeats: true) { [weak self] _ in\n self?.updateAllPeripheralRSSI()\n }\n \n // Start write queue cleanup timer (every 30 seconds)\n writeQueueTimer = Timer.scheduledTimer(withTimeInterval: 30.0, repeats: true) { [weak self] _ in\n self?.cleanExpiredWriteQueues()\n }\n \n // Start identity cache cleanup timer (every hour)\n Timer.scheduledTimer(withTimeInterval: 3600.0, repeats: true) { [weak self] _ in\n self?.cleanExpiredIdentityCache()\n }\n \n // Start memory cleanup timer (every minute)\n startMemoryCleanupTimer()\n \n // Start connection keep-alive timer to prevent iOS BLE timeouts\n connectionKeepAliveTimer = Timer.scheduledTimer(withTimeInterval: keepAliveInterval, repeats: true) { [weak self] _ in\n self?.sendKeepAlivePings()\n }\n \n // Log handshake states periodically for debugging and clean up stale states\n #if DEBUG\n Timer.scheduledTimer(withTimeInterval: 30.0, repeats: true) { [weak self] _ in\n guard let self = self else { return }\n \n // Clean up stale handshakes\n let stalePeerIDs = self.handshakeCoordinator.cleanupStaleHandshakes()\n if !stalePeerIDs.isEmpty {\n for peerID in stalePeerIDs {\n // Also remove from noise service\n self.cleanupPeerCryptoState(peerID)\n SecureLogger.log(\"Cleaned up stale handshake for \\(peerID)\", category: SecureLogger.handshake, level: .info)\n }\n }\n \n self.handshakeCoordinator.logHandshakeStates()\n }\n #endif\n \n // Schedule first peer ID rotation\n scheduleNextRotation()\n \n // Setup noise callbacks\n noiseService.onPeerAuthenticated = { [weak self] peerID, fingerprint in\n // Get peer's public key data from noise service\n if let publicKeyData = self?.noiseService.getPeerPublicKeyData(peerID) {\n // Register with ChatViewModel for verification tracking\n DispatchQueue.main.async {\n (self?.delegate as? ChatViewModel)?.registerPeerPublicKey(peerID: peerID, publicKeyData: publicKeyData)\n \n // Force UI to update encryption status for this specific peer\n (self?.delegate as? ChatViewModel)?.updateEncryptionStatusForPeer(peerID)\n }\n }\n \n // Send regular announce packet when authenticated to trigger connect message\n // This covers the case where we're the responder in the handshake\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in\n self?.sendAnnouncementToPeer(peerID)\n }\n }\n \n // Register for app termination notifications\n #if os(macOS)\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillTerminate),\n name: NSApplication.willTerminateNotification,\n object: nil\n )\n #else\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillTerminate),\n name: UIApplication.willTerminateNotification,\n object: nil\n )\n #endif\n }\n \n // MARK: - Deinitialization and Cleanup\n \n deinit {\n cleanup()\n scanDutyCycleTimer?.invalidate()\n batteryMonitorTimer?.invalidate()\n coverTrafficTimer?.invalidate()\n bloomFilterResetTimer?.invalidate()\n aggregationTimer?.invalidate()\n cleanupTimer?.invalidate()\n rotationTimer?.invalidate()\n memoryCleanupTimer?.invalidate()\n connectionKeepAliveTimer?.invalidate()\n availabilityCheckTimer?.invalidate()\n }\n \n @objc private func appWillTerminate() {\n cleanup()\n }\n \n private func cleanup() {\n // Send leave announcement before disconnecting\n sendLeaveAnnouncement()\n \n // Give the leave message time to send\n Thread.sleep(forTimeInterval: 0.2)\n \n // First, disconnect all peripherals which will trigger disconnect delegates\n for (_, peripheral) in connectedPeripherals {\n centralManager?.cancelPeripheralConnection(peripheral)\n }\n \n // Stop advertising\n if peripheralManager?.isAdvertising == true {\n peripheralManager?.stopAdvertising()\n }\n \n // Stop scanning\n centralManager?.stopScan()\n \n // Remove all services - this will disconnect any connected centrals\n if peripheralManager?.state == .poweredOn {\n peripheralManager?.removeAllServices()\n }\n \n // Clear all tracking\n connectedPeripherals.removeAll()\n subscribedCentrals.removeAll()\n collectionsQueue.sync(flags: .barrier) {\n activePeers.removeAll()\n }\n announcedPeers.removeAll()\n // For normal disconnect, respect the timing\n networkBecameEmptyTime = Date()\n \n // Clear announcement tracking\n announcedToPeers.removeAll()\n \n // Clear last seen timestamps\n peerLastSeenTimestamps.removeAll()\n \n // Clear all encryption queues\n encryptionQueuesLock.lock()\n peerEncryptionQueues.removeAll()\n encryptionQueuesLock.unlock()\n \n // Clear peer tracking\n lastHeardFromPeer.removeAll()\n }\n \n // MARK: - Service Management\n \n /// Starts the Bluetooth mesh networking services.\n /// This initializes both central (scanning) and peripheral (advertising) modes,\n /// enabling the device to both discover peers and be discovered.\n /// Call this method after setting the delegate and localUserID.\n func startServices() {\n // Starting services\n // Start both central and peripheral services\n if centralManager?.state == .poweredOn {\n startScanning()\n }\n if peripheralManager?.state == .poweredOn {\n setupPeripheral()\n startAdvertising()\n }\n \n // Send initial announces after services are ready\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [weak self] in\n self?.sendBroadcastAnnounce()\n }\n \n // Setup battery optimizer\n setupBatteryOptimizer()\n \n // Start cover traffic for privacy (disabled by default for now)\n // TODO: Make this configurable in settings\n let coverTrafficEnabled = true\n if coverTrafficEnabled {\n SecureLogger.log(\"Cover traffic enabled\", category: SecureLogger.security, level: .info)\n startCoverTraffic()\n }\n }\n \n // MARK: - Message Sending\n \n func sendBroadcastAnnounce() {\n guard let vm = delegate as? ChatViewModel else { return }\n \n \n let announcePacket = BitchatPacket(\n type: MessageType.announce.rawValue,\n ttl: 3, // Increase TTL so announce reaches all peers\n senderID: myPeerID,\n payload: Data(vm.nickname.utf8) )\n \n \n // Single send with smart collision avoidance\n let initialDelay = self.smartCollisionAvoidanceDelay(baseDelay: self.randomDelay())\n DispatchQueue.main.asyncAfter(deadline: .now() + initialDelay) { [weak self] in\n self?.broadcastPacket(announcePacket)\n \n // Don't automatically send identity announcement on startup\n // Let it happen naturally when peers connect\n }\n }\n \n func startAdvertising() {\n guard peripheralManager?.state == .poweredOn else { \n return \n }\n \n // Use generic advertising to avoid identification\n // No identifying prefixes or app names for activist safety\n \n // Only use allowed advertisement keys\n advertisementData = [\n CBAdvertisementDataServiceUUIDsKey: [BluetoothMeshService.serviceUUID],\n // Use only peer ID without any identifying prefix\n CBAdvertisementDataLocalNameKey: myPeerID\n ]\n \n isAdvertising = true\n peripheralManager?.startAdvertising(advertisementData)\n }\n \n func startScanning() {\n guard centralManager?.state == .poweredOn else { \n return \n }\n \n // Enable duplicate detection for RSSI tracking\n let scanOptions: [String: Any] = [\n CBCentralManagerScanOptionAllowDuplicatesKey: true\n ]\n \n centralManager?.scanForPeripherals(\n withServices: [BluetoothMeshService.serviceUUID],\n options: scanOptions\n )\n \n // Update scan parameters based on battery before starting\n updateScanParametersForBattery()\n \n // Implement scan duty cycling for battery efficiency\n scheduleScanDutyCycle()\n }\n \n private func scheduleScanDutyCycle() {\n guard scanDutyCycleTimer == nil else { return }\n \n // Start with active scanning\n isActivelyScanning = true\n \n scanDutyCycleTimer = Timer.scheduledTimer(withTimeInterval: activeScanDuration, repeats: true) { [weak self] _ in\n guard let self = self else { return }\n \n if self.isActivelyScanning {\n // Pause scanning to save battery\n self.centralManager?.stopScan()\n self.isActivelyScanning = false\n \n // Schedule resume\n DispatchQueue.main.asyncAfter(deadline: .now() + self.scanPauseDuration) { [weak self] in\n guard let self = self else { return }\n if self.centralManager?.state == .poweredOn {\n self.centralManager?.scanForPeripherals(\n withServices: [BluetoothMeshService.serviceUUID],\n options: [CBCentralManagerScanOptionAllowDuplicatesKey: true]\n )\n self.isActivelyScanning = true\n }\n }\n }\n }\n }\n \n private func setupPeripheral() {\n let characteristic = CBMutableCharacteristic(\n type: BluetoothMeshService.characteristicUUID,\n properties: [.read, .write, .writeWithoutResponse, .notify],\n value: nil,\n permissions: [.readable, .writeable]\n )\n \n let service = CBMutableService(type: BluetoothMeshService.serviceUUID, primary: true)\n service.characteristics = [characteristic]\n \n peripheralManager?.add(service)\n self.characteristic = characteristic\n }\n \n /// Sends a message through the mesh network.\n /// - Parameters:\n /// - content: The message content to send\n /// - mentions: Array of user IDs being mentioned in the message\n /// - recipientID: Optional recipient ID for directed messages (nil for broadcast)\n /// - messageID: Optional custom message ID (auto-generated if nil)\n /// - timestamp: Optional custom timestamp (current time if nil)\n /// - Note: Messages are automatically routed through the mesh using TTL-based forwarding\n func sendMessage(_ content: String, mentions: [String] = [], to recipientID: String? = nil, messageID: String? = nil, timestamp: Date? = nil) {\n // Defensive check for empty content\n guard !content.isEmpty else { return }\n messageQueue.async { [weak self] in\n guard let self = self else { return }\n \n let nickname = self.delegate as? ChatViewModel\n let senderNick = nickname?.nickname ?? self.myPeerID\n \n let message = BitchatMessage(\n id: messageID,\n sender: senderNick,\n content: content,\n timestamp: timestamp ?? Date(),\n isRelay: false,\n originalSender: nil,\n isPrivate: false,\n recipientNickname: nil,\n senderPeerID: self.myPeerID,\n mentions: mentions.isEmpty ? nil : mentions\n )\n \n if let messageData = message.toBinaryPayload() {\n \n \n // Use unified message type with broadcast recipient\n let packet = BitchatPacket(\n type: MessageType.message.rawValue,\n senderID: Data(hexString: self.myPeerID) ?? Data(),\n recipientID: SpecialRecipients.broadcast, // Special broadcast ID\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000), // milliseconds\n payload: messageData,\n signature: nil,\n ttl: self.adaptiveTTL )\n \n // Track this message to prevent duplicate sends\n let msgID = \"\\(packet.timestamp)-\\(self.myPeerID)-\\(packet.payload.prefix(32).hashValue)\"\n \n let shouldSend = !self.recentlySentMessages.contains(msgID)\n if shouldSend {\n self.recentlySentMessages.insert(msgID)\n }\n \n if shouldSend {\n // Clean up old entries after 10 seconds\n self.messageQueue.asyncAfter(deadline: .now() + 10.0) { [weak self] in\n guard let self = self else { return }\n self.recentlySentMessages.remove(msgID)\n }\n \n // Single send with smart collision avoidance\n let initialDelay = self.smartCollisionAvoidanceDelay(baseDelay: self.randomDelay())\n DispatchQueue.main.asyncAfter(deadline: .now() + initialDelay) { [weak self] in\n self?.broadcastPacket(packet)\n }\n }\n }\n }\n }\n \n \n /// Sends an end-to-end encrypted private message to a specific peer.\n /// - Parameters:\n /// - content: The message content to encrypt and send\n /// - recipientPeerID: The peer ID of the recipient\n /// - recipientNickname: The nickname of the recipient (for UI display)\n /// - messageID: Optional custom message ID (auto-generated if nil)\n /// - Note: This method automatically handles Noise handshake if not already established\n func sendPrivateMessage(_ content: String, to recipientPeerID: String, recipientNickname: String, messageID: String? = nil) {\n // Defensive checks\n guard !content.isEmpty, !recipientPeerID.isEmpty, !recipientNickname.isEmpty else { \n return \n }\n \n let msgID = messageID ?? UUID().uuidString\n \n messageQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Check if this is an old peer ID that has rotated\n var targetPeerID = recipientPeerID\n \n // If we have a fingerprint for this peer ID, check if there's a newer peer ID\n if let fingerprint = self.collectionsQueue.sync(execute: { self.peerIDToFingerprint[recipientPeerID] }),\n let currentPeerID = self.collectionsQueue.sync(execute: { self.fingerprintToPeerID[fingerprint] }),\n currentPeerID != recipientPeerID {\n // Use the current peer ID instead\n targetPeerID = currentPeerID\n }\n \n // Always use Noise encryption\n self.sendPrivateMessageViaNoise(content, to: targetPeerID, recipientNickname: recipientNickname, messageID: msgID)\n }\n }\n \n func sendDeliveryAck(_ ack: DeliveryAck, to recipientID: String) {\n // Use per-peer encryption queue to prevent nonce desynchronization\n let encryptionQueue = getEncryptionQueue(for: recipientID)\n \n encryptionQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Encode the ACK\n let ackData = ack.toBinaryData()\n \n // Check if we have a Noise session with this peer\n // Use noiseService directly\n if self.noiseService.hasEstablishedSession(with: recipientID) {\n // Use Noise encryption - encrypt only the ACK payload directly\n do {\n // Create a special payload that indicates this is a delivery ACK\n // Format: [1 byte type marker] + [ACK JSON data]\n var ackPayload = Data()\n ackPayload.append(MessageType.deliveryAck.rawValue) // Type marker\n ackPayload.append(ackData) // ACK JSON\n \n // Encrypt only the payload (not a full packet)\n let encryptedPayload = try noiseService.encrypt(ackPayload, for: recipientID)\n \n // Create outer Noise packet with the encrypted payload\n let outerPacket = BitchatPacket(\n type: MessageType.noiseEncrypted.rawValue,\n senderID: Data(hexString: self.myPeerID) ?? Data(),\n recipientID: Data(hexString: recipientID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: encryptedPayload,\n signature: nil,\n ttl: 3 )\n \n // Try direct delivery first for delivery ACKs\n if !self.sendDirectToRecipient(outerPacket, recipientPeerID: recipientID) {\n // Recipient not directly connected, use selective relay\n SecureLogger.log(\"Recipient \\(recipientID) not directly connected for delivery ACK, using relay\", \n category: SecureLogger.session, level: .info)\n self.sendViaSelectiveRelay(outerPacket, recipientPeerID: recipientID)\n }\n } catch {\n SecureLogger.logError(error, context: \"Failed to encrypt delivery ACK via Noise for \\(recipientID)\", category: SecureLogger.encryption)\n }\n } else {\n // Lazy handshake: No session available, drop the ACK\n SecureLogger.log(\"No Noise session with \\(recipientID) for delivery ACK - dropping (lazy handshake mode)\", \n category: SecureLogger.noise, level: .info)\n }\n }\n }\n \n private func getEncryptionQueue(for peerID: String) -> DispatchQueue {\n encryptionQueuesLock.lock()\n defer { encryptionQueuesLock.unlock() }\n \n if let queue = peerEncryptionQueues[peerID] {\n return queue\n }\n \n let queue = DispatchQueue(label: \"bitchat.encryption.\\(peerID)\", qos: .userInitiated)\n peerEncryptionQueues[peerID] = queue\n return queue\n }\n \n private func removeEncryptionQueue(for peerID: String) {\n encryptionQueuesLock.lock()\n defer { encryptionQueuesLock.unlock() }\n \n peerEncryptionQueues.removeValue(forKey: peerID)\n }\n \n // Centralized cleanup for peer crypto state\n private func cleanupPeerCryptoState(_ peerID: String) {\n noiseService.removePeer(peerID)\n handshakeCoordinator.resetHandshakeState(for: peerID)\n removeEncryptionQueue(for: peerID)\n }\n \n func sendReadReceipt(_ receipt: ReadReceipt, to recipientID: String) {\n // Use per-peer encryption queue to prevent nonce desynchronization\n let encryptionQueue = getEncryptionQueue(for: recipientID)\n \n encryptionQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Encode the receipt\n let receiptData = receipt.toBinaryData()\n \n // Check if we have a Noise session with this peer\n // Use noiseService directly\n if self.noiseService.hasEstablishedSession(with: recipientID) {\n // Use Noise encryption - encrypt only the receipt payload directly\n do {\n // Create a special payload that indicates this is a read receipt\n // Format: [1 byte type marker] + [receipt binary data]\n var receiptPayload = Data()\n receiptPayload.append(MessageType.readReceipt.rawValue) // Type marker\n receiptPayload.append(receiptData) // Receipt binary data\n \n // Encrypt only the payload (not a full packet)\n let encryptedPayload = try noiseService.encrypt(receiptPayload, for: recipientID)\n \n // Create outer Noise packet with the encrypted payload\n let outerPacket = BitchatPacket(\n type: MessageType.noiseEncrypted.rawValue,\n senderID: Data(hexString: self.myPeerID) ?? Data(),\n recipientID: Data(hexString: recipientID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: encryptedPayload,\n signature: nil,\n ttl: 3 )\n \n SecureLogger.log(\"Sending encrypted read receipt for message \\(receipt.originalMessageID) to \\(recipientID)\", category: SecureLogger.noise, level: .info)\n \n // Try direct delivery first for read receipts\n if !self.sendDirectToRecipient(outerPacket, recipientPeerID: recipientID) {\n // Recipient not directly connected, use selective relay\n SecureLogger.log(\"Recipient \\(recipientID) not directly connected for read receipt, using relay\", \n category: SecureLogger.session, level: .info)\n self.sendViaSelectiveRelay(outerPacket, recipientPeerID: recipientID)\n }\n } catch {\n SecureLogger.logError(error, context: \"Failed to encrypt read receipt via Noise for \\(recipientID)\", category: SecureLogger.encryption)\n }\n } else {\n // Lazy handshake: No session available, drop the read receipt\n SecureLogger.log(\"No Noise session with \\(recipientID) for read receipt - dropping (lazy handshake mode)\", \n category: SecureLogger.noise, level: .info)\n }\n }\n }\n \n \n \n \n \n private func sendAnnouncementToPeer(_ peerID: String) {\n guard let vm = delegate as? ChatViewModel else { return }\n \n \n // Always send announce, don't check if already announced\n // This ensures peers get our nickname even if they reconnect\n \n let packet = BitchatPacket(\n type: MessageType.announce.rawValue,\n ttl: 3, // Allow relay for better reach\n senderID: myPeerID,\n payload: Data(vm.nickname.utf8) )\n \n if let data = packet.toBinaryData() {\n // Try both broadcast and targeted send\n broadcastPacket(packet)\n \n // Also try targeted send if we have the peripheral\n if let peripheral = connectedPeripherals[peerID],\n peripheral.state == .connected,\n let characteristic = peripheral.services?.first(where: { $0.uuid == BluetoothMeshService.serviceUUID })?.characteristics?.first(where: { $0.uuid == BluetoothMeshService.characteristicUUID }) {\n writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: peerID)\n } else {\n }\n } else {\n }\n \n announcedToPeers.insert(peerID)\n }\n \n private func sendLeaveAnnouncement() {\n guard let vm = delegate as? ChatViewModel else { return }\n \n let packet = BitchatPacket(\n type: MessageType.leave.rawValue,\n ttl: 1, // Don't relay leave messages\n senderID: myPeerID,\n payload: Data(vm.nickname.utf8) )\n \n broadcastPacket(packet)\n }\n \n // Get Noise session state for UI display\n func getNoiseSessionState(for peerID: String) -> LazyHandshakeState {\n return collectionsQueue.sync {\n // First check our tracked state\n if let state = noiseSessionStates[peerID] {\n return state\n }\n \n // If no tracked state, check if we have an established session\n if noiseService.hasEstablishedSession(with: peerID) {\n return .established\n }\n \n // Default to none\n return .none\n }\n }\n \n // Trigger handshake with a peer (for UI)\n func triggerHandshake(with peerID: String) {\n SecureLogger.log(\"UI triggered handshake with \\(peerID)\", category: SecureLogger.noise, level: .info)\n \n // Check if we already have a session\n if noiseService.hasEstablishedSession(with: peerID) {\n SecureLogger.log(\"Already have session with \\(peerID), skipping handshake\", category: SecureLogger.noise, level: .debug)\n return\n }\n \n // Update state to handshakeQueued\n collectionsQueue.sync(flags: .barrier) {\n noiseSessionStates[peerID] = .handshakeQueued\n }\n \n // Always initiate handshake when triggered by UI\n // This ensures immediate handshake when opening PM\n initiateNoiseHandshake(with: peerID)\n }\n \n func getPeerNicknames() -> [String: String] {\n return collectionsQueue.sync {\n return peerNicknames\n }\n }\n \n func getPeerRSSI() -> [String: NSNumber] {\n var rssiValues = peerRSSI\n \n \n // Log connectedPeripherals state\n SecureLogger.log(\"connectedPeripherals has \\(connectedPeripherals.count) entries:\", category: SecureLogger.session, level: .debug)\n for (peerID, peripheral) in connectedPeripherals {\n SecureLogger.log(\" connectedPeripherals[\\(peerID)] = \\(peripheral.identifier.uuidString)\", category: SecureLogger.session, level: .debug)\n }\n \n \n // Also check peripheralRSSI for any connected peripherals\n // This handles cases where RSSI is stored under temp IDs\n for (peerID, peripheral) in connectedPeripherals {\n // Skip temp IDs when iterating\n if peerID.count != 16 {\n continue\n }\n \n // If we don't have RSSI for this peer ID\n if rssiValues[peerID] == nil {\n \n // Check if we have RSSI stored by peripheral ID\n let peripheralID = peripheral.identifier.uuidString\n if let rssi = peripheralRSSI[peripheralID] {\n rssiValues[peerID] = rssi\n }\n // Also check if RSSI is stored under the peer ID as a temp ID\n else if let rssi = peripheralRSSI[peerID] {\n rssiValues[peerID] = rssi\n }\n }\n }\n \n // Also check for any known peers that might have RSSI in peerRSSI but not in connectedPeripherals\n for (peerID, _) in peerNicknames {\n if rssiValues[peerID] == nil && peerID.count == 16 {\n // Check if we have RSSI stored directly\n if let rssi = peerRSSI[peerID] {\n rssiValues[peerID] = rssi\n } else if let rssi = peripheralRSSI[peerID] {\n rssiValues[peerID] = rssi\n }\n }\n }\n \n \n return rssiValues\n }\n \n // Emergency disconnect for panic situations\n func emergencyDisconnectAll() {\n SecureLogger.log(\"Emergency disconnect triggered\", category: SecureLogger.security, level: .warning)\n \n // Stop advertising immediately\n if peripheralManager?.isAdvertising == true {\n peripheralManager?.stopAdvertising()\n }\n \n // Stop scanning\n centralManager?.stopScan()\n scanDutyCycleTimer?.invalidate()\n scanDutyCycleTimer = nil\n \n // Disconnect all peripherals\n for (peerID, peripheral) in connectedPeripherals {\n SecureLogger.log(\"Emergency disconnect peer: \\(peerID)\", category: SecureLogger.session, level: .warning)\n centralManager?.cancelPeripheralConnection(peripheral)\n }\n \n // Clear all peer data\n connectedPeripherals.removeAll()\n peripheralCharacteristics.removeAll()\n discoveredPeripherals.removeAll()\n subscribedCentrals.removeAll()\n peerNicknames.removeAll()\n activePeers.removeAll()\n peerRSSI.removeAll()\n peripheralRSSI.removeAll()\n rssiRetryCount.removeAll()\n announcedToPeers.removeAll()\n announcedPeers.removeAll()\n // For emergency/panic, reset immediately\n hasNotifiedNetworkAvailable = false\n networkBecameEmptyTime = nil\n lastNetworkNotificationTime = nil\n processedMessagesLock.lock()\n processedMessages.removeAll()\n processedMessagesLock.unlock()\n incomingFragments.removeAll()\n \n // Clear all encryption queues\n encryptionQueuesLock.lock()\n peerEncryptionQueues.removeAll()\n encryptionQueuesLock.unlock()\n fragmentMetadata.removeAll()\n \n // Cancel all pending relays\n pendingRelaysLock.lock()\n for (_, relay) in pendingRelays {\n relay.cancel()\n }\n pendingRelays.removeAll()\n pendingRelaysLock.unlock()\n \n // Clear peer tracking\n lastHeardFromPeer.removeAll()\n \n // Clear persistent identity\n noiseService.clearPersistentIdentity()\n \n // Clear all handshake coordinator states\n handshakeCoordinator.clearAllHandshakeStates()\n \n // Clear handshake attempt times\n handshakeAttemptTimes.removeAll()\n \n // Notify UI that all peers are disconnected\n DispatchQueue.main.async { [weak self] in\n self?.delegate?.didUpdatePeerList([])\n }\n }\n \n private func getAllConnectedPeerIDs() -> [String] {\n // Return all valid active peers\n let peersCopy = collectionsQueue.sync {\n return activePeers\n }\n \n \n let validPeers = peersCopy.filter { peerID in\n // Ensure peerID is valid and not self\n let isEmpty = peerID.isEmpty\n let isUnknown = peerID == \"unknown\"\n let isSelf = peerID == self.myPeerID\n \n return !isEmpty && !isUnknown && !isSelf\n }\n \n let result = Array(validPeers).sorted()\n return result\n }\n \n // Debounced peer list update notification\n private func notifyPeerListUpdate(immediate: Bool = false) {\n if immediate {\n // For initial connections, update immediately\n let connectedPeerIDs = self.getAllConnectedPeerIDs()\n \n DispatchQueue.main.async {\n self.delegate?.didUpdatePeerList(connectedPeerIDs)\n }\n } else {\n // Must schedule timer on main thread\n DispatchQueue.main.async { [weak self] in\n guard let self = self else { return }\n \n // Cancel any pending update\n self.peerListUpdateTimer?.invalidate()\n \n // Schedule a new update after debounce interval\n self.peerListUpdateTimer = Timer.scheduledTimer(withTimeInterval: self.peerListUpdateDebounceInterval, repeats: false) { [weak self] _ in\n guard let self = self else { return }\n \n let connectedPeerIDs = self.getAllConnectedPeerIDs()\n \n self.delegate?.didUpdatePeerList(connectedPeerIDs)\n }\n }\n }\n }\n \n // Clean up stale peers that haven't been seen in a while\n private func cleanupStalePeers() {\n let staleThreshold: TimeInterval = 180.0 // 3 minutes - increased for better stability\n let now = Date()\n \n // Clean up expired gracefully left peers\n let expiredGracefulPeers = gracefulLeaveTimestamps.filter { (_, timestamp) in\n now.timeIntervalSince(timestamp) > gracefulLeaveExpirationTime\n }.map { $0.key }\n \n for peerID in expiredGracefulPeers {\n gracefullyLeftPeers.remove(peerID)\n gracefulLeaveTimestamps.removeValue(forKey: peerID)\n SecureLogger.log(\"Cleaned up expired gracefullyLeft entry for \\(peerID)\", \n category: SecureLogger.session, level: .debug)\n }\n \n let peersToRemove = collectionsQueue.sync(flags: .barrier) {\n let toRemove = activePeers.filter { peerID in\n if let lastSeen = peerLastSeenTimestamps.get(peerID) {\n return now.timeIntervalSince(lastSeen) > staleThreshold\n }\n return false // Keep peers we haven't tracked yet\n }\n \n var actuallyRemoved: [String] = []\n \n for peerID in toRemove {\n // Check if this peer has an active peripheral connection\n if let peripheral = connectedPeripherals[peerID], peripheral.state == .connected {\n // Skipping removal - still has active connection\n // Update last seen time to prevent immediate re-removal\n peerLastSeenTimestamps.set(peerID, value: Date())\n continue\n }\n \n let nickname = peerNicknames[peerID] ?? \"unknown\"\n activePeers.remove(peerID)\n peerLastSeenTimestamps.remove(peerID)\n SecureLogger.log(\"📴 Removed stale peer from network: \\(peerID) (\\(nickname))\", category: SecureLogger.session, level: .info)\n \n // Clean up all associated data\n connectedPeripherals.removeValue(forKey: peerID)\n peerRSSI.removeValue(forKey: peerID)\n announcedPeers.remove(peerID)\n announcedToPeers.remove(peerID)\n peerNicknames.removeValue(forKey: peerID)\n lastHeardFromPeer.removeValue(forKey: peerID)\n \n actuallyRemoved.append(peerID)\n // Removed stale peer\n }\n return actuallyRemoved\n }\n \n if !peersToRemove.isEmpty {\n notifyPeerListUpdate()\n \n // Mark when network became empty, but don't reset flag immediately\n let currentNetworkSize = collectionsQueue.sync { activePeers.count }\n if currentNetworkSize == 0 && networkBecameEmptyTime == nil {\n networkBecameEmptyTime = Date()\n }\n }\n \n // Check if we should reset the notification flag\n if let emptyTime = networkBecameEmptyTime {\n let currentNetworkSize = collectionsQueue.sync { activePeers.count }\n if currentNetworkSize == 0 {\n // Network is still empty, check if enough time has passed\n let timeSinceEmpty = Date().timeIntervalSince(emptyTime)\n if timeSinceEmpty >= networkEmptyResetDelay {\n // Reset the flag after network has been empty for the delay period\n hasNotifiedNetworkAvailable = false\n // Keep the empty time set so we don't immediately notify again\n }\n } else {\n // Network is no longer empty, clear the empty time\n networkBecameEmptyTime = nil\n }\n }\n }\n \n // MARK: - Store-and-Forward Methods\n \n private func cacheMessage(_ packet: BitchatPacket, messageID: String) {\n messageQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n // Don't cache certain message types\n guard packet.type != MessageType.announce.rawValue,\n packet.type != MessageType.leave.rawValue,\n packet.type != MessageType.fragmentStart.rawValue,\n packet.type != MessageType.fragmentContinue.rawValue,\n packet.type != MessageType.fragmentEnd.rawValue else {\n return\n }\n \n // Don't cache broadcast messages\n if let recipientID = packet.recipientID,\n recipientID == SpecialRecipients.broadcast {\n return // Never cache broadcast messages\n }\n \n // Check if this is a private message for a favorite\n var isForFavorite = false\n if packet.type == MessageType.message.rawValue,\n let recipientID = packet.recipientID {\n let recipientPeerID = recipientID.hexEncodedString()\n // Check if recipient is a favorite via their public key fingerprint\n if let fingerprint = self.noiseService.getPeerFingerprint(recipientPeerID) {\n isForFavorite = self.delegate?.isFavorite(fingerprint: fingerprint) ?? false\n }\n }\n \n // Create stored message with original packet timestamp preserved\n let storedMessage = StoredMessage(\n packet: packet,\n timestamp: Date(timeIntervalSince1970: TimeInterval(packet.timestamp) / 1000.0), // convert from milliseconds\n messageID: messageID,\n isForFavorite: isForFavorite\n )\n \n \n if isForFavorite {\n if let recipientID = packet.recipientID {\n let recipientPeerID = recipientID.hexEncodedString()\n if self.favoriteMessageQueue[recipientPeerID] == nil {\n self.favoriteMessageQueue[recipientPeerID] = []\n }\n self.favoriteMessageQueue[recipientPeerID]?.append(storedMessage)\n \n // Limit favorite queue size\n if let count = self.favoriteMessageQueue[recipientPeerID]?.count,\n count > self.maxCachedMessagesForFavorites {\n self.favoriteMessageQueue[recipientPeerID]?.removeFirst()\n }\n \n }\n } else {\n // Clean up old messages first (only for regular cache)\n self.cleanupMessageCache()\n \n // Add to regular cache\n self.messageCache.append(storedMessage)\n \n // Limit cache size\n if self.messageCache.count > self.maxCachedMessages {\n self.messageCache.removeFirst()\n }\n \n }\n }\n }\n \n private func cleanupMessageCache() {\n let cutoffTime = Date().addingTimeInterval(-messageCacheTimeout)\n // Only remove non-favorite messages that are older than timeout\n messageCache.removeAll { !$0.isForFavorite && $0.timestamp < cutoffTime }\n \n // Clean up delivered messages set periodically (keep recent 1000 entries)\n if deliveredMessages.count > 1000 {\n // Clear older entries while keeping recent ones\n deliveredMessages.removeAll()\n }\n }\n \n private func sendCachedMessages(to peerID: String) {\n messageQueue.async { [weak self] in\n guard let self = self,\n let peripheral = self.connectedPeripherals[peerID],\n let characteristic = self.peripheralCharacteristics[peripheral] else {\n return\n }\n \n \n // Check if we've already sent cached messages to this peer in this session\n if self.cachedMessagesSentToPeer.contains(peerID) {\n return // Already sent cached messages to this peer in this session\n }\n \n // Mark that we're sending cached messages to this peer\n self.cachedMessagesSentToPeer.insert(peerID)\n \n // Clean up old messages first\n self.cleanupMessageCache()\n \n var messagesToSend: [StoredMessage] = []\n \n // First, check if this peer has any favorite messages waiting\n if let favoriteMessages = self.favoriteMessageQueue[peerID] {\n // Filter out already delivered messages\n let undeliveredFavoriteMessages = favoriteMessages.filter { !self.deliveredMessages.contains($0.messageID) }\n messagesToSend.append(contentsOf: undeliveredFavoriteMessages)\n // Clear the favorite queue after adding to send list\n self.favoriteMessageQueue[peerID] = nil\n }\n \n // Filter regular cached messages for this specific recipient\n let recipientMessages = self.messageCache.filter { storedMessage in\n if self.deliveredMessages.contains(storedMessage.messageID) {\n return false\n }\n if let recipientID = storedMessage.packet.recipientID {\n let recipientPeerID = recipientID.hexEncodedString()\n return recipientPeerID == peerID\n }\n return false // Don't forward broadcast messages\n }\n messagesToSend.append(contentsOf: recipientMessages)\n \n \n // Sort messages by timestamp to ensure proper ordering\n messagesToSend.sort { $0.timestamp < $1.timestamp }\n \n if !messagesToSend.isEmpty {\n }\n \n // Mark messages as delivered immediately to prevent duplicates\n let messageIDsToRemove = messagesToSend.map { $0.messageID }\n for messageID in messageIDsToRemove {\n self.deliveredMessages.insert(messageID)\n }\n \n // Send cached messages with slight delay between each\n for (index, storedMessage) in messagesToSend.enumerated() {\n let delay = Double(index) * 0.02 // 20ms between messages for faster sync\n \n DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self, weak peripheral] in\n guard let peripheral = peripheral,\n peripheral.state == .connected else {\n return\n }\n \n // Send the original packet with preserved timestamp\n let packetToSend = storedMessage.packet\n \n if let data = packetToSend.toBinaryData(),\n characteristic.properties.contains(.writeWithoutResponse) {\n self?.writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: peerID)\n }\n }\n }\n \n // Remove sent messages immediately\n if !messageIDsToRemove.isEmpty {\n self.messageQueue.async(flags: .barrier) {\n // Remove only the messages we sent to this specific peer\n self.messageCache.removeAll { message in\n messageIDsToRemove.contains(message.messageID)\n }\n \n // Also remove from favorite queue if any\n if var favoriteQueue = self.favoriteMessageQueue[peerID] {\n favoriteQueue.removeAll { message in\n messageIDsToRemove.contains(message.messageID)\n }\n self.favoriteMessageQueue[peerID] = favoriteQueue.isEmpty ? nil : favoriteQueue\n }\n }\n }\n }\n }\n \n private func estimateDistance(rssi: Int) -> Int {\n // Rough distance estimation based on RSSI\n // Using path loss formula: RSSI = TxPower - 10 * n * log10(distance)\n // Assuming TxPower = -59 dBm at 1m, n = 2.0 (free space)\n let txPower = -59.0\n let pathLossExponent = 2.0\n \n let ratio = (txPower - Double(rssi)) / (10.0 * pathLossExponent)\n let distance = pow(10.0, ratio)\n \n return Int(distance)\n }\n \n private func broadcastPacket(_ packet: BitchatPacket) {\n // CRITICAL CHECK: Never send unencrypted JSON\n if packet.type == MessageType.deliveryAck.rawValue {\n // Check if payload looks like JSON\n if let jsonCheck = String(data: packet.payload.prefix(1), encoding: .utf8), jsonCheck == \"{\" {\n // Block unencrypted JSON in delivery ACKs\n return\n }\n }\n \n \n guard let data = packet.toBinaryData() else { \n // Failed to convert packet - add to retry queue if it's our message\n let senderID = packet.senderID.hexEncodedString()\n if senderID == self.myPeerID,\n packet.type == MessageType.message.rawValue,\n let message = BitchatMessage.fromBinaryPayload(packet.payload) {\n MessageRetryService.shared.addMessageForRetry(\n content: message.content,\n mentions: message.mentions,\n isPrivate: message.isPrivate,\n recipientPeerID: nil,\n recipientNickname: message.recipientNickname,\n originalMessageID: message.id,\n originalTimestamp: message.timestamp\n )\n }\n return \n }\n \n // Check if fragmentation is needed for large packets\n if data.count > 512 && packet.type != MessageType.fragmentStart.rawValue && \n packet.type != MessageType.fragmentContinue.rawValue && \n packet.type != MessageType.fragmentEnd.rawValue {\n sendFragmentedPacket(packet)\n return\n }\n \n // Track which peers we've sent to (to avoid duplicates)\n var sentToPeers = Set()\n \n // Send to connected peripherals (as central)\n var sentToPeripherals = 0\n \n // Log if this is a private message being broadcast\n if packet.type == MessageType.noiseEncrypted.rawValue,\n let recipientID = packet.recipientID?.hexEncodedString(),\n !recipientID.isEmpty {\n SecureLogger.log(\"WARNING: Broadcasting private message intended for \\(recipientID) to all peers\", \n category: SecureLogger.session, level: .warning)\n }\n \n // Broadcasting to connected peripherals\n for (peerID, peripheral) in connectedPeripherals {\n if let characteristic = peripheralCharacteristics[peripheral] {\n // Check if peripheral is connected before writing\n if peripheral.state == .connected {\n // Additional safety check for characteristic properties\n if characteristic.properties.contains(.write) || \n characteristic.properties.contains(.writeWithoutResponse) {\n // Writing packet to peripheral\n writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: peerID)\n sentToPeripherals += 1\n sentToPeers.insert(peerID)\n }\n } else {\n if let peerID = connectedPeripherals.first(where: { $0.value == peripheral })?.key {\n connectedPeripherals.removeValue(forKey: peerID)\n peripheralCharacteristics.removeValue(forKey: peripheral)\n }\n }\n }\n }\n \n // Send to subscribed centrals (as peripheral) - but only if we didn't already send via peripheral connections\n var sentToCentrals = 0\n if let char = characteristic, !subscribedCentrals.isEmpty && sentToPeripherals == 0 {\n // Only send to centrals if we haven't sent via peripheral connections\n // This prevents duplicate sends in 2-peer networks where peers connect both ways\n // Broadcasting to subscribed centrals\n let success = peripheralManager?.updateValue(data, for: char, onSubscribedCentrals: nil) ?? false\n if success {\n sentToCentrals = subscribedCentrals.count\n }\n } else if sentToPeripherals > 0 && !subscribedCentrals.isEmpty {\n // Skip central broadcast - already sent via peripherals\n }\n \n // If no peers received the message, add to retry queue ONLY if it's our own message\n if sentToPeripherals == 0 && sentToCentrals == 0 {\n // Check if this packet originated from us\n let senderID = packet.senderID.hexEncodedString()\n if senderID == self.myPeerID {\n // This is our own message that failed to send\n if packet.type == MessageType.message.rawValue,\n let message = BitchatMessage.fromBinaryPayload(packet.payload) {\n MessageRetryService.shared.addMessageForRetry(\n content: message.content,\n mentions: message.mentions,\n isPrivate: message.isPrivate,\n recipientPeerID: nil,\n recipientNickname: message.recipientNickname,\n originalMessageID: message.id,\n originalTimestamp: message.timestamp\n )\n }\n }\n }\n }\n \n private func handleReceivedPacket(_ packet: BitchatPacket, from peerID: String, peripheral: CBPeripheral? = nil) {\n messageQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n // Track that we heard from this peer\n let senderID = packet.senderID.hexEncodedString()\n if !senderID.isEmpty && senderID != self.myPeerID {\n // Update peer availability\n self.updatePeerAvailability(senderID)\n \n // IMPORTANT: Update peripheral mapping for ALL message types including handshakes\n // This ensures disconnect messages work even if peer disconnects right after handshake\n if let peripheral = peripheral {\n let peripheralID = peripheral.identifier.uuidString\n \n // Check if we need to update the mapping\n if peerIDByPeripheralID[peripheralID] != senderID {\n SecureLogger.log(\"Updating peripheral mapping: \\(peripheralID) -> \\(senderID)\", \n category: SecureLogger.session, level: .debug)\n peerIDByPeripheralID[peripheralID] = senderID\n \n // Also ensure connectedPeripherals has the correct mapping\n // Remove any temp ID mapping if it exists\n let tempIDToRemove = connectedPeripherals.first(where: { $0.value == peripheral && $0.key != senderID })?.key\n if let tempID = tempIDToRemove {\n connectedPeripherals.removeValue(forKey: tempID)\n }\n connectedPeripherals[senderID] = peripheral\n }\n }\n \n // Check if this is a reconnection after a long silence\n let wasReconnection: Bool\n if let lastHeard = self.lastHeardFromPeer[senderID] {\n let timeSinceLastHeard = Date().timeIntervalSince(lastHeard)\n wasReconnection = timeSinceLastHeard > 30.0\n } else {\n // First time hearing from this peer\n wasReconnection = true\n }\n \n self.lastHeardFromPeer[senderID] = Date()\n \n // If this is a reconnection, send our identity announcement\n if wasReconnection && packet.type != MessageType.noiseIdentityAnnounce.rawValue {\n SecureLogger.log(\"Detected reconnection from \\(senderID) after silence, sending identity announcement\", category: SecureLogger.noise, level: .info)\n DispatchQueue.main.async { [weak self] in\n self?.sendNoiseIdentityAnnounce(to: senderID)\n }\n }\n }\n \n \n // Log specific Noise packet types\n \n guard packet.ttl > 0 else { \n return \n }\n \n // Validate packet has payload\n guard !packet.payload.isEmpty else {\n return\n }\n \n // Update last seen timestamp for this peer\n if senderID != \"unknown\" && senderID != self.myPeerID {\n peerLastSeenTimestamps.set(senderID, value: Date())\n }\n \n // Replay attack protection: Check timestamp is within reasonable window (5 minutes)\n let currentTime = UInt64(Date().timeIntervalSince1970 * 1000) // milliseconds\n let timeDiff = abs(Int64(currentTime) - Int64(packet.timestamp))\n if timeDiff > 300000 { // 5 minutes in milliseconds\n SecureLogger.log(\"Replay attack detected - timestamp from \\(senderID)\", category: SecureLogger.security, level: .warning)\n SecureLogger.log(\"Dropped message with stale timestamp. Age: \\(timeDiff/1000)s from \\(senderID)\", category: SecureLogger.security, level: .warning)\n return\n }\n \n // Log message type for debugging\n let messageTypeName: String\n switch MessageType(rawValue: packet.type) {\n case .message:\n messageTypeName = \"MESSAGE\"\n case .protocolAck:\n messageTypeName = \"PROTOCOL_ACK\"\n case .protocolNack:\n messageTypeName = \"PROTOCOL_NACK\"\n case .noiseHandshakeInit:\n messageTypeName = \"NOISE_HANDSHAKE_INIT\"\n case .noiseHandshakeResp:\n messageTypeName = \"NOISE_HANDSHAKE_RESP\"\n case .noiseIdentityAnnounce:\n messageTypeName = \"NOISE_IDENTITY_ANNOUNCE\"\n case .noiseEncrypted:\n messageTypeName = \"NOISE_ENCRYPTED\"\n case .leave:\n messageTypeName = \"LEAVE\"\n case .readReceipt:\n messageTypeName = \"READ_RECEIPT\"\n case .versionHello:\n messageTypeName = \"VERSION_HELLO\"\n case .versionAck:\n messageTypeName = \"VERSION_ACK\"\n case .systemValidation:\n messageTypeName = \"SYSTEM_VALIDATION\"\n case .handshakeRequest:\n messageTypeName = \"HANDSHAKE_REQUEST\"\n default:\n messageTypeName = \"UNKNOWN(\\(packet.type))\"\n }\n \n // Processing packet\n \n // Rate limiting check with message type awareness\n let isHighPriority = [MessageType.protocolAck.rawValue,\n MessageType.protocolNack.rawValue,\n MessageType.noiseHandshakeInit.rawValue,\n MessageType.noiseHandshakeResp.rawValue,\n MessageType.noiseIdentityAnnounce.rawValue,\n MessageType.leave.rawValue].contains(packet.type)\n \n \n if senderID != self.myPeerID && isRateLimited(peerID: senderID, messageType: packet.type) {\n if !isHighPriority {\n SecureLogger.log(\"RATE_LIMITED: Dropped \\(messageTypeName) from \\(senderID)\", \n category: SecureLogger.security, level: .warning)\n return\n } else {\n SecureLogger.log(\"RATE_LIMITED: Allowing high-priority \\(messageTypeName) from \\(senderID)\", \n category: SecureLogger.security, level: .info)\n }\n }\n \n // Record message for rate limiting based on type\n if senderID != self.myPeerID && !isHighPriority {\n recordMessage(from: senderID, messageType: packet.type)\n }\n \n // Content-based duplicate detection using packet ID\n let messageID = generatePacketID(for: packet)\n \n // Check if we've seen this exact message before\n processedMessagesLock.lock()\n if let existingState = processedMessages[messageID] {\n // Update the state\n var updatedState = existingState\n updatedState.updateSeen()\n processedMessages[messageID] = updatedState\n processedMessagesLock.unlock()\n \n SecureLogger.log(\"Dropped duplicate message from \\(senderID) (seen \\(updatedState.seenCount) times)\", category: SecureLogger.security, level: .debug)\n // Cancel any pending relay for this message\n cancelPendingRelay(messageID: messageID)\n return\n }\n processedMessagesLock.unlock()\n \n // Use bloom filter for efficient duplicate detection\n if messageBloomFilter.contains(messageID) {\n // Double check with exact set (bloom filter can have false positives)\n processedMessagesLock.lock()\n let isProcessed = processedMessages[messageID] != nil\n processedMessagesLock.unlock()\n if !isProcessed {\n SecureLogger.log(\"Bloom filter false positive for message: \\(messageID)\", category: SecureLogger.security, level: .debug)\n }\n }\n \n // Record this message as processed\n messageBloomFilter.insert(messageID)\n processedMessagesLock.lock()\n processedMessages[messageID] = MessageState(\n firstSeen: Date(),\n lastSeen: Date(),\n seenCount: 1,\n relayed: false,\n acknowledged: false\n )\n \n // Prune old entries if needed\n if processedMessages.count > maxProcessedMessages {\n // Remove oldest entries\n let sortedByFirstSeen = processedMessages.sorted { $0.value.firstSeen < $1.value.firstSeen }\n let toRemove = sortedByFirstSeen.prefix(processedMessages.count - maxProcessedMessages + 1000)\n for (key, _) in toRemove {\n processedMessages.removeValue(forKey: key)\n }\n }\n processedMessagesLock.unlock()\n \n \n // Log statistics periodically\n if messageBloomFilter.insertCount % 100 == 0 {\n _ = messageBloomFilter.estimatedFalsePositiveRate\n }\n \n // Bloom filter will be reset by timer, processedMessages is now bounded\n \n // let _ = packet.senderID.hexEncodedString()\n \n \n // Note: We'll decode messages in the switch statement below, not here\n \n switch MessageType(rawValue: packet.type) {\n case .message:\n // Unified message handler for both broadcast and private messages\n // Convert binary senderID back to hex string\n let senderID = packet.senderID.hexEncodedString()\n if senderID.isEmpty {\n return\n }\n \n \n // Ignore our own messages\n if senderID == myPeerID {\n return\n }\n \n // Check if this is a broadcast or private message\n if let recipientID = packet.recipientID {\n if recipientID == SpecialRecipients.broadcast {\n // BROADCAST MESSAGE\n \n // No signature verification - broadcasts are not authenticated\n \n // Parse broadcast message (not encrypted)\n if let message = BitchatMessage.fromBinaryPayload(packet.payload) {\n \n // Store nickname mapping\n collectionsQueue.sync(flags: .barrier) {\n self.peerNicknames[senderID] = message.sender\n }\n \n let finalContent = message.content\n \n let messageWithPeerID = BitchatMessage(\n id: message.id, // Preserve the original message ID\n sender: message.sender,\n content: finalContent,\n timestamp: message.timestamp,\n isRelay: message.isRelay,\n originalSender: message.originalSender,\n isPrivate: false,\n recipientNickname: nil,\n senderPeerID: senderID,\n mentions: message.mentions\n )\n \n // Track last message time from this peer\n let peerID = packet.senderID.hexEncodedString()\n self.lastMessageFromPeer.set(peerID, value: Date())\n \n DispatchQueue.main.async {\n self.delegate?.didReceiveMessage(messageWithPeerID)\n }\n \n }\n \n // Relay broadcast messages\n var relayPacket = packet\n relayPacket.ttl -= 1\n if relayPacket.ttl > 0 {\n // RSSI-based relay probability\n let rssiValue = peerRSSI[senderID]?.intValue ?? -70\n let relayProb = self.calculateRelayProbability(baseProb: self.adaptiveRelayProbability, rssi: rssiValue)\n \n // Relay based on probability only - no TTL boost if base probability is 0\n let effectiveProb = relayProb > 0 ? relayProb : 0.0\n let shouldRelay = effectiveProb > 0 && Double.random(in: 0...1) < effectiveProb\n \n if shouldRelay {\n // Relaying broadcast\n // High priority messages relay immediately, others use exponential delay\n if self.isHighPriorityMessage(type: relayPacket.type) {\n self.broadcastPacket(relayPacket)\n } else {\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n } else {\n // Dropped broadcast relay\n }\n }\n \n } else if isPeerIDOurs(recipientID.hexEncodedString()) {\n // PRIVATE MESSAGE FOR US\n \n \n // No signature verification - broadcasts are not authenticated\n \n // Private messages should only come through Noise now\n // If we're getting a private message here, it must already be decrypted from Noise\n let decryptedPayload = packet.payload\n \n // Parse the message\n if let message = BitchatMessage.fromBinaryPayload(decryptedPayload) {\n \n // Check if this is a dummy message for cover traffic\n if message.content.hasPrefix(self.coverTrafficPrefix) {\n return // Silently discard dummy messages\n }\n \n // Check if we've seen this exact message recently (within 5 seconds)\n let messageKey = \"\\(senderID)-\\(message.content)-\\(message.timestamp)\"\n if let lastReceived = self.receivedMessageTimestamps.get(messageKey) {\n let timeSinceLastReceived = Date().timeIntervalSince(lastReceived)\n if timeSinceLastReceived < 5.0 {\n }\n }\n self.receivedMessageTimestamps.set(messageKey, value: Date())\n \n // LRU cache handles cleanup automatically\n \n collectionsQueue.sync(flags: .barrier) {\n if self.peerNicknames[senderID] == nil {\n self.peerNicknames[senderID] = message.sender\n }\n }\n \n let messageWithPeerID = BitchatMessage(\n id: message.id, // Preserve the original message ID\n sender: message.sender,\n content: message.content,\n timestamp: message.timestamp,\n isRelay: message.isRelay,\n originalSender: message.originalSender,\n isPrivate: message.isPrivate,\n recipientNickname: message.recipientNickname,\n senderPeerID: senderID,\n mentions: message.mentions,\n deliveryStatus: nil // Will be set to .delivered in ChatViewModel\n )\n \n // Track last message time from this peer\n let peerID = packet.senderID.hexEncodedString()\n self.lastMessageFromPeer.set(peerID, value: Date())\n \n DispatchQueue.main.async {\n self.delegate?.didReceiveMessage(messageWithPeerID)\n }\n \n // Generate and send ACK for private messages\n let viewModel = self.delegate as? ChatViewModel\n let myNickname = viewModel?.nickname ?? self.myPeerID\n if let ack = DeliveryTracker.shared.generateAck(\n for: messageWithPeerID,\n myPeerID: self.myPeerID,\n myNickname: myNickname,\n hopCount: UInt8(self.maxTTL - packet.ttl)\n ) {\n self.sendDeliveryAck(ack, to: senderID)\n }\n } else {\n SecureLogger.log(\"Failed to parse private message from binary, size: \\(decryptedPayload.count)\", category: SecureLogger.encryption, level: .error)\n }\n \n } else if packet.ttl > 0 {\n // RELAY PRIVATE MESSAGE (not for us)\n var relayPacket = packet\n relayPacket.ttl -= 1\n \n // Check if this message is for an offline favorite and cache it\n let recipientIDString = recipientID.hexEncodedString()\n if let fingerprint = self.noiseService.getPeerFingerprint(recipientIDString) {\n // Only cache if recipient is a favorite AND is currently offline\n if (self.delegate?.isFavorite(fingerprint: fingerprint) ?? false) && !self.activePeers.contains(recipientIDString) {\n self.cacheMessage(relayPacket, messageID: messageID)\n }\n }\n \n // Private messages are important - use RSSI-based relay with boost\n let rssiValue = peerRSSI[senderID]?.intValue ?? -70\n let baseProb = min(self.adaptiveRelayProbability + 0.15, 1.0) // Boost by 15%\n let relayProb = self.calculateRelayProbability(baseProb: baseProb, rssi: rssiValue)\n \n // Relay based on probability only - no forced relay for small networks\n let shouldRelay = Double.random(in: 0...1) < relayProb\n \n if shouldRelay {\n // High priority messages relay immediately, others use exponential delay\n if self.isHighPriorityMessage(type: relayPacket.type) {\n self.broadcastPacket(relayPacket)\n } else {\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n }\n } else {\n // Message has recipient ID but not for us and TTL is 0\n // Message not for us - will be relayed if TTL > 0\n }\n } else {\n // No recipient ID - this shouldn't happen for messages\n SecureLogger.log(\"Message packet with no recipient ID from \\(senderID)\", category: SecureLogger.security, level: .warning)\n }\n \n // Note: 0x02 was legacy keyExchange - removed\n \n case .announce:\n if let rawNickname = String(data: packet.payload, encoding: .utf8) {\n // Trim whitespace from received nickname\n let nickname = rawNickname.trimmingCharacters(in: .whitespacesAndNewlines)\n let senderID = packet.senderID.hexEncodedString()\n \n SecureLogger.log(\"handleReceivedPacket: Received announce from \\(senderID), peripheral is \\(peripheral != nil ? \"present\" : \"nil\")\", category: SecureLogger.session, level: .debug)\n \n // Ignore if it's from ourselves (including previous peer IDs)\n if isPeerIDOurs(senderID) {\n return\n }\n \n // Check if we've already announced this peer\n let isFirstAnnounce = !announcedPeers.contains(senderID)\n \n // Clean up stale peer IDs with the same nickname\n collectionsQueue.sync(flags: .barrier) {\n var stalePeerIDs: [String] = []\n for (existingPeerID, existingNickname) in self.peerNicknames {\n if existingNickname == nickname && existingPeerID != senderID {\n // Check if this peer was seen very recently (within 10 seconds)\n let wasRecentlySeen = self.peerLastSeenTimestamps.get(existingPeerID).map { Date().timeIntervalSince($0) < 10.0 } ?? false\n if !wasRecentlySeen {\n // Found a stale peer ID with the same nickname\n stalePeerIDs.append(existingPeerID)\n // Found stale peer ID\n } else {\n // Peer was seen recently, keeping both\n }\n }\n }\n \n // Remove stale peer IDs\n for stalePeerID in stalePeerIDs {\n // Removing stale peer\n self.peerNicknames.removeValue(forKey: stalePeerID)\n \n // Also remove from active peers\n self.activePeers.remove(stalePeerID)\n \n // Remove from announced peers\n self.announcedPeers.remove(stalePeerID)\n self.announcedToPeers.remove(stalePeerID)\n \n // Clear tracking data\n self.lastHeardFromPeer.removeValue(forKey: stalePeerID)\n \n // Disconnect any peripherals associated with stale ID\n if let peripheral = self.connectedPeripherals[stalePeerID] {\n self.intentionalDisconnects.insert(peripheral.identifier.uuidString)\n self.centralManager?.cancelPeripheralConnection(peripheral)\n self.connectedPeripherals.removeValue(forKey: stalePeerID)\n self.peripheralCharacteristics.removeValue(forKey: peripheral)\n }\n \n // Remove RSSI data\n self.peerRSSI.removeValue(forKey: stalePeerID)\n \n // Clear cached messages tracking\n self.cachedMessagesSentToPeer.remove(stalePeerID)\n \n // Remove from last seen timestamps\n self.peerLastSeenTimestamps.remove(stalePeerID)\n \n // No longer tracking key exchanges\n }\n \n // If we had stale peers, notify the UI immediately\n if !stalePeerIDs.isEmpty {\n DispatchQueue.main.async { [weak self] in\n self?.notifyPeerListUpdate(immediate: true)\n }\n }\n \n // Now add the new peer ID with the nickname\n self.peerNicknames[senderID] = nickname\n }\n \n // Update peripheral mapping if we have it\n // If peripheral is nil (e.g., from relay), try to find it\n var peripheralToUpdate = peripheral\n if peripheralToUpdate == nil {\n // Look for any peripheral that might be this peer\n // First check if we already have a mapping for this peer ID\n peripheralToUpdate = self.connectedPeripherals[senderID]\n \n if peripheralToUpdate == nil {\n SecureLogger.log(\"handleReceivedPacket: No peripheral passed and no existing mapping for \\(senderID)\", category: SecureLogger.session, level: .debug)\n \n // Try to find an unidentified peripheral that might be this peer\n // This handles case where announce is relayed and we need to update RSSI mapping\n var unmappedPeripherals: [(String, CBPeripheral)] = []\n for (tempID, peripheral) in self.connectedPeripherals {\n // Check if this is a temp ID (UUID format, not a peer ID)\n if tempID.count == 36 && tempID.contains(\"-\") { // UUID length with dashes\n unmappedPeripherals.append((tempID, peripheral))\n SecureLogger.log(\"handleReceivedPacket: Found unmapped peripheral with temp ID \\(tempID)\", category: SecureLogger.session, level: .debug)\n }\n }\n \n // If we have exactly one unmapped peripheral, it's likely this one\n if unmappedPeripherals.count == 1 {\n let (tempID, peripheral) = unmappedPeripherals[0]\n SecureLogger.log(\"handleReceivedPacket: Single unmapped peripheral \\(tempID), mapping to \\(senderID)\", category: SecureLogger.session, level: .info)\n peripheralToUpdate = peripheral\n \n // Remove temp mapping and add real mapping\n self.connectedPeripherals.removeValue(forKey: tempID)\n self.connectedPeripherals[senderID] = peripheral\n \n // Transfer RSSI if available\n if let rssi = self.peripheralRSSI[tempID] {\n self.peripheralRSSI.removeValue(forKey: tempID)\n self.peripheralRSSI[senderID] = rssi\n self.peerRSSI[senderID] = rssi\n }\n \n // Also check the peripheral's UUID-based RSSI\n let peripheralUUID = peripheral.identifier.uuidString\n if peripheralUUID == tempID && peripheralRSSI[peripheralUUID] != nil {\n // Already handled above\n } else if let rssi = self.peripheralRSSI[peripheralUUID] {\n self.peerRSSI[senderID] = rssi\n }\n } else if unmappedPeripherals.count > 1 {\n SecureLogger.log(\"handleReceivedPacket: Multiple unmapped peripherals (\\(unmappedPeripherals.count)), cannot determine which is \\(senderID)\", category: SecureLogger.session, level: .debug)\n // TODO: Could use timing heuristics or other methods to match\n }\n }\n }\n \n if let peripheral = peripheralToUpdate {\n let peripheralID = peripheral.identifier.uuidString\n SecureLogger.log(\"Updating peripheral \\(peripheralID) mapping to peer ID \\(senderID)\", \n category: SecureLogger.session, level: .info)\n \n // Update simplified mapping\n updatePeripheralMapping(peripheralID: peripheralID, peerID: senderID)\n \n // Find and remove any temp ID mapping for this peripheral\n var tempIDToRemove: String? = nil\n for (id, per) in self.connectedPeripherals {\n if per == peripheral && id != senderID && id == peripheralID {\n tempIDToRemove = id\n break\n }\n }\n \n if let tempID = tempIDToRemove {\n // RSSI transfer is handled by updatePeripheralMapping\n self.peripheralRSSI.removeValue(forKey: tempID)\n \n // IMPORTANT: Remove old peer ID from activePeers to prevent duplicates\n collectionsQueue.sync(flags: .barrier) {\n if self.activePeers.contains(tempID) {\n _ = self.activePeers.remove(tempID)\n }\n }\n \n // Don't notify about disconnect - this is just cleanup of temporary ID\n } else {\n SecureLogger.log(\"handleReceivedPacket: No temp ID found for peripheral, directly mapping \\(senderID)\", category: SecureLogger.session, level: .debug)\n // No temp ID found, just add the mapping\n self.connectedPeripherals[senderID] = peripheral\n self.peerIDByPeripheralID[peripheral.identifier.uuidString] = senderID\n \n // Check if RSSI is stored under peripheral UUID and transfer it\n let peripheralUUID = peripheral.identifier.uuidString\n if let peripheralStoredRSSI = self.peripheralRSSI[peripheralUUID] {\n self.peerRSSI[senderID] = peripheralStoredRSSI\n }\n }\n }\n \n // Add to active peers if not already there\n if senderID != \"unknown\" && senderID != self.myPeerID {\n // Check for duplicate nicknames and remove old peer IDs\n collectionsQueue.sync(flags: .barrier) {\n // Find any existing peers with the same nickname\n var oldPeerIDsToRemove: [String] = []\n for existingPeerID in self.activePeers {\n if existingPeerID != senderID {\n let existingNickname = self.peerNicknames[existingPeerID] ?? \"\"\n if existingNickname == nickname && !existingNickname.isEmpty && existingNickname != \"unknown\" {\n oldPeerIDsToRemove.append(existingPeerID)\n }\n }\n }\n \n // Remove old peer IDs with same nickname\n for oldPeerID in oldPeerIDsToRemove {\n self.activePeers.remove(oldPeerID)\n self.peerNicknames.removeValue(forKey: oldPeerID)\n self.connectedPeripherals.removeValue(forKey: oldPeerID)\n \n // Don't notify about disconnect - this is just cleanup of duplicate\n }\n }\n \n let wasInserted = collectionsQueue.sync(flags: .barrier) {\n // Final safety check\n if senderID == self.myPeerID {\n SecureLogger.log(\"Blocked self from being added to activePeers\", category: SecureLogger.noise, level: .error)\n return false\n }\n let result = self.activePeers.insert(senderID).inserted\n return result\n }\n if wasInserted {\n SecureLogger.log(\"📡 Peer joined network: \\(senderID) (\\(nickname))\", category: SecureLogger.session, level: .info)\n }\n \n // Show join message only for first announce AND if we actually added the peer\n if isFirstAnnounce && wasInserted {\n announcedPeers.insert(senderID)\n \n // Delay the connect message slightly to allow identity announcement to be processed\n // This helps ensure fingerprint mappings are available for nickname resolution\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {\n self.delegate?.didConnectToPeer(senderID)\n }\n self.notifyPeerListUpdate(immediate: true)\n \n // Send network available notification if appropriate\n let currentNetworkSize = collectionsQueue.sync { self.activePeers.count }\n if currentNetworkSize > 0 {\n // Clear empty time since network is active\n networkBecameEmptyTime = nil\n \n if !hasNotifiedNetworkAvailable {\n // Check if enough time has passed since last notification\n let now = Date()\n var shouldSendNotification = true\n \n if let lastNotification = lastNetworkNotificationTime {\n let timeSinceLastNotification = now.timeIntervalSince(lastNotification)\n if timeSinceLastNotification < networkNotificationCooldown {\n // Too soon to send another notification\n shouldSendNotification = false\n }\n }\n \n if shouldSendNotification {\n hasNotifiedNetworkAvailable = true\n lastNetworkNotificationTime = now\n NotificationService.shared.sendNetworkAvailableNotification(peerCount: currentNetworkSize)\n }\n }\n }\n \n DispatchQueue.main.async {\n // Check if this is a favorite peer and send notification\n // Note: This might not work immediately if key exchange hasn't happened yet\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n guard let self = self else { return }\n \n // Check if this is a favorite using their public key fingerprint\n if let fingerprint = self.noiseService.getPeerFingerprint(senderID) {\n if self.delegate?.isFavorite(fingerprint: fingerprint) ?? false {\n NotificationService.shared.sendFavoriteOnlineNotification(nickname: nickname)\n \n // Send any cached messages for this favorite\n self.sendCachedMessages(to: senderID)\n }\n }\n }\n }\n } else {\n // Just update the peer list\n self.notifyPeerListUpdate()\n }\n }\n \n // Relay announce if TTL > 0\n if packet.ttl > 1 {\n var relayPacket = packet\n relayPacket.ttl -= 1\n \n // Add small delay to prevent collision\n let delay = Double.random(in: 0.1...0.3)\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n }\n \n case .leave:\n let senderID = packet.senderID.hexEncodedString()\n // Legacy peer disconnect (keeping for backwards compatibility)\n if String(data: packet.payload, encoding: .utf8) != nil {\n // Remove from active peers with proper locking\n collectionsQueue.sync(flags: .barrier) {\n let wasRemoved = self.activePeers.remove(senderID) != nil\n let nickname = self.peerNicknames.removeValue(forKey: senderID) ?? \"unknown\"\n \n if wasRemoved {\n // Mark as gracefully left to prevent duplicate disconnect message\n self.gracefullyLeftPeers.insert(senderID)\n self.gracefulLeaveTimestamps[senderID] = Date()\n \n SecureLogger.log(\"📴 Peer left network: \\(senderID) (\\(nickname)) - marked as gracefully left\", category: SecureLogger.session, level: .info)\n }\n }\n \n announcedPeers.remove(senderID)\n \n // Show disconnect message immediately when peer leaves\n DispatchQueue.main.async {\n self.delegate?.didDisconnectFromPeer(senderID)\n }\n self.notifyPeerListUpdate()\n }\n \n case .fragmentStart, .fragmentContinue, .fragmentEnd:\n // let fragmentTypeStr = packet.type == MessageType.fragmentStart.rawValue ? \"START\" : \n // (packet.type == MessageType.fragmentContinue.rawValue ? \"CONTINUE\" : \"END\")\n \n // Validate fragment has minimum required size\n if packet.payload.count < 13 {\n return\n }\n \n handleFragment(packet, from: peerID)\n \n // Relay fragments if TTL > 0\n var relayPacket = packet\n relayPacket.ttl -= 1\n if relayPacket.ttl > 0 {\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n \n \n case .deliveryAck:\n // Handle delivery acknowledgment\n if let recipientIDData = packet.recipientID,\n isPeerIDOurs(recipientIDData.hexEncodedString()) {\n // This ACK is for us\n let senderID = packet.senderID.hexEncodedString()\n // Check if payload is already decrypted (came through Noise)\n if let ack = DeliveryAck.fromBinaryData(packet.payload) {\n // Already decrypted - process directly\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n } else if let ack = DeliveryAck.decode(from: packet.payload) {\n // Fallback to JSON for backward compatibility\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n } else {\n // Try legacy decryption\n do {\n let decryptedData = try noiseService.decrypt(packet.payload, from: senderID)\n if let ack = DeliveryAck.fromBinaryData(decryptedData) {\n // Process the ACK\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n } else if let ack = DeliveryAck.decode(from: decryptedData) {\n // Fallback to JSON\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n }\n } catch {\n SecureLogger.log(\"Failed to decrypt delivery ACK from \\(senderID): \\(error)\", \n category: SecureLogger.encryption, level: .error)\n }\n }\n } else if packet.ttl > 0 {\n // Relay the ACK if not for us\n \n // SAFETY CHECK: Never relay unencrypted JSON\n if let jsonCheck = String(data: packet.payload.prefix(1), encoding: .utf8), jsonCheck == \"{\" {\n return\n }\n \n var relayPacket = packet\n relayPacket.ttl -= 1\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n \n case .readReceipt:\n // Handle read receipt\n if let recipientIDData = packet.recipientID,\n isPeerIDOurs(recipientIDData.hexEncodedString()) {\n // This read receipt is for us\n let senderID = packet.senderID.hexEncodedString()\n // Received read receipt\n // Check if payload is already decrypted (came through Noise)\n if let receipt = ReadReceipt.fromBinaryData(packet.payload) {\n // Already decrypted - process directly\n // Processing read receipt\n DispatchQueue.main.async {\n self.delegate?.didReceiveReadReceipt(receipt)\n }\n } else if let receipt = ReadReceipt.decode(from: packet.payload) {\n // Fallback to JSON for backward compatibility\n // Processing read receipt (JSON)\n DispatchQueue.main.async {\n self.delegate?.didReceiveReadReceipt(receipt)\n }\n } else {\n // Try legacy decryption\n do {\n let decryptedData = try noiseService.decrypt(packet.payload, from: senderID)\n if let receipt = ReadReceipt.fromBinaryData(decryptedData) {\n // Process the read receipt\n DispatchQueue.main.async {\n self.delegate?.didReceiveReadReceipt(receipt)\n }\n } else if let receipt = ReadReceipt.decode(from: decryptedData) {\n // Fallback to JSON\n DispatchQueue.main.async {\n self.delegate?.didReceiveReadReceipt(receipt)\n }\n }\n } catch {\n // Failed to decrypt read receipt - might be from unknown sender\n }\n }\n } else if packet.ttl > 0 {\n // Relay the read receipt if not for us\n var relayPacket = packet\n relayPacket.ttl -= 1\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n \n case .noiseIdentityAnnounce:\n // Handle Noise identity announcement\n let senderID = packet.senderID.hexEncodedString()\n \n // Check if this identity announce is targeted to someone else\n if let recipientID = packet.recipientID,\n !isPeerIDOurs(recipientID.hexEncodedString()) {\n // Not for us, relay if TTL > 0\n if packet.ttl > 0 {\n // Relay identity announce\n var relayPacket = packet\n relayPacket.ttl -= 1\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n return\n }\n \n // Special duplicate detection for identity announces\n processedMessagesLock.lock()\n if let lastSeenTime = recentIdentityAnnounces[senderID] {\n let timeSince = Date().timeIntervalSince(lastSeenTime)\n if timeSince < identityAnnounceDuplicateWindow {\n processedMessagesLock.unlock()\n SecureLogger.log(\"Dropped duplicate identity announce from \\(senderID) (last seen \\(timeSince)s ago)\", \n category: SecureLogger.security, level: .debug)\n return\n }\n }\n recentIdentityAnnounces[senderID] = Date()\n processedMessagesLock.unlock()\n \n if senderID != myPeerID && !isPeerIDOurs(senderID) {\n // Create defensive copy and validate\n let payloadCopy = Data(packet.payload)\n \n guard !payloadCopy.isEmpty else {\n SecureLogger.log(\"Received empty NoiseIdentityAnnouncement from \\(senderID)\", category: SecureLogger.noise, level: .error)\n return\n }\n \n // Decode the announcement\n let announcement: NoiseIdentityAnnouncement?\n if let firstByte = payloadCopy.first, firstByte == 0x7B { // '{' character - JSON\n announcement = NoiseIdentityAnnouncement.decode(from: payloadCopy) ?? NoiseIdentityAnnouncement.fromBinaryData(payloadCopy)\n } else {\n announcement = NoiseIdentityAnnouncement.fromBinaryData(payloadCopy) ?? NoiseIdentityAnnouncement.decode(from: payloadCopy)\n }\n \n guard let announcement = announcement else {\n SecureLogger.log(\"Failed to decode NoiseIdentityAnnouncement from \\(senderID), size: \\(payloadCopy.count)\", category: SecureLogger.noise, level: .error)\n return\n }\n \n // Verify the signature using the signing public key\n let timestampData = String(Int64(announcement.timestamp.timeIntervalSince1970 * 1000)).data(using: .utf8)!\n let bindingData = announcement.peerID.data(using: .utf8)! + announcement.publicKey + timestampData\n if !noiseService.verifySignature(announcement.signature, for: bindingData, publicKey: announcement.signingPublicKey) {\n SecureLogger.log(\"Signature verification failed for \\(senderID)\", category: SecureLogger.noise, level: .warning)\n return // Reject announcements with invalid signatures\n }\n \n // Calculate fingerprint from public key\n let hash = SHA256.hash(data: announcement.publicKey)\n let fingerprint = hash.map { String(format: \"%02x\", $0) }.joined()\n \n // Log receipt of identity announce\n SecureLogger.log(\"Received identity announce from \\(announcement.peerID) (\\(announcement.nickname))\", \n category: SecureLogger.noise, level: .info)\n \n // Create the binding\n let binding = PeerIdentityBinding(\n currentPeerID: announcement.peerID,\n fingerprint: fingerprint,\n publicKey: announcement.publicKey,\n signingPublicKey: announcement.signingPublicKey,\n nickname: announcement.nickname,\n bindingTimestamp: announcement.timestamp,\n signature: announcement.signature\n )\n \n SecureLogger.log(\"Creating identity binding for \\(announcement.peerID) -> \\(fingerprint)\", category: SecureLogger.security, level: .info)\n \n // Handle peer ID rotation if previousPeerID is provided\n if let previousID = announcement.previousPeerID, previousID != announcement.peerID {\n SecureLogger.log(\"Peer announced rotation from \\(previousID) to \\(announcement.peerID)\", \n category: SecureLogger.security, level: .info)\n \n // Transfer states from previous ID\n collectionsQueue.sync(flags: .barrier) {\n // Transfer gracefullyLeft state\n if self.gracefullyLeftPeers.contains(previousID) {\n self.gracefullyLeftPeers.remove(previousID)\n self.gracefullyLeftPeers.insert(announcement.peerID)\n }\n \n // Clean up the old peer ID from active peers\n if self.activePeers.contains(previousID) {\n self.activePeers.remove(previousID)\n // Don't add new ID yet - let normal flow handle it\n }\n }\n }\n \n // Update our mappings\n updatePeerBinding(announcement.peerID, fingerprint: fingerprint, binding: binding)\n \n // Update connection state only if we're not already authenticated\n let currentState = peerConnectionStates[announcement.peerID] ?? .disconnected\n if currentState != .authenticated {\n updatePeerConnectionState(announcement.peerID, state: .connected)\n }\n \n // Register the peer's public key with ChatViewModel for verification tracking\n DispatchQueue.main.async { [weak self] in\n (self?.delegate as? ChatViewModel)?.registerPeerPublicKey(peerID: announcement.peerID, publicKeyData: announcement.publicKey)\n }\n \n // Lazy handshake: No longer initiate handshake on identity announcement\n // Just respond with our own identity announcement\n if !noiseService.hasEstablishedSession(with: announcement.peerID) {\n // Send our identity back so they know we're here\n SecureLogger.log(\"Responding to identity announce from \\(announcement.peerID) with our own (lazy handshake mode)\", \n category: SecureLogger.noise, level: .info)\n sendNoiseIdentityAnnounce(to: announcement.peerID)\n } else {\n // We already have a session, ensure ChatViewModel knows about the fingerprint\n // This handles the case where handshake completed before identity announcement\n DispatchQueue.main.async { [weak self] in\n if let publicKeyData = self?.noiseService.getPeerPublicKeyData(announcement.peerID) {\n (self?.delegate as? ChatViewModel)?.registerPeerPublicKey(peerID: announcement.peerID, publicKeyData: publicKeyData)\n }\n }\n }\n }\n \n case .noiseHandshakeInit:\n // Handle incoming Noise handshake initiation\n let senderID = packet.senderID.hexEncodedString()\n SecureLogger.logHandshake(\"initiation received\", peerID: senderID, success: true)\n \n // Check if this handshake is for us or broadcast\n if let recipientID = packet.recipientID,\n !isPeerIDOurs(recipientID.hexEncodedString()) {\n // Not for us, relay if TTL > 0\n if packet.ttl > 0 {\n // Relay handshake init\n var relayPacket = packet\n relayPacket.ttl -= 1\n broadcastPacket(relayPacket)\n }\n return\n }\n if !isPeerIDOurs(senderID) {\n // Check if we already have an established session\n if noiseService.hasEstablishedSession(with: senderID) {\n // Determine who should be initiator based on peer ID comparison\n let shouldBeInitiator = myPeerID < senderID\n \n if shouldBeInitiator {\n // We should be initiator but peer is initiating - likely they had a session failure\n SecureLogger.log(\"Received handshake init from \\(senderID) who should be responder - likely session mismatch, clearing and accepting\", category: SecureLogger.noise, level: .warning)\n cleanupPeerCryptoState(senderID)\n } else {\n // Check if we've heard from this peer recently\n let lastHeard = lastHeardFromPeer[senderID] ?? Date.distantPast\n let timeSinceLastHeard = Date().timeIntervalSince(lastHeard)\n \n // Check session validity before clearing\n let lastSuccess = lastSuccessfulMessageTime[senderID] ?? Date.distantPast\n let sessionAge = Date().timeIntervalSince(lastSuccess)\n \n // If the peer is initiating a handshake despite us having a valid session,\n // they must have cleared their session for a good reason (e.g., decryption failure).\n // We should always accept the handshake to re-establish encryption.\n SecureLogger.log(\"Received handshake init from \\(senderID) with existing session (age: \\(Int(sessionAge))s, last heard: \\(Int(timeSinceLastHeard))s ago) - accepting to re-establish encryption\", \n category: SecureLogger.handshake, level: .info)\n cleanupPeerCryptoState(senderID)\n }\n }\n \n // If we have a handshaking session, reset it to allow new handshake\n if noiseService.hasSession(with: senderID) && !noiseService.hasEstablishedSession(with: senderID) {\n SecureLogger.log(\"Received handshake init from \\(senderID) while already handshaking - resetting to allow new handshake\", category: SecureLogger.noise, level: .info)\n cleanupPeerCryptoState(senderID)\n }\n \n // Check if we've completed version negotiation with this peer\n if negotiatedVersions[senderID] == nil {\n // Legacy peer - assume version 1 for backward compatibility\n SecureLogger.log(\"Received Noise handshake from \\(senderID) without version negotiation, assuming v1\", \n category: SecureLogger.session, level: .debug)\n negotiatedVersions[senderID] = 1\n versionNegotiationState[senderID] = .ackReceived(version: 1)\n }\n handleNoiseHandshakeMessage(from: senderID, message: packet.payload, isInitiation: true)\n \n // Send protocol ACK for successfully processed handshake initiation\n sendProtocolAck(for: packet, to: senderID)\n }\n \n case .noiseHandshakeResp:\n // Handle Noise handshake response\n let senderID = packet.senderID.hexEncodedString()\n SecureLogger.logHandshake(\"response received\", peerID: senderID, success: true)\n \n // Check if this handshake response is for us\n if let recipientID = packet.recipientID {\n let recipientIDStr = recipientID.hexEncodedString()\n SecureLogger.log(\"Response targeted to: \\(recipientIDStr), is us: \\(isPeerIDOurs(recipientIDStr))\", category: SecureLogger.noise, level: .debug)\n if !isPeerIDOurs(recipientIDStr) {\n // Not for us, relay if TTL > 0\n if packet.ttl > 0 {\n // Relay handshake response\n var relayPacket = packet\n relayPacket.ttl -= 1\n broadcastPacket(relayPacket)\n }\n return\n }\n }\n \n if !isPeerIDOurs(senderID) {\n // Check our current handshake state\n let currentState = handshakeCoordinator.getHandshakeState(for: senderID)\n SecureLogger.log(\"Processing handshake response from \\(senderID), current state: \\(currentState)\", category: SecureLogger.noise, level: .info)\n \n // Process the response - this could be message 2 or message 3 in the XX pattern\n handleNoiseHandshakeMessage(from: senderID, message: packet.payload, isInitiation: false)\n \n // Send protocol ACK for successfully processed handshake response\n sendProtocolAck(for: packet, to: senderID)\n }\n \n case .noiseEncrypted:\n // Handle Noise encrypted message\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n let recipientID = packet.recipientID?.hexEncodedString() ?? \"\"\n \n // Check if this message is for us\n if isPeerIDOurs(recipientID) {\n // Message is for us, try to decrypt\n handleNoiseEncryptedMessage(from: senderID, encryptedData: packet.payload, originalPacket: packet, peripheral: peripheral)\n } else if packet.ttl > 1 {\n // Message is not for us but has TTL > 1, consider relaying\n // Only relay if we think we might be able to reach the recipient\n \n // Check if recipient is directly connected to us\n let canReachDirectly = connectedPeripherals[recipientID] != nil\n \n // Check if we've seen this recipient recently (might be reachable via relay)\n let seenRecently = collectionsQueue.sync {\n if let lastSeen = self.peerLastSeenTimestamps.get(recipientID) {\n return Date().timeIntervalSince(lastSeen) < 180.0 // Seen in last 3 minutes\n }\n return false\n }\n \n if canReachDirectly || seenRecently {\n // Relay the message with reduced TTL\n var relayPacket = packet\n relayPacket.ttl = min(packet.ttl - 1, 2) // Decrement TTL, max 2 for relayed private messages\n \n SecureLogger.log(\"Relaying private message from \\(senderID) to \\(recipientID) (TTL: \\(relayPacket.ttl))\", \n category: SecureLogger.session, level: .debug)\n \n if canReachDirectly {\n // Send directly to recipient\n _ = sendDirectToRecipient(relayPacket, recipientPeerID: recipientID)\n } else {\n // Use selective relay\n sendViaSelectiveRelay(relayPacket, recipientPeerID: recipientID)\n }\n } else {\n SecureLogger.log(\"Not relaying private message to \\(recipientID) - recipient not reachable\", \n category: SecureLogger.session, level: .debug)\n }\n } else {\n // recipientID is empty or invalid, try to decrypt anyway (backwards compatibility)\n handleNoiseEncryptedMessage(from: senderID, encryptedData: packet.payload, originalPacket: packet, peripheral: peripheral)\n }\n }\n \n case .versionHello:\n // Handle version negotiation hello\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n handleVersionHello(from: senderID, data: packet.payload, peripheral: peripheral)\n }\n \n case .versionAck:\n // Handle version negotiation acknowledgment\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n handleVersionAck(from: senderID, data: packet.payload)\n }\n \n case .protocolAck:\n // Handle protocol-level acknowledgment\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n handleProtocolAck(from: senderID, data: packet.payload)\n }\n \n case .protocolNack:\n // Handle protocol-level negative acknowledgment\n let senderID = packet.senderID.hexEncodedString()\n if let recipientIDData = packet.recipientID,\n isPeerIDOurs(recipientIDData.hexEncodedString())\n && !isPeerIDOurs(senderID) {\n handleProtocolNack(from: senderID, data: packet.payload)\n }\n \n case .systemValidation:\n // Handle system validation ping (for session sync verification)\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n // Try to decrypt the validation ping\n do {\n let decrypted = try noiseService.decrypt(packet.payload, from: senderID)\n SecureLogger.log(\"Successfully validated session with \\(senderID) - ping: \\(String(data: decrypted, encoding: .utf8) ?? \"?\")\", \n category: SecureLogger.session, level: .debug)\n \n // Session is valid, update last successful message time\n lastSuccessfulMessageTime[senderID] = Date()\n } catch {\n // Validation failed - session is out of sync\n SecureLogger.log(\"Session validation failed with \\(senderID): \\(error)\", \n category: SecureLogger.session, level: .warning)\n \n // Send NACK to trigger session re-establishment\n sendProtocolNack(for: packet, to: senderID, \n reason: \"Session validation failed\", \n errorCode: .decryptionFailed)\n }\n }\n \n case .handshakeRequest:\n // Handle handshake request for pending messages\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n handleHandshakeRequest(from: senderID, data: packet.payload)\n }\n \n default:\n break\n }\n }\n }\n \n private func sendFragmentedPacket(_ packet: BitchatPacket) {\n guard let fullData = packet.toBinaryData() else { return }\n \n // Generate a fixed 8-byte fragment ID\n var fragmentID = Data(count: 8)\n fragmentID.withUnsafeMutableBytes { bytes in\n arc4random_buf(bytes.baseAddress, 8)\n }\n \n let fragments = stride(from: 0, to: fullData.count, by: maxFragmentSize).map { offset in\n fullData[offset..> 8) & 0xFF))\n fragmentPayload.append(UInt8(index & 0xFF))\n fragmentPayload.append(UInt8((fragments.count >> 8) & 0xFF))\n fragmentPayload.append(UInt8(fragments.count & 0xFF))\n fragmentPayload.append(packet.type)\n fragmentPayload.append(fragmentData)\n \n let fragmentType: MessageType\n if index == 0 {\n fragmentType = .fragmentStart\n } else if index == fragments.count - 1 {\n fragmentType = .fragmentEnd\n } else {\n fragmentType = .fragmentContinue\n }\n \n let fragmentPacket = BitchatPacket(\n type: fragmentType.rawValue,\n senderID: packet.senderID, // Use original packet's senderID (already Data)\n recipientID: packet.recipientID, // Preserve recipient if any\n timestamp: packet.timestamp, // Use original timestamp\n payload: fragmentPayload,\n signature: nil, // Fragments don't need signatures\n ttl: packet.ttl )\n \n // Send fragments with linear delay\n let totalDelay = Double(index) * delayBetweenFragments\n \n // Send fragments on background queue with calculated delay\n messageQueue.asyncAfter(deadline: .now() + totalDelay) { [weak self] in\n self?.broadcastPacket(fragmentPacket)\n }\n }\n \n let _ = Double(fragments.count - 1) * delayBetweenFragments\n }\n \n private func handleFragment(_ packet: BitchatPacket, from peerID: String) {\n // Handling fragment\n \n guard packet.payload.count >= 13 else { \n return \n }\n \n // Convert to array for safer access\n let payloadArray = Array(packet.payload)\n var offset = 0\n \n // Extract fragment ID as binary data (8 bytes)\n guard payloadArray.count >= 8 else {\n return\n }\n \n let fragmentIDData = Data(payloadArray[0..<8])\n let fragmentID = fragmentIDData.hexEncodedString()\n offset = 8\n \n // Safely extract index\n guard payloadArray.count >= offset + 2 else { \n // Not enough data for index\n return \n }\n let index = Int(payloadArray[offset]) << 8 | Int(payloadArray[offset + 1])\n offset += 2\n \n // Safely extract total\n guard payloadArray.count >= offset + 2 else { \n // Not enough data for total\n return \n }\n let total = Int(payloadArray[offset]) << 8 | Int(payloadArray[offset + 1])\n offset += 2\n \n // Safely extract original type\n guard payloadArray.count >= offset + 1 else { \n // Not enough data for type\n return \n }\n let originalType = payloadArray[offset]\n offset += 1\n \n // Extract fragment data\n let fragmentData: Data\n if payloadArray.count > offset {\n fragmentData = Data(payloadArray[offset...])\n } else {\n fragmentData = Data()\n }\n \n \n // Initialize fragment collection if needed\n if incomingFragments[fragmentID] == nil {\n // Check if we've reached the concurrent session limit\n if incomingFragments.count >= maxConcurrentFragmentSessions {\n // Clean up oldest fragments first\n cleanupOldFragments()\n \n // If still at limit, reject new session to prevent DoS\n if incomingFragments.count >= maxConcurrentFragmentSessions {\n return\n }\n }\n \n incomingFragments[fragmentID] = [:]\n fragmentMetadata[fragmentID] = (originalType, total, Date())\n }\n \n incomingFragments[fragmentID]?[index] = fragmentData\n \n \n // Check if we have all fragments\n if let fragments = incomingFragments[fragmentID],\n fragments.count == total {\n \n // Reassemble the original packet\n var reassembledData = Data()\n for i in 0.. maxFragmentBytes {\n // Remove oldest fragments until under limit\n let sortedFragments = fragmentMetadata.sorted { $0.value.timestamp < $1.value.timestamp }\n for (fragID, _) in sortedFragments {\n incomingFragments.removeValue(forKey: fragID)\n fragmentMetadata.removeValue(forKey: fragID)\n \n // Recalculate total\n totalFragmentBytes = 0\n for (_, fragments) in incomingFragments {\n for (_, data) in fragments {\n totalFragmentBytes += data.count\n }\n }\n \n if totalFragmentBytes <= maxFragmentBytes {\n break\n }\n }\n }\n }\n} // End of BluetoothMeshService class\n\nextension BluetoothMeshService: CBCentralManagerDelegate {\n // MARK: - CBCentralManagerDelegate\n \n func centralManagerDidUpdateState(_ central: CBCentralManager) {\n // Central manager state updated\n switch central.state {\n case .unknown: break\n case .resetting: break\n case .unsupported: break\n case .unauthorized: break\n case .poweredOff: break\n case .poweredOn: break\n @unknown default: break\n }\n \n if central.state == .unsupported {\n } else if central.state == .unauthorized {\n } else if central.state == .poweredOff {\n } else if central.state == .poweredOn {\n startScanning()\n \n // Send announces when central manager is ready\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n self?.sendBroadcastAnnounce()\n }\n }\n }\n \n func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {\n // Optimize for 300m range - only connect to strong enough signals\n let rssiValue = RSSI.intValue\n \n // Dynamic RSSI threshold based on peer count (smart compromise)\n let rssiThreshold = dynamicRSSIThreshold\n guard rssiValue > rssiThreshold else { \n // Ignoring peripheral due to weak signal (threshold: \\(rssiThreshold) dBm)\n return \n }\n \n // Throttle RSSI updates to save CPU\n let peripheralID = peripheral.identifier.uuidString\n if let lastUpdate = lastRSSIUpdate[peripheralID],\n Date().timeIntervalSince(lastUpdate) < 1.0 {\n return // Skip update if less than 1 second since last update\n }\n lastRSSIUpdate[peripheralID] = Date()\n \n // Store RSSI by peripheral ID for later use\n peripheralRSSI[peripheralID] = RSSI\n \n // Extract peer ID from name (no prefix for stealth)\n // Peer IDs are 8 bytes = 16 hex characters\n if let name = peripheral.name, name.count == 16 {\n // Assume 16-character hex names are peer IDs\n let peerID = name\n SecureLogger.log(\"Discovery: Found peer ID \\(peerID) from peripheral name\", category: SecureLogger.session, level: .debug)\n \n // Don't process our own advertisements (including previous peer IDs)\n if isPeerIDOurs(peerID) {\n SecureLogger.log(\"Discovery: Ignoring our own peer ID \\(peerID)\", category: SecureLogger.session, level: .debug)\n return\n }\n \n // Validate RSSI before storing\n let rssiValue = RSSI.intValue\n if rssiValue != 127 && rssiValue >= -100 && rssiValue <= 0 {\n peerRSSI[peerID] = RSSI\n }\n // Discovered potential peer\n SecureLogger.log(\"Discovered peer with ID: \\(peerID), self ID: \\(myPeerID)\", category: SecureLogger.noise, level: .debug)\n }\n \n // Connection pooling with exponential backoff\n // peripheralID already declared above\n \n // Check if we should attempt connection (considering backoff)\n if let backoffTime = connectionBackoff[peripheralID],\n Date().timeIntervalSince1970 < backoffTime {\n // Still in backoff period, skip connection\n return\n }\n \n // Check if we already have this peripheral in our pool\n if let pooledPeripheral = connectionPool[peripheralID] {\n // Reuse existing peripheral from pool\n if pooledPeripheral.state == CBPeripheralState.disconnected {\n // Reconnect if disconnected with optimized parameters\n let connectionOptions: [String: Any] = [\n CBConnectPeripheralOptionNotifyOnConnectionKey: true,\n CBConnectPeripheralOptionNotifyOnDisconnectionKey: true,\n CBConnectPeripheralOptionNotifyOnNotificationKey: true\n ]\n \n // Smart compromise: would set low latency for small networks if API supported it\n // iOS/macOS don't expose connection interval control in public API\n \n central.connect(pooledPeripheral, options: connectionOptions)\n }\n return\n }\n \n // New peripheral - add to pool and connect\n if !discoveredPeripherals.contains(peripheral) {\n // Check connection pool limits\n let connectedCount = connectionPool.values.filter { $0.state == .connected }.count\n if connectedCount >= maxConnectedPeripherals {\n // Connection pool is full - find least recently used peripheral to disconnect\n if let lruPeripheralID = findLeastRecentlyUsedPeripheral() {\n if let lruPeripheral = connectionPool[lruPeripheralID] {\n SecureLogger.log(\"Connection pool full, disconnecting LRU peripheral: \\(lruPeripheralID)\", \n category: SecureLogger.session, level: .debug)\n central.cancelPeripheralConnection(lruPeripheral)\n connectionPool.removeValue(forKey: lruPeripheralID)\n }\n }\n }\n \n discoveredPeripherals.append(peripheral)\n peripheral.delegate = self\n connectionPool[peripheralID] = peripheral\n \n // Track connection attempts\n let attempts = connectionAttempts[peripheralID] ?? 0\n connectionAttempts[peripheralID] = attempts + 1\n \n // Only attempt if under max attempts\n if attempts < maxConnectionAttempts {\n // Use optimized connection parameters based on peer count\n let connectionOptions: [String: Any] = [\n CBConnectPeripheralOptionNotifyOnConnectionKey: true,\n CBConnectPeripheralOptionNotifyOnDisconnectionKey: true,\n CBConnectPeripheralOptionNotifyOnNotificationKey: true\n ]\n \n // Smart compromise: would set low latency for small networks if API supported it\n // iOS/macOS don't expose connection interval control in public API\n \n central.connect(peripheral, options: connectionOptions)\n }\n }\n }\n \n func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {\n let peripheralID = peripheral.identifier.uuidString\n \n peripheral.delegate = self\n peripheral.discoverServices([BluetoothMeshService.serviceUUID])\n \n // Register peripheral in simplified mapping system\n registerPeripheral(peripheral)\n \n // Store peripheral temporarily until we get the real peer ID\n connectedPeripherals[peripheralID] = peripheral\n \n SecureLogger.log(\"Connected to peripheral \\(peripheralID) - awaiting peer ID\", \n category: SecureLogger.session, level: .debug)\n \n // Update connection state to connected (but not authenticated yet)\n // We don't know the real peer ID yet, so we can't update the state\n \n // Don't show connected message yet - wait for key exchange\n // This prevents the connect/disconnect/connect pattern\n \n // Request RSSI reading\n peripheral.readRSSI()\n \n // iOS 11+ BLE 5.0: Request 2M PHY for better range and speed\n if #available(iOS 11.0, macOS 10.14, *) {\n // 2M PHY provides better range than 1M PHY\n // This is a hint - system will use best available\n }\n }\n \n func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {\n let peripheralID = peripheral.identifier.uuidString\n \n // Clean up RSSI retry count\n rssiRetryCount.removeValue(forKey: peripheralID)\n \n // Check if this was an intentional disconnect\n if intentionalDisconnects.contains(peripheralID) {\n intentionalDisconnects.remove(peripheralID)\n SecureLogger.log(\"Intentional disconnect: \\(peripheralID)\", category: SecureLogger.session, level: .debug)\n // Don't process this disconnect further\n return\n }\n \n // Log disconnect with error if present\n if let error = error {\n SecureLogger.logError(error, context: \"Peripheral disconnected: \\(peripheralID)\", category: SecureLogger.session)\n } else {\n SecureLogger.log(\"Peripheral disconnected normally: \\(peripheralID)\", category: SecureLogger.session, level: .info)\n }\n \n // Find the real peer ID using simplified mapping\n var realPeerID: String? = nil\n \n if let mapping = peripheralMappings[peripheralID], let peerID = mapping.peerID {\n realPeerID = peerID\n SecureLogger.log(\"Found peer ID \\(peerID) for peripheral \\(peripheralID)\", \n category: SecureLogger.session, level: .debug)\n } else if let peerID = peerIDByPeripheralID[peripheralID] {\n // Fallback to legacy mapping\n realPeerID = peerID\n SecureLogger.log(\"Found peer ID \\(peerID) from legacy mapping for peripheral \\(peripheralID)\", \n category: SecureLogger.session, level: .debug)\n } else {\n SecureLogger.log(\"No peer ID mapping found for peripheral \\(peripheralID)\", \n category: SecureLogger.session, level: .debug)\n \n // Fallback: check if we have a direct mapping from peripheral to peer ID\n for (peerID, connectedPeripheral) in connectedPeripherals {\n if connectedPeripheral.identifier == peripheral.identifier {\n // Check if this is a real peer ID (16 hex chars) not a temp ID\n if peerID.count == 16 && peerID.allSatisfy({ $0.isHexDigit }) {\n realPeerID = peerID\n SecureLogger.log(\"Found peer ID \\(peerID) from connectedPeripherals fallback\", \n category: SecureLogger.session, level: .debug)\n break\n } else {\n SecureLogger.log(\"Skipping non-peer ID '\\(peerID)' (length: \\(peerID.count))\", \n category: SecureLogger.session, level: .debug)\n }\n }\n }\n }\n \n // Update connection state immediately if we have a real peer ID\n if let peerID = realPeerID {\n // Update peer connection state\n updatePeerConnectionState(peerID, state: .disconnected)\n \n // Clear pending messages for disconnected peer to prevent retry loops\n collectionsQueue.async(flags: .barrier) { [weak self] in\n if let pendingCount = self?.pendingPrivateMessages[peerID]?.count, pendingCount > 0 {\n SecureLogger.log(\"Clearing \\(pendingCount) pending messages for disconnected peer \\(peerID)\", \n category: SecureLogger.session, level: .info)\n self?.pendingPrivateMessages[peerID]?.removeAll()\n }\n }\n \n // Reset handshake state to prevent stuck handshakes\n handshakeCoordinator.resetHandshakeState(for: peerID)\n \n // Check if peer gracefully left and notify delegate\n let shouldNotifyDisconnect = collectionsQueue.sync {\n let isGracefullyLeft = self.gracefullyLeftPeers.contains(peerID)\n if isGracefullyLeft {\n SecureLogger.log(\"Physical disconnect for \\(peerID) - was gracefully left, NOT notifying delegate\", category: SecureLogger.session, level: .info)\n } else {\n SecureLogger.log(\"Physical disconnect for \\(peerID) - was NOT gracefully left, will notify delegate\", category: SecureLogger.session, level: .info)\n }\n return !isGracefullyLeft\n }\n \n if shouldNotifyDisconnect {\n DispatchQueue.main.async {\n self.delegate?.didDisconnectFromPeer(peerID)\n }\n }\n }\n \n // Implement exponential backoff for failed connections\n if error != nil {\n let attempts = connectionAttempts[peripheralID] ?? 0\n if attempts >= maxConnectionAttempts {\n // Max attempts reached, apply long backoff\n let backoffDuration = baseBackoffInterval * pow(2.0, Double(attempts))\n connectionBackoff[peripheralID] = Date().timeIntervalSince1970 + backoffDuration\n }\n } else {\n // Clean disconnect, reset attempts\n connectionAttempts[peripheralID] = 0\n connectionBackoff.removeValue(forKey: peripheralID)\n }\n \n // Clean up peripheral tracking\n peripheralMappings.removeValue(forKey: peripheralID)\n peerIDByPeripheralID.removeValue(forKey: peripheralID)\n lastActivityByPeripheralID.removeValue(forKey: peripheralID)\n \n // Find peer ID for this peripheral (could be temp ID or real ID)\n var foundPeerID: String? = nil\n for (id, per) in connectedPeripherals {\n if per == peripheral {\n foundPeerID = id\n break\n }\n }\n \n if let peerID = foundPeerID {\n connectedPeripherals.removeValue(forKey: peerID)\n peripheralCharacteristics.removeValue(forKey: peripheral)\n \n // Don't clear Noise session on disconnect - sessions should survive disconnects\n // The Noise protocol is designed to maintain sessions across network interruptions\n // Only clear sessions on authentication failure\n if peerID.count == 16 { // Real peer ID\n // Clear connection time and last heard tracking on disconnect to properly detect stale sessions\n lastConnectionTime.removeValue(forKey: peerID)\n lastHeardFromPeer.removeValue(forKey: peerID)\n // Keep lastSuccessfulMessageTime to validate session on reconnect\n let lastSuccess = lastSuccessfulMessageTime[peerID] ?? Date.distantPast\n let sessionAge = Date().timeIntervalSince(lastSuccess)\n SecureLogger.log(\"Peer disconnected: \\(peerID), keeping Noise session (age: \\(Int(sessionAge))s)\", category: SecureLogger.noise, level: .info)\n }\n \n // Only remove from active peers if it's not a temp ID\n // Temp IDs shouldn't be in activePeers anyway\n let (removed, _) = collectionsQueue.sync(flags: .barrier) {\n var removed = false\n if peerID.count == 16 { // Real peer ID (8 bytes = 16 hex chars)\n removed = activePeers.remove(peerID) != nil\n if removed {\n // Only log disconnect if peer didn't gracefully leave\n if !self.gracefullyLeftPeers.contains(peerID) {\n let nickname = self.peerNicknames[peerID] ?? \"unknown\"\n SecureLogger.log(\"📴 Peer disconnected from network: \\(peerID) (\\(nickname))\", category: SecureLogger.session, level: .info)\n } else {\n // Peer gracefully left, just clean up the tracking\n self.gracefullyLeftPeers.remove(peerID)\n self.gracefulLeaveTimestamps.removeValue(forKey: peerID)\n SecureLogger.log(\"Cleaning up gracefullyLeftPeers for \\(peerID)\", category: SecureLogger.session, level: .debug)\n }\n }\n \n _ = announcedPeers.remove(peerID)\n _ = announcedToPeers.remove(peerID)\n } else {\n }\n \n // Clear cached messages tracking for this peer to allow re-sending if they reconnect\n cachedMessagesSentToPeer.remove(peerID)\n \n // Clear version negotiation state\n versionNegotiationState.removeValue(forKey: peerID)\n negotiatedVersions.removeValue(forKey: peerID)\n \n // Peer disconnected\n \n return (removed, peerNicknames[peerID])\n }\n \n // Always notify peer list update on disconnect, regardless of whether peer was in activePeers\n // This ensures UI stays in sync even if there was a state mismatch\n self.notifyPeerListUpdate(immediate: true)\n \n if removed {\n // Mark when network became empty, but don't reset flag immediately\n let currentNetworkSize = collectionsQueue.sync { activePeers.count }\n if currentNetworkSize == 0 && networkBecameEmptyTime == nil {\n networkBecameEmptyTime = Date()\n }\n }\n }\n \n // Keep in pool but remove from discovered list\n discoveredPeripherals.removeAll { $0 == peripheral }\n \n // Continue scanning for reconnection\n if centralManager?.state == .poweredOn {\n // Stop and restart to ensure clean state\n centralManager?.stopScan()\n centralManager?.scanForPeripherals(withServices: [BluetoothMeshService.serviceUUID], options: [CBCentralManagerScanOptionAllowDuplicatesKey: false])\n }\n }\n}\n\nextension BluetoothMeshService: CBPeripheralDelegate {\n // MARK: - CBPeripheralDelegate\n \n func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {\n if let error = error {\n SecureLogger.log(\"Error discovering services: \\(error)\", \n category: SecureLogger.encryption, level: .error)\n return\n }\n \n guard let services = peripheral.services else { return }\n \n \n for service in services {\n peripheral.discoverCharacteristics([BluetoothMeshService.characteristicUUID], for: service)\n }\n }\n \n func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {\n if let error = error {\n SecureLogger.log(\"Error discovering characteristics: \\(error)\", \n category: SecureLogger.encryption, level: .error)\n return\n }\n \n guard let characteristics = service.characteristics else { return }\n \n \n for characteristic in characteristics {\n if characteristic.uuid == BluetoothMeshService.characteristicUUID {\n peripheral.setNotifyValue(true, for: characteristic)\n peripheralCharacteristics[peripheral] = characteristic\n \n // Request maximum MTU for faster data transfer\n // iOS supports up to 512 bytes with BLE 5.0\n peripheral.maximumWriteValueLength(for: .withoutResponse)\n \n // Start version negotiation instead of immediately sending Noise identity\n self.sendVersionHello(to: peripheral)\n \n // Send announce packet after version negotiation completes\n if let vm = self.delegate as? ChatViewModel {\n // Send single announce with slight delay\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in\n guard let self = self else { return }\n let announcePacket = BitchatPacket(\n type: MessageType.announce.rawValue,\n ttl: 3,\n senderID: self.myPeerID,\n payload: Data(vm.nickname.utf8) )\n self.broadcastPacket(announcePacket)\n }\n \n // Also send targeted announce to this specific peripheral\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [weak self, weak peripheral] in\n guard let self = self,\n let peripheral = peripheral,\n peripheral.state == .connected,\n let characteristic = peripheral.services?.first(where: { $0.uuid == BluetoothMeshService.serviceUUID })?.characteristics?.first(where: { $0.uuid == BluetoothMeshService.characteristicUUID }) else { return }\n \n let announcePacket = BitchatPacket(\n type: MessageType.announce.rawValue,\n ttl: 3,\n senderID: self.myPeerID,\n payload: Data(vm.nickname.utf8) )\n if let data = announcePacket.toBinaryData() {\n self.writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: nil)\n }\n }\n }\n }\n }\n }\n \n func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {\n guard let data = characteristic.value else {\n return\n }\n \n // Update activity tracking for this peripheral\n updatePeripheralActivity(peripheral.identifier.uuidString)\n \n \n guard let packet = BitchatPacket.from(data) else { \n return \n }\n \n \n // Use the sender ID from the packet, not our local mapping which might still be a temp ID\n let _ = connectedPeripherals.first(where: { $0.value == peripheral })?.key ?? \"unknown\"\n let packetSenderID = packet.senderID.hexEncodedString()\n \n \n // Always handle received packets\n handleReceivedPacket(packet, from: packetSenderID, peripheral: peripheral)\n }\n \n func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {\n if let error = error {\n // Log error but don't spam for common errors\n let errorCode = (error as NSError).code\n if errorCode != 242 { // Don't log the common \"Unknown ATT error\"\n }\n } else {\n }\n }\n \n func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {\n peripheral.discoverServices([BluetoothMeshService.serviceUUID])\n }\n \n func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {\n // Handle notification state updates if needed\n }\n \n func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {\n let peripheralID = peripheral.identifier.uuidString\n \n if error != nil {\n return\n }\n \n // Validate RSSI value - 127 means no RSSI available\n let rssiValue = RSSI.intValue\n \n // Only store valid RSSI values\n if rssiValue == 127 || rssiValue < -100 || rssiValue > 0 {\n // Track retry count\n let retryCount = rssiRetryCount[peripheralID] ?? 0\n rssiRetryCount[peripheralID] = retryCount + 1\n \n \n // Retry up to 5 times with exponential backoff\n if retryCount < 5 {\n let delay = min(0.2 * pow(2.0, Double(retryCount)), 2.0) // 0.2s, 0.4s, 0.8s, 1.6s, 2.0s max\n DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self, weak peripheral] in\n guard let peripheral = peripheral, peripheral.state == .connected else { \n self?.rssiRetryCount.removeValue(forKey: peripheralID)\n return \n }\n peripheral.readRSSI()\n }\n } else {\n // Give up after 5 retries, reset counter\n rssiRetryCount.removeValue(forKey: peripheralID)\n }\n return\n }\n \n // Valid RSSI received, reset retry count\n rssiRetryCount.removeValue(forKey: peripheralID)\n \n // Update RSSI in simplified mapping\n updatePeripheralRSSI(peripheralID: peripheralID, rssi: RSSI)\n \n // Also store in legacy mapping for compatibility\n peripheralRSSI[peripheralID] = RSSI\n \n // If we have a peer ID, update peer RSSI (handled in updatePeripheralRSSI)\n if let mapping = peripheralMappings[peripheralID], mapping.isIdentified {\n // Force UI update when we have a real peer ID\n DispatchQueue.main.async { [weak self] in\n self?.notifyPeerListUpdate()\n }\n } else {\n // Keep trying to read RSSI until we get real peer ID\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak peripheral] in\n guard let peripheral = peripheral, peripheral.state == .connected else { return }\n peripheral.readRSSI()\n }\n }\n \n // Periodically update RSSI\n DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) { [weak peripheral] in\n guard let peripheral = peripheral, peripheral.state == .connected else { return }\n peripheral.readRSSI()\n }\n }\n}\n\nextension BluetoothMeshService: CBPeripheralManagerDelegate {\n // MARK: - CBPeripheralManagerDelegate\n \n func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {\n // Peripheral manager state updated\n switch peripheral.state {\n case .unknown: break\n case .resetting: break\n case .unsupported: break\n case .unauthorized: break\n case .poweredOff: break\n case .poweredOn: break\n @unknown default: break\n }\n \n switch peripheral.state {\n case .unsupported:\n break\n case .unauthorized:\n break\n case .poweredOff:\n break\n case .poweredOn:\n setupPeripheral()\n startAdvertising()\n \n // Send announces when peripheral manager is ready\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n self?.sendBroadcastAnnounce()\n }\n default:\n break\n }\n }\n \n func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) {\n // Service added\n }\n \n func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) {\n // Advertising state changed\n }\n \n func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {\n for request in requests {\n if let data = request.value {\n \n if let packet = BitchatPacket.from(data) {\n \n // Log specific Noise packet types\n switch packet.type {\n case MessageType.noiseHandshakeInit.rawValue:\n break\n case MessageType.noiseHandshakeResp.rawValue:\n break\n case MessageType.noiseEncrypted.rawValue:\n break\n default:\n break\n }\n \n // Try to identify peer from packet\n let peerID = packet.senderID.hexEncodedString()\n \n // Store the central for updates\n if !subscribedCentrals.contains(request.central) {\n subscribedCentrals.append(request.central)\n }\n \n // Track this peer as connected\n if peerID != \"unknown\" && peerID != myPeerID {\n // Double-check we're not adding ourselves\n if peerID == self.myPeerID {\n SecureLogger.log(\"Preventing self from being added as peer (peripheral manager)\", category: SecureLogger.noise, level: .warning)\n peripheral.respond(to: request, withResult: .success)\n return\n }\n \n // Note: Legacy keyExchange (0x02) no longer handled\n \n self.notifyPeerListUpdate()\n }\n \n handleReceivedPacket(packet, from: peerID)\n peripheral.respond(to: request, withResult: .success)\n } else {\n peripheral.respond(to: request, withResult: .invalidPdu)\n }\n } else {\n peripheral.respond(to: request, withResult: .invalidPdu)\n }\n }\n }\n \n func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {\n if !subscribedCentrals.contains(central) {\n subscribedCentrals.append(central)\n \n // Only send identity announcement if we haven't recently\n // This reduces spam when multiple centrals connect quickly\n // sendNoiseIdentityAnnounce() will check rate limits internally\n \n // Update peer list to show we're connected (even without peer ID yet)\n self.notifyPeerListUpdate()\n }\n }\n \n func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) {\n subscribedCentrals.removeAll { $0 == central }\n \n // Don't aggressively remove peers when centrals unsubscribe\n // Peers may be connected through multiple paths\n \n // Ensure advertising continues for reconnection\n if peripheralManager?.state == .poweredOn && peripheralManager?.isAdvertising == false {\n startAdvertising()\n }\n }\n \n // MARK: - Battery Monitoring\n \n private func setupBatteryOptimizer() {\n // Subscribe to power mode changes\n batteryOptimizer.$currentPowerMode\n .sink { [weak self] powerMode in\n self?.handlePowerModeChange(powerMode)\n }\n .store(in: &batteryOptimizerCancellables)\n \n // Subscribe to battery level changes\n batteryOptimizer.$batteryLevel\n .sink { [weak self] level in\n self?.currentBatteryLevel = level\n }\n .store(in: &batteryOptimizerCancellables)\n \n // Initial update\n handlePowerModeChange(batteryOptimizer.currentPowerMode)\n }\n \n private func handlePowerModeChange(_ powerMode: PowerMode) {\n let params = batteryOptimizer.scanParameters\n activeScanDuration = params.duration\n scanPauseDuration = params.pause\n \n // Update max connections\n let maxConnections = powerMode.maxConnections\n \n // If we have too many connections, disconnect from the least important ones\n if connectedPeripherals.count > maxConnections {\n disconnectLeastImportantPeripherals(keepCount: maxConnections)\n }\n \n // Update message aggregation window\n aggregationWindow = powerMode.messageAggregationWindow\n \n // If we're currently scanning, restart with new parameters\n if scanDutyCycleTimer != nil {\n scanDutyCycleTimer?.invalidate()\n scheduleScanDutyCycle()\n }\n \n // Handle advertising intervals\n if powerMode.advertisingInterval > 0 {\n // Stop continuous advertising and use interval-based\n scheduleAdvertisingCycle(interval: powerMode.advertisingInterval)\n } else {\n // Continuous advertising for performance mode\n startAdvertising()\n }\n }\n \n private func disconnectLeastImportantPeripherals(keepCount: Int) {\n // Disconnect peripherals with lowest activity/importance\n let sortedPeripherals = connectedPeripherals.values\n .sorted { peer1, peer2 in\n // Keep peripherals we've recently communicated with\n let peer1Activity = lastMessageFromPeer.get(peer1.identifier.uuidString) ?? Date.distantPast\n let peer2Activity = lastMessageFromPeer.get(peer2.identifier.uuidString) ?? Date.distantPast\n return peer1Activity > peer2Activity\n }\n \n // Disconnect the least active ones\n let toDisconnect = sortedPeripherals.dropFirst(keepCount)\n for peripheral in toDisconnect {\n centralManager?.cancelPeripheralConnection(peripheral)\n }\n }\n \n private func scheduleAdvertisingCycle(interval: TimeInterval) {\n advertisingTimer?.invalidate()\n \n // Stop advertising\n if isAdvertising {\n peripheralManager?.stopAdvertising()\n isAdvertising = false\n }\n \n // Schedule next advertising burst\n advertisingTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in\n self?.advertiseBurst()\n }\n }\n \n private func advertiseBurst() {\n guard batteryOptimizer.currentPowerMode != .ultraLowPower || !batteryOptimizer.isInBackground else {\n return // Skip advertising in ultra low power + background\n }\n \n startAdvertising()\n \n // Stop advertising after a short burst (1 second)\n DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in\n if self?.batteryOptimizer.currentPowerMode.advertisingInterval ?? 0 > 0 {\n self?.peripheralManager?.stopAdvertising()\n self?.isAdvertising = false\n }\n }\n }\n \n // Legacy battery monitoring methods - kept for compatibility\n // Now handled by BatteryOptimizer\n private func updateBatteryLevel() {\n // This method is now handled by BatteryOptimizer\n // Keeping empty implementation for compatibility\n }\n \n private func updateScanParametersForBattery() {\n // This method is now handled by BatteryOptimizer through handlePowerModeChange\n // Keeping empty implementation for compatibility\n }\n \n // MARK: - Privacy Utilities\n \n private func randomDelay() -> TimeInterval {\n // Generate random delay between min and max for timing obfuscation\n return TimeInterval.random(in: minMessageDelay...maxMessageDelay)\n }\n \n // MARK: - Range Optimization Methods\n \n // Calculate relay probability based on RSSI (edge nodes relay more)\n private func calculateRelayProbability(baseProb: Double, rssi: Int) -> Double {\n // RSSI typically ranges from -30 (very close) to -90 (far)\n // We want edge nodes (weak RSSI) to relay more aggressively\n let rssiFactor = Double(100 + rssi) / 100.0 // -90 = 0.1, -70 = 0.3, -50 = 0.5\n \n // Invert the factor so weak signals relay more\n let edgeFactor = max(0.5, 2.0 - rssiFactor)\n \n return min(1.0, baseProb * edgeFactor)\n }\n \n // Exponential delay distribution to prevent synchronized collision storms\n private func exponentialRelayDelay() -> TimeInterval {\n // Use exponential distribution with mean of (min + max) / 2\n let meanDelay = (minMessageDelay + maxMessageDelay) / 2.0\n let lambda = 1.0 / meanDelay\n \n // Generate exponential random value\n let u = Double.random(in: 0..<1)\n let exponentialDelay = -log(1.0 - u) / lambda\n \n // Clamp to our bounds\n return min(maxMessageDelay, max(minMessageDelay, exponentialDelay))\n }\n \n // Check if message type is high priority (should bypass aggregation)\n private func isHighPriorityMessage(type: UInt8) -> Bool {\n switch MessageType(rawValue: type) {\n case .noiseHandshakeInit, .noiseHandshakeResp, .protocolAck,\n .versionHello, .versionAck, .deliveryAck, .systemValidation,\n .handshakeRequest:\n return true\n case .message, .announce, .leave, .readReceipt, .deliveryStatusRequest,\n .fragmentStart, .fragmentContinue, .fragmentEnd,\n .noiseIdentityAnnounce, .noiseEncrypted, .protocolNack, .none:\n return false\n }\n }\n \n // Calculate exponential backoff for retries\n private func calculateExponentialBackoff(retry: Int) -> TimeInterval {\n // Start with 1s, double each time: 1s, 2s, 4s, 8s, 16s, max 30s\n let baseDelay = 1.0\n let maxDelay = 30.0\n let delay = min(maxDelay, baseDelay * pow(2.0, Double(retry - 1)))\n \n // Add 10% jitter to prevent synchronized retries\n let jitter = delay * 0.1 * (Double.random(in: -1...1))\n return delay + jitter\n }\n \n // MARK: - Collision Avoidance\n \n // Calculate jitter based on node ID to spread transmissions\n private func calculateNodeIDJitter() -> TimeInterval {\n // Use hash of peer ID to generate consistent jitter for this node\n let hashValue = myPeerID.hash\n let normalizedHash = Double(abs(hashValue % 1000)) / 1000.0 // 0.0 to 0.999\n \n // Jitter range: 0-20ms based on node ID\n let jitterRange: TimeInterval = 0.02 // 20ms max jitter\n return normalizedHash * jitterRange\n }\n \n // Add smart delay to avoid collisions\n private func smartCollisionAvoidanceDelay(baseDelay: TimeInterval) -> TimeInterval {\n // Add node-specific jitter to base delay\n let nodeJitter = calculateNodeIDJitter()\n \n // Add small random component to avoid perfect synchronization\n let randomJitter = TimeInterval.random(in: 0...0.005) // 0-5ms additional random\n \n return baseDelay + nodeJitter + randomJitter\n }\n \n // MARK: - Relay Cancellation\n \n private func scheduleRelay(_ packet: BitchatPacket, messageID: String, delay: TimeInterval) {\n pendingRelaysLock.lock()\n defer { pendingRelaysLock.unlock() }\n \n // Cancel any existing relay for this message\n if let existingRelay = pendingRelays[messageID] {\n existingRelay.cancel()\n }\n \n // Apply smart collision avoidance to delay\n let adjustedDelay = smartCollisionAvoidanceDelay(baseDelay: delay)\n \n // Create new relay task\n let relayTask = DispatchWorkItem { [weak self] in\n guard let self = self else { return }\n \n // Remove from pending when executed\n self.pendingRelaysLock.lock()\n self.pendingRelays.removeValue(forKey: messageID)\n self.pendingRelaysLock.unlock()\n \n // Mark this message as relayed\n self.processedMessagesLock.lock()\n if var state = self.processedMessages[messageID] {\n state.relayed = true\n self.processedMessages[messageID] = state\n }\n self.processedMessagesLock.unlock()\n \n // Actually relay the packet\n self.broadcastPacket(packet)\n }\n \n // Store the task\n pendingRelays[messageID] = relayTask\n \n // Schedule it with adjusted delay\n DispatchQueue.global(qos: .default).asyncAfter(deadline: .now() + adjustedDelay, execute: relayTask)\n }\n \n private func cancelPendingRelay(messageID: String) {\n pendingRelaysLock.lock()\n defer { pendingRelaysLock.unlock() }\n \n if let pendingRelay = pendingRelays[messageID] {\n pendingRelay.cancel()\n pendingRelays.removeValue(forKey: messageID)\n // Cancelled pending relay - another node handled it\n }\n }\n \n // MARK: - Memory Management\n \n private func startMemoryCleanupTimer() {\n memoryCleanupTimer?.invalidate()\n memoryCleanupTimer = Timer.scheduledTimer(withTimeInterval: 60.0, repeats: true) { [weak self] _ in\n self?.performMemoryCleanup()\n }\n }\n \n private func performMemoryCleanup() {\n messageQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n let startTime = Date()\n \n // Clean up old fragments\n let fragmentTimeout = Date().addingTimeInterval(-self.fragmentTimeout)\n var expiredFragments = [String]()\n for (fragmentID, metadata) in self.fragmentMetadata {\n if metadata.timestamp < fragmentTimeout {\n expiredFragments.append(fragmentID)\n }\n }\n for fragmentID in expiredFragments {\n self.incomingFragments.removeValue(forKey: fragmentID)\n self.fragmentMetadata.removeValue(forKey: fragmentID)\n }\n \n // Limit pending private messages\n if self.pendingPrivateMessages.count > self.maxPendingPrivateMessages {\n let excess = self.pendingPrivateMessages.count - self.maxPendingPrivateMessages\n let keysToRemove = Array(self.pendingPrivateMessages.keys.prefix(excess))\n for key in keysToRemove {\n self.pendingPrivateMessages.removeValue(forKey: key)\n }\n SecureLogger.log(\"Removed \\(excess) oldest pending private message queues\", \n category: SecureLogger.session, level: .info)\n }\n \n // Limit cached messages sent to peer\n if self.cachedMessagesSentToPeer.count > self.maxCachedMessagesSentToPeer {\n let excess = self.cachedMessagesSentToPeer.count - self.maxCachedMessagesSentToPeer\n let toRemove = self.cachedMessagesSentToPeer.prefix(excess)\n self.cachedMessagesSentToPeer.subtract(toRemove)\n SecureLogger.log(\"Removed \\(excess) oldest cached message tracking entries\", \n category: SecureLogger.session, level: .debug)\n }\n \n // Clean up pending relays\n self.pendingRelaysLock.lock()\n _ = self.pendingRelays.count\n self.pendingRelaysLock.unlock()\n \n // Clean up rate limiters\n self.cleanupRateLimiters()\n \n // Log memory status\n _ = Date().timeIntervalSince(startTime)\n // Memory cleanup completed\n \n // Estimate current memory usage and log if high\n let estimatedMemory = self.estimateMemoryUsage()\n if estimatedMemory > self.maxMemoryUsageBytes {\n SecureLogger.log(\"Warning: Estimated memory usage \\(estimatedMemory / 1024 / 1024)MB exceeds limit\", \n category: SecureLogger.session, level: .warning)\n }\n }\n }\n \n private func estimateMemoryUsage() -> Int {\n // Rough estimates based on typical sizes\n let messageSize = 512 // Average message size\n let fragmentSize = 512 // Average fragment size\n \n var totalBytes = 0\n \n // Processed messages (string storage + MessageState)\n processedMessagesLock.lock()\n totalBytes += processedMessages.count * 150 // messageID strings + MessageState struct\n processedMessagesLock.unlock()\n \n // Fragments\n for (_, fragments) in incomingFragments {\n totalBytes += fragments.count * fragmentSize\n }\n \n // Pending private messages\n for (_, messages) in pendingPrivateMessages {\n totalBytes += messages.count * messageSize\n }\n \n // Other caches\n totalBytes += cachedMessagesSentToPeer.count * 50 // peerID strings\n totalBytes += deliveredMessages.count * 100 // messageID strings\n totalBytes += recentlySentMessages.count * 100 // messageID strings\n \n return totalBytes\n }\n \n // MARK: - Rate Limiting\n \n private func isRateLimited(peerID: String, messageType: UInt8) -> Bool {\n rateLimiterLock.lock()\n defer { rateLimiterLock.unlock() }\n \n let now = Date()\n let cutoff = now.addingTimeInterval(-rateLimitWindow)\n \n // Clean old timestamps from total counter\n totalMessageTimestamps.removeAll { $0 < cutoff }\n \n // Check global rate limit with progressive throttling\n if totalMessageTimestamps.count >= maxTotalMessagesPerMinute {\n // Apply progressive throttling for global limit\n let overageRatio = Double(totalMessageTimestamps.count - maxTotalMessagesPerMinute) / Double(maxTotalMessagesPerMinute)\n let dropProbability = min(0.95, 0.5 + overageRatio * 0.5) // 50% to 95% drop rate\n \n if Double.random(in: 0...1) < dropProbability {\n SecureLogger.log(\"Global rate limit throttling: \\(totalMessageTimestamps.count) messages, drop prob: \\(Int(dropProbability * 100))%\", \n category: SecureLogger.security, level: .warning)\n return true\n }\n }\n \n // Determine which rate limiter to use based on message type\n let isChatMessage = messageType == MessageType.message.rawValue\n \n let limiter = isChatMessage ? messageRateLimiter : protocolMessageRateLimiter\n let maxPerMinute = isChatMessage ? maxChatMessagesPerPeerPerMinute : maxProtocolMessagesPerPeerPerMinute\n \n // Clean old timestamps for this peer\n if var timestamps = limiter[peerID] {\n timestamps.removeAll { $0 < cutoff }\n \n // Update the appropriate limiter\n if isChatMessage {\n messageRateLimiter[peerID] = timestamps\n } else {\n protocolMessageRateLimiter[peerID] = timestamps\n }\n \n // Progressive throttling for per-peer limit\n if timestamps.count >= maxPerMinute {\n // Calculate how much over the limit we are\n let overageRatio = Double(timestamps.count - maxPerMinute) / Double(maxPerMinute)\n \n // Progressive drop probability: starts at 30% when just over limit, increases to 90%\n let dropProbability = min(0.9, 0.3 + overageRatio * 0.6)\n \n if Double.random(in: 0...1) < dropProbability {\n let messageTypeStr = isChatMessage ? \"chat\" : \"protocol\"\n SecureLogger.log(\"Peer \\(peerID) \\(messageTypeStr) rate throttling: \\(timestamps.count) msgs/min, drop prob: \\(Int(dropProbability * 100))%\", \n category: SecureLogger.security, level: .info)\n return true\n } else {\n SecureLogger.log(\"Peer \\(peerID) rate throttling: allowing message (\\(timestamps.count) msgs/min)\", \n category: SecureLogger.security, level: .debug)\n }\n }\n }\n \n return false\n }\n \n private func recordMessage(from peerID: String, messageType: UInt8) {\n rateLimiterLock.lock()\n defer { rateLimiterLock.unlock() }\n \n let now = Date()\n \n // Record in global counter\n totalMessageTimestamps.append(now)\n \n // Determine which rate limiter to use based on message type\n let isChatMessage = messageType == MessageType.message.rawValue\n \n // Record for specific peer in the appropriate limiter\n if isChatMessage {\n if messageRateLimiter[peerID] == nil {\n messageRateLimiter[peerID] = []\n }\n messageRateLimiter[peerID]?.append(now)\n } else {\n if protocolMessageRateLimiter[peerID] == nil {\n protocolMessageRateLimiter[peerID] = []\n }\n protocolMessageRateLimiter[peerID]?.append(now)\n }\n }\n \n private func cleanupRateLimiters() {\n rateLimiterLock.lock()\n defer { rateLimiterLock.unlock() }\n \n let cutoff = Date().addingTimeInterval(-rateLimitWindow)\n \n // Clean global timestamps\n totalMessageTimestamps.removeAll { $0 < cutoff }\n \n // Clean up old identity announce tracking\n processedMessagesLock.lock()\n let identityCutoff = Date().addingTimeInterval(-identityAnnounceDuplicateWindow * 2)\n recentIdentityAnnounces = recentIdentityAnnounces.filter { $0.value > identityCutoff }\n processedMessagesLock.unlock()\n \n // Clean per-peer chat message timestamps\n for (peerID, timestamps) in messageRateLimiter {\n let filtered = timestamps.filter { $0 >= cutoff }\n if filtered.isEmpty {\n messageRateLimiter.removeValue(forKey: peerID)\n } else {\n messageRateLimiter[peerID] = filtered\n }\n }\n \n // Clean per-peer protocol message timestamps\n for (peerID, timestamps) in protocolMessageRateLimiter {\n let filtered = timestamps.filter { $0 >= cutoff }\n if filtered.isEmpty {\n protocolMessageRateLimiter.removeValue(forKey: peerID)\n } else {\n protocolMessageRateLimiter[peerID] = filtered\n }\n }\n \n SecureLogger.log(\"Rate limiter cleanup: tracking \\(messageRateLimiter.count) chat peers, \\(protocolMessageRateLimiter.count) protocol peers, \\(totalMessageTimestamps.count) total messages\", \n category: SecureLogger.session, level: .debug)\n }\n \n // MARK: - Cover Traffic\n \n private func startCoverTraffic() {\n // Start cover traffic with random interval\n scheduleCoverTraffic()\n }\n \n private func scheduleCoverTraffic() {\n // Random interval between 30-120 seconds\n let interval = TimeInterval.random(in: 30...120)\n \n coverTrafficTimer?.invalidate()\n coverTrafficTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { [weak self] _ in\n self?.sendDummyMessage()\n self?.scheduleCoverTraffic() // Schedule next dummy message\n }\n }\n \n private func sendDummyMessage() {\n // Only send dummy messages if we have connected peers with established sessions\n let peersWithSessions = getAllConnectedPeerIDs().filter { peerID in\n return noiseService.hasEstablishedSession(with: peerID)\n }\n \n guard !peersWithSessions.isEmpty else { \n SecureLogger.log(\"Cover traffic: No peers with established sessions, skipping dummy message\", \n category: SecureLogger.security, level: .debug)\n return \n }\n \n // Skip if battery is low\n if currentBatteryLevel < 0.2 {\n SecureLogger.log(\"Cover traffic: Battery low, skipping dummy message\", \n category: SecureLogger.security, level: .debug)\n return\n }\n \n // Pick a random peer with an established session to send to\n guard let randomPeer = peersWithSessions.randomElement() else { return }\n \n // Generate random dummy content\n let dummyContent = generateDummyContent()\n \n SecureLogger.log(\"Cover traffic: Sending dummy message to \\(randomPeer)\", \n category: SecureLogger.security, level: .info)\n \n // Send as a private message so it's encrypted\n let recipientNickname = collectionsQueue.sync {\n return peerNicknames[randomPeer] ?? \"unknown\"\n }\n \n sendPrivateMessage(dummyContent, to: randomPeer, recipientNickname: recipientNickname)\n }\n \n private func generateDummyContent() -> String {\n // Generate realistic-looking dummy messages\n let templates = [\n \"hey\",\n \"ok\",\n \"got it\",\n \"sure\",\n \"sounds good\",\n \"thanks\",\n \"np\",\n \"see you there\",\n \"on my way\",\n \"running late\",\n \"be there soon\",\n \"👍\",\n \"✓\",\n \"meeting at the usual spot\",\n \"confirmed\",\n \"roger that\"\n ]\n \n // Prefix with dummy marker (will be encrypted)\n return coverTrafficPrefix + (templates.randomElement() ?? \"ok\")\n }\n \n \n private func updatePeerLastSeen(_ peerID: String) {\n peerLastSeenTimestamps.set(peerID, value: Date())\n }\n \n private func sendPendingPrivateMessages(to peerID: String) {\n messageQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n // Get pending messages with proper queue synchronization\n let pendingMessages = self.collectionsQueue.sync {\n return self.pendingPrivateMessages[peerID]\n }\n \n guard let messages = pendingMessages else { return }\n \n SecureLogger.log(\"Sending \\(messages.count) pending private messages to \\(peerID)\", category: SecureLogger.session, level: .info)\n \n // Clear pending messages for this peer\n self.collectionsQueue.sync(flags: .barrier) {\n _ = self.pendingPrivateMessages.removeValue(forKey: peerID)\n }\n \n // Send each pending message\n for (content, recipientNickname, messageID) in messages {\n // Check if this is a read receipt\n if content.hasPrefix(\"READ_RECEIPT:\") {\n // Extract the original message ID\n let originalMessageID = String(content.dropFirst(\"READ_RECEIPT:\".count))\n SecureLogger.log(\"Sending queued read receipt for message \\(originalMessageID) to \\(peerID)\", category: SecureLogger.session, level: .debug)\n \n // Create and send the actual read receipt\n let receipt = ReadReceipt(\n originalMessageID: originalMessageID,\n readerID: self.myPeerID,\n readerNickname: recipientNickname // This is actually the reader's nickname\n )\n \n // Send the read receipt using the normal method\n DispatchQueue.global().async { [weak self] in\n self?.sendReadReceipt(receipt, to: peerID)\n }\n } else {\n // Regular message\n SecureLogger.log(\"Sending pending message \\(messageID) to \\(peerID)\", category: SecureLogger.session, level: .debug)\n // Use async to avoid blocking the queue\n DispatchQueue.global().async { [weak self] in\n self?.sendPrivateMessage(content, to: peerID, recipientNickname: recipientNickname, messageID: messageID)\n }\n }\n }\n }\n }\n \n // MARK: - Noise Protocol Support\n \n private func attemptHandshakeIfNeeded(with peerID: String, forceIfStale: Bool = false) {\n // Check if we already have an established session\n if noiseService.hasEstablishedSession(with: peerID) {\n SecureLogger.log(\"Already have established session with \\(peerID), skipping handshake\", \n category: SecureLogger.handshake, level: .debug)\n return\n }\n \n // Check if we should initiate using the handshake coordinator\n if !handshakeCoordinator.shouldInitiateHandshake(\n myPeerID: myPeerID, \n remotePeerID: peerID,\n forceIfStale: forceIfStale\n ) {\n SecureLogger.log(\"Should not initiate handshake with \\(peerID) at this time\", \n category: SecureLogger.handshake, level: .debug)\n return\n }\n \n // Initiate the handshake\n initiateNoiseHandshake(with: peerID)\n }\n \n // Send keep-alive pings to all connected peers to prevent iOS BLE timeouts\n private func sendKeepAlivePings() {\n let connectedPeers = collectionsQueue.sync {\n return Array(activePeers).filter { peerID in\n // Only send keepalive to authenticated peers that still exist\n // Check if this peer ID is still current (not rotated)\n guard let fingerprint = peerIDToFingerprint[peerID],\n let currentPeerID = fingerprintToPeerID[fingerprint],\n currentPeerID == peerID else {\n // This peer ID has rotated, skip it\n SecureLogger.log(\"Skipping keepalive for rotated peer ID: \\(peerID)\", \n category: SecureLogger.session, level: .debug)\n return false\n }\n \n // Check if we actually have a Noise session with this peer\n guard noiseService.hasEstablishedSession(with: peerID) else {\n SecureLogger.log(\"Skipping keepalive for \\(peerID) - no established session\", \n category: SecureLogger.session, level: .debug)\n return false\n }\n \n return peerConnectionStates[peerID] == .authenticated\n }\n }\n \n SecureLogger.log(\"Keep-alive timer: checking \\(connectedPeers.count) peers for pings\", \n category: SecureLogger.session, level: .debug)\n \n for peerID in connectedPeers {\n // Don't spam if we recently heard from them\n if let lastHeard = lastHeardFromPeer[peerID], \n Date().timeIntervalSince(lastHeard) < keepAliveInterval / 2 {\n SecureLogger.log(\"Skipping keepalive for \\(peerID) - heard recently\", \n category: SecureLogger.session, level: .debug)\n continue // Skip if we heard from them in the last 10 seconds\n }\n \n SecureLogger.log(\"Sending keepalive ping to \\(peerID)\", \n category: SecureLogger.session, level: .debug)\n validateNoiseSession(with: peerID)\n }\n }\n \n // Validate an existing Noise session by sending an encrypted ping\n private func validateNoiseSession(with peerID: String) {\n let encryptionQueue = getEncryptionQueue(for: peerID)\n \n encryptionQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Create a ping packet with minimal data\n let pingData = \"ping:\\(Date().timeIntervalSince1970)\".data(using: .utf8)!\n \n do {\n // Try to encrypt a small ping message\n let encrypted = try self.noiseService.encrypt(pingData, for: peerID)\n \n // Create a validation packet (won't be displayed to user)\n let packet = BitchatPacket(\n type: MessageType.systemValidation.rawValue,\n senderID: Data(hexString: self.myPeerID) ?? Data(),\n recipientID: Data(hexString: peerID),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: encrypted,\n signature: nil,\n ttl: 1 )\n \n // System validation should go directly to the peer when possible\n if !self.sendDirectToRecipient(packet, recipientPeerID: peerID) {\n // Fall back to selective relay if direct delivery fails\n self.sendViaSelectiveRelay(packet, recipientPeerID: peerID)\n }\n \n SecureLogger.log(\"Sent session validation ping to \\(peerID)\", \n category: SecureLogger.session, level: .debug)\n } catch {\n // Encryption failed - session is invalid\n SecureLogger.log(\"Session validation failed for \\(peerID): \\(error)\", \n category: SecureLogger.session, level: .warning)\n \n // Clear the invalid session\n self.cleanupPeerCryptoState(peerID)\n \n // Initiate fresh handshake\n DispatchQueue.main.async { [weak self] in\n self?.attemptHandshakeIfNeeded(with: peerID, forceIfStale: true)\n }\n }\n }\n }\n \n private func initiateNoiseHandshake(with peerID: String) {\n // Use noiseService directly\n \n SecureLogger.log(\"Initiating Noise handshake with \\(peerID)\", category: SecureLogger.noise, level: .info)\n \n // Check if we already have an established session\n if noiseService.hasEstablishedSession(with: peerID) {\n SecureLogger.log(\"Already have established session with \\(peerID)\", category: SecureLogger.noise, level: .debug)\n // Clear any lingering handshake attempt time\n handshakeAttemptTimes.removeValue(forKey: peerID)\n handshakeCoordinator.recordHandshakeSuccess(peerID: peerID)\n \n // Update session state to established\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[peerID] = .established\n }\n \n // Update connection state to authenticated\n updatePeerConnectionState(peerID, state: .authenticated)\n \n // Force UI update since we have an existing session\n DispatchQueue.main.async { [weak self] in\n (self?.delegate as? ChatViewModel)?.updateEncryptionStatusForPeers()\n }\n \n return\n }\n \n // Update state to handshaking\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[peerID] = .handshaking\n }\n \n // Check if we have pending messages\n let hasPendingMessages = collectionsQueue.sync {\n return pendingPrivateMessages[peerID]?.isEmpty == false\n }\n \n // Check with coordinator if we should initiate\n if !handshakeCoordinator.shouldInitiateHandshake(myPeerID: myPeerID, remotePeerID: peerID, forceIfStale: hasPendingMessages) {\n SecureLogger.log(\"Coordinator says we should not initiate handshake with \\(peerID)\", category: SecureLogger.handshake, level: .debug)\n \n if hasPendingMessages {\n // Check if peer is still connected before retrying\n let connectionState = collectionsQueue.sync { peerConnectionStates[peerID] ?? .disconnected }\n \n if connectionState == .disconnected {\n // Peer is disconnected - clear pending messages and stop retrying\n SecureLogger.log(\"Peer \\(peerID) is disconnected, clearing pending messages\", category: SecureLogger.handshake, level: .info)\n collectionsQueue.async(flags: .barrier) { [weak self] in\n self?.pendingPrivateMessages[peerID]?.removeAll()\n }\n handshakeCoordinator.resetHandshakeState(for: peerID)\n } else {\n // Peer is still connected but handshake is stuck\n // Send identity announce to prompt them to initiate if they have lower ID\n SecureLogger.log(\"Handshake stuck with connected peer \\(peerID), sending identity announce\", category: SecureLogger.handshake, level: .info)\n sendNoiseIdentityAnnounce(to: peerID)\n \n // Only retry if we haven't retried too many times\n let retryCount = handshakeCoordinator.getRetryCount(for: peerID)\n if retryCount < 3 {\n handshakeCoordinator.incrementRetryCount(for: peerID)\n DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { [weak self] in\n self?.initiateNoiseHandshake(with: peerID)\n }\n } else {\n SecureLogger.log(\"Max retries reached for \\(peerID), clearing pending messages\", category: SecureLogger.handshake, level: .warning)\n collectionsQueue.async(flags: .barrier) { [weak self] in\n self?.pendingPrivateMessages[peerID]?.removeAll()\n }\n handshakeCoordinator.resetHandshakeState(for: peerID)\n }\n }\n }\n return\n }\n \n // Check if there's a retry delay\n if let retryDelay = handshakeCoordinator.getRetryDelay(for: peerID), retryDelay > 0 {\n SecureLogger.log(\"Waiting \\(retryDelay)s before retrying handshake with \\(peerID)\", category: SecureLogger.handshake, level: .debug)\n DispatchQueue.main.asyncAfter(deadline: .now() + retryDelay) { [weak self] in\n self?.initiateNoiseHandshake(with: peerID)\n }\n return\n }\n \n // Record that we're initiating\n handshakeCoordinator.recordHandshakeInitiation(peerID: peerID)\n handshakeAttemptTimes[peerID] = Date()\n \n // Update connection state to authenticating\n updatePeerConnectionState(peerID, state: .authenticating)\n \n do {\n // Generate handshake initiation message\n let handshakeData = try noiseService.initiateHandshake(with: peerID)\n SecureLogger.logHandshake(\"initiated\", peerID: peerID, success: true)\n \n // Send handshake initiation\n let packet = BitchatPacket(\n type: MessageType.noiseHandshakeInit.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: peerID) ?? Data(), // Add recipient ID for targeted delivery\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: handshakeData,\n signature: nil,\n ttl: 6 // Increased TTL for better delivery on startup\n )\n \n // Track packet for ACK\n trackPacketForAck(packet)\n \n // Try direct delivery first for handshake init\n if !sendDirectToRecipient(packet, recipientPeerID: peerID) {\n // Handshakes are critical - use broadcast as fallback to ensure delivery\n SecureLogger.log(\"Recipient \\(peerID) not directly connected for handshake init, using broadcast\", \n category: SecureLogger.session, level: .info)\n broadcastPacket(packet)\n }\n \n // Schedule a retry check after 5 seconds\n DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) { [weak self] in\n guard let self = self else { return }\n // Check if handshake completed\n if !self.noiseService.hasEstablishedSession(with: peerID) {\n let state = self.handshakeCoordinator.getHandshakeState(for: peerID)\n if case .initiating = state {\n SecureLogger.log(\"Handshake with \\(peerID) not completed after 5s, will retry\", category: SecureLogger.handshake, level: .warning)\n // The handshake coordinator will handle retry logic\n }\n }\n }\n \n } catch NoiseSessionError.alreadyEstablished {\n // Session already established, no need to handshake\n handshakeCoordinator.recordHandshakeSuccess(peerID: peerID)\n } catch {\n // Failed to initiate handshake\n handshakeCoordinator.recordHandshakeFailure(peerID: peerID, reason: error.localizedDescription)\n SecureLogger.logSecurityEvent(.handshakeFailed(peerID: peerID, error: error.localizedDescription))\n }\n }\n \n private func handleNoiseHandshakeMessage(from peerID: String, message: Data, isInitiation: Bool) {\n // Use noiseService directly\n SecureLogger.logHandshake(\"processing \\(isInitiation ? \"init\" : \"response\")\", peerID: peerID, success: true)\n \n // Get current handshake state before processing\n let currentState = handshakeCoordinator.getHandshakeState(for: peerID)\n let hasEstablishedSession = noiseService.hasEstablishedSession(with: peerID)\n SecureLogger.log(\"Current handshake state for \\(peerID): \\(currentState), hasEstablishedSession: \\(hasEstablishedSession)\", category: SecureLogger.noise, level: .info)\n \n // Check for duplicate handshake messages\n if handshakeCoordinator.isDuplicateHandshakeMessage(message) {\n SecureLogger.log(\"Duplicate handshake message from \\(peerID), ignoring\", category: SecureLogger.handshake, level: .debug)\n return\n }\n \n // If this is an initiation, check if we should accept it\n if isInitiation {\n if !handshakeCoordinator.shouldAcceptHandshakeInitiation(myPeerID: myPeerID, remotePeerID: peerID) {\n SecureLogger.log(\"Coordinator says we should not accept handshake from \\(peerID)\", category: SecureLogger.handshake, level: .debug)\n return\n }\n // Record that we're responding\n handshakeCoordinator.recordHandshakeResponse(peerID: peerID)\n \n // Update connection state to authenticating\n updatePeerConnectionState(peerID, state: .authenticating)\n }\n \n do {\n // Process handshake message\n if let response = try noiseService.processHandshakeMessage(from: peerID, message: message) {\n // Handshake response ready to send\n \n // Always send responses as handshake response type\n let packet = BitchatPacket(\n type: MessageType.noiseHandshakeResp.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: peerID) ?? Data(), // Add recipient ID for targeted delivery\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: response,\n signature: nil,\n ttl: 6 // Increased TTL for better delivery on startup\n )\n \n // Track packet for ACK\n trackPacketForAck(packet)\n \n // Try direct delivery first for handshake response\n if !sendDirectToRecipient(packet, recipientPeerID: peerID) {\n // Handshakes are critical - use broadcast as fallback to ensure delivery\n SecureLogger.log(\"Recipient \\(peerID) not directly connected for handshake response, using broadcast\", \n category: SecureLogger.session, level: .info)\n broadcastPacket(packet)\n }\n } else {\n SecureLogger.log(\"No response needed from processHandshakeMessage (isInitiation: \\(isInitiation))\", category: SecureLogger.noise, level: .debug)\n }\n \n // Check if handshake is complete\n let sessionEstablished = noiseService.hasEstablishedSession(with: peerID)\n _ = handshakeCoordinator.getHandshakeState(for: peerID)\n // Handshake state updated\n \n if sessionEstablished {\n SecureLogger.logSecurityEvent(.handshakeCompleted(peerID: peerID))\n // Unlock rotation now that handshake is complete\n unlockRotation()\n \n // Session established successfully\n handshakeCoordinator.recordHandshakeSuccess(peerID: peerID)\n \n // Update session state to established\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[peerID] = .established\n }\n \n // Update connection state to authenticated\n updatePeerConnectionState(peerID, state: .authenticated)\n \n // Clear handshake attempt time on success\n handshakeAttemptTimes.removeValue(forKey: peerID)\n \n // Initialize last successful message time\n lastSuccessfulMessageTime[peerID] = Date()\n SecureLogger.log(\"Initialized lastSuccessfulMessageTime for \\(peerID)\", category: SecureLogger.noise, level: .debug)\n \n // Send identity announcement to this specific peer\n sendNoiseIdentityAnnounce(to: peerID)\n \n // Also broadcast to ensure all peers get it\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n self?.sendNoiseIdentityAnnounce()\n }\n \n // Send regular announce packet after handshake to trigger connect message\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [weak self] in\n self?.sendAnnouncementToPeer(peerID)\n }\n \n // Send any pending private messages\n self.sendPendingPrivateMessages(to: peerID)\n \n // Send any cached store-and-forward messages\n sendCachedMessages(to: peerID)\n }\n } catch NoiseSessionError.alreadyEstablished {\n // Session already established, ignore handshake\n SecureLogger.log(\"Handshake already established with \\(peerID)\", category: SecureLogger.noise, level: .info)\n handshakeCoordinator.recordHandshakeSuccess(peerID: peerID)\n \n // Update session state to established\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[peerID] = .established\n }\n } catch {\n // Handshake failed\n handshakeCoordinator.recordHandshakeFailure(peerID: peerID, reason: error.localizedDescription)\n SecureLogger.logSecurityEvent(.handshakeFailed(peerID: peerID, error: error.localizedDescription))\n SecureLogger.log(\"Handshake failed with \\(peerID): \\(error)\", category: SecureLogger.noise, level: .error)\n \n // Update session state to failed\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[peerID] = .failed(error)\n }\n \n // If handshake failed due to authentication error, clear the session to allow retry\n if case NoiseError.authenticationFailure = error {\n SecureLogger.log(\"Handshake failed with \\(peerID): authenticationFailure - clearing session\", category: SecureLogger.noise, level: .warning)\n cleanupPeerCryptoState(peerID)\n }\n }\n }\n \n private func handleNoiseEncryptedMessage(from peerID: String, encryptedData: Data, originalPacket: BitchatPacket, peripheral: CBPeripheral? = nil) {\n // Use noiseService directly\n \n // For Noise encrypted messages, we need to decrypt first to check the inner packet\n // The outer packet's recipientID might be for routing, not the final recipient\n \n // Create unique identifier for this encrypted message\n let messageHash = encryptedData.prefix(32).hexEncodedString() // Use first 32 bytes as identifier\n let messageKey = \"\\(peerID)-\\(messageHash)\"\n \n // Check if we've already processed this exact encrypted message\n let alreadyProcessed = collectionsQueue.sync(flags: .barrier) {\n if processedNoiseMessages.contains(messageKey) {\n return true\n }\n processedNoiseMessages.insert(messageKey)\n return false\n }\n \n if alreadyProcessed {\n return\n }\n \n do {\n // Decrypt the message\n // Attempting to decrypt\n let decryptedData = try noiseService.decrypt(encryptedData, from: peerID)\n // Successfully decrypted message\n \n // Update last successful message time\n lastSuccessfulMessageTime[peerID] = Date()\n \n // Send protocol ACK after successful decryption (only once per encrypted packet)\n sendProtocolAck(for: originalPacket, to: peerID)\n \n // If we can decrypt messages from this peer, they should be in activePeers\n let wasAdded = collectionsQueue.sync(flags: .barrier) {\n if !self.activePeers.contains(peerID) {\n SecureLogger.log(\"Adding \\(peerID) to activePeers after successful decryption\", category: SecureLogger.noise, level: .info)\n return self.activePeers.insert(peerID).inserted\n }\n return false\n }\n \n if wasAdded {\n // Notify about peer list update\n self.notifyPeerListUpdate()\n }\n \n // Check if this is a special format message (type marker + payload)\n if decryptedData.count > 1 {\n let typeMarker = decryptedData[0]\n \n // Check if this is a delivery ACK with the new format\n if typeMarker == MessageType.deliveryAck.rawValue {\n // Extract the ACK JSON data (skip the type marker)\n let ackData = decryptedData.dropFirst()\n \n // Decode the delivery ACK - try binary first, then JSON\n if let ack = DeliveryAck.fromBinaryData(ackData) {\n SecureLogger.log(\"Received binary delivery ACK via Noise: \\(ack.originalMessageID) from \\(ack.recipientNickname)\", category: SecureLogger.session, level: .debug)\n \n // Process the ACK\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n return\n } else if let ack = DeliveryAck.decode(from: ackData) {\n SecureLogger.log(\"Received JSON delivery ACK via Noise: \\(ack.originalMessageID) from \\(ack.recipientNickname)\", category: SecureLogger.session, level: .debug)\n \n // Process the ACK\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n return\n } else {\n SecureLogger.log(\"Failed to decode delivery ACK via Noise - data size: \\(ackData.count)\", category: SecureLogger.session, level: .warning)\n }\n }\n \n // Check if this is a read receipt with the new format\n else if typeMarker == MessageType.readReceipt.rawValue {\n // Extract the receipt binary data (skip the type marker)\n let receiptData = decryptedData.dropFirst()\n \n // Decode the read receipt from binary\n if let receipt = ReadReceipt.fromBinaryData(receiptData) {\n SecureLogger.log(\"Received binary read receipt via Noise: \\(receipt.originalMessageID) from \\(receipt.readerNickname)\", category: SecureLogger.session, level: .debug)\n \n // Process the read receipt\n DispatchQueue.main.async {\n self.delegate?.didReceiveReadReceipt(receipt)\n }\n return\n } else {\n SecureLogger.log(\"Failed to decode read receipt via Noise - data size: \\(receiptData.count)\", category: SecureLogger.session, level: .warning)\n }\n }\n }\n \n // Try to parse as a full inner packet (for backward compatibility and other message types)\n if let innerPacket = BitchatPacket.from(decryptedData) {\n SecureLogger.log(\"Successfully parsed inner packet - type: \\(MessageType(rawValue: innerPacket.type)?.description ?? \"unknown\"), from: \\(innerPacket.senderID.hexEncodedString()), to: \\(innerPacket.recipientID?.hexEncodedString() ?? \"broadcast\")\", category: SecureLogger.session, level: .debug)\n \n // Process the decrypted inner packet\n // The packet will be handled according to its recipient ID\n // If it's for us, it won't be relayed\n // Pass the peripheral context for proper ACK routing\n handleReceivedPacket(innerPacket, from: peerID, peripheral: peripheral)\n } else {\n SecureLogger.log(\"Failed to parse inner packet from decrypted data\", category: SecureLogger.encryption, level: .warning)\n }\n } catch {\n // Failed to decrypt - might need to re-establish session\n SecureLogger.log(\"Failed to decrypt Noise message from \\(peerID): \\(error)\", category: SecureLogger.encryption, level: .error)\n if !noiseService.hasEstablishedSession(with: peerID) {\n SecureLogger.log(\"No Noise session with \\(peerID), attempting handshake\", category: SecureLogger.noise, level: .info)\n attemptHandshakeIfNeeded(with: peerID, forceIfStale: true)\n } else {\n SecureLogger.log(\"Have session with \\(peerID) but decryption failed\", category: SecureLogger.encryption, level: .warning)\n \n // Send a NACK to inform peer that decryption failed\n sendProtocolNack(for: originalPacket, to: peerID,\n reason: \"Decryption failed\",\n errorCode: .decryptionFailed)\n \n // The NACK handler will take care of clearing sessions and re-establishing\n // Don't initiate anything here to avoid race conditions\n \n // Update UI to show encryption is broken\n DispatchQueue.main.async { [weak self] in\n if let chatVM = self?.delegate as? ChatViewModel {\n chatVM.updateEncryptionStatusForPeer(peerID)\n }\n }\n }\n }\n }\n \n \n // MARK: - Protocol Version Negotiation\n \n private func handleVersionHello(from peerID: String, data: Data, peripheral: CBPeripheral? = nil) {\n // Create a copy to avoid potential race conditions\n let dataCopy = Data(data)\n \n // Safety check for empty data\n guard !dataCopy.isEmpty else {\n SecureLogger.log(\"Received empty version hello data from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n // Check if this peer is reconnecting after disconnect\n if let lastConnected = lastConnectionTime[peerID] {\n let timeSinceLastConnection = Date().timeIntervalSince(lastConnected)\n // Only clear truly stale sessions, not on every reconnect\n if timeSinceLastConnection > 86400.0 { // More than 24 hours since last connection\n // Clear any stale Noise session\n if noiseService.hasEstablishedSession(with: peerID) {\n SecureLogger.log(\"Peer \\(peerID) reconnecting after \\(Int(timeSinceLastConnection))s - clearing stale session\", category: SecureLogger.noise, level: .info)\n cleanupPeerCryptoState(peerID)\n }\n } else if timeSinceLastConnection > 5.0 {\n // Just log the reconnection, don't clear the session\n SecureLogger.log(\"Peer \\(peerID) reconnecting after \\(Int(timeSinceLastConnection))s - keeping existing session\", category: SecureLogger.noise, level: .info)\n }\n }\n \n // Update last connection time\n lastConnectionTime[peerID] = Date()\n \n // Check if we've already negotiated version with this peer\n if let existingVersion = negotiatedVersions[peerID] {\n SecureLogger.log(\"Already negotiated version \\(existingVersion) with \\(peerID), skipping re-negotiation\", \n category: SecureLogger.session, level: .debug)\n // If we have a session, validate it\n if noiseService.hasEstablishedSession(with: peerID) {\n validateNoiseSession(with: peerID)\n }\n return\n }\n \n // Try JSON first if it looks like JSON\n let hello: VersionHello?\n if let firstByte = dataCopy.first, firstByte == 0x7B { // '{' character\n SecureLogger.log(\"Version hello from \\(peerID) appears to be JSON (size: \\(dataCopy.count))\", category: SecureLogger.session, level: .debug)\n hello = VersionHello.decode(from: dataCopy) ?? VersionHello.fromBinaryData(dataCopy)\n } else {\n SecureLogger.log(\"Version hello from \\(peerID) appears to be binary (size: \\(dataCopy.count), first byte: \\(dataCopy.first?.description ?? \"nil\"))\", category: SecureLogger.session, level: .debug)\n hello = VersionHello.fromBinaryData(dataCopy) ?? VersionHello.decode(from: dataCopy)\n }\n \n guard let hello = hello else {\n SecureLogger.log(\"Failed to decode version hello from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n SecureLogger.log(\"Received version hello from \\(peerID): supported versions \\(hello.supportedVersions), preferred \\(hello.preferredVersion)\", \n category: SecureLogger.session, level: .debug)\n \n // Find the best common version\n let ourVersions = Array(ProtocolVersion.supportedVersions)\n if let agreedVersion = ProtocolVersion.negotiateVersion(clientVersions: hello.supportedVersions, serverVersions: ourVersions) {\n // We can communicate! Send ACK\n SecureLogger.log(\"Version negotiation agreed with \\(peerID): v\\(agreedVersion) (client: \\(hello.clientVersion), platform: \\(hello.platform))\", category: SecureLogger.session, level: .info)\n negotiatedVersions[peerID] = agreedVersion\n versionNegotiationState[peerID] = .ackReceived(version: agreedVersion)\n \n let ack = VersionAck(\n agreedVersion: agreedVersion,\n serverVersion: Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String ?? \"1.0\",\n platform: getPlatformString()\n )\n \n sendVersionAck(ack, to: peerID)\n \n // Lazy handshake: No longer initiate handshake after version negotiation\n // Just announce our identity\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in\n guard let self = self else { return }\n \n // Just announce our identity\n self.sendNoiseIdentityAnnounce()\n \n SecureLogger.log(\"Version negotiation complete with \\(peerID) - lazy handshake mode\", \n category: SecureLogger.handshake, level: .info)\n }\n } else {\n // No compatible version\n SecureLogger.log(\"Version negotiation failed with \\(peerID): No compatible version (client supports: \\(hello.supportedVersions))\", category: SecureLogger.session, level: .warning)\n versionNegotiationState[peerID] = .failed(reason: \"No compatible protocol version\")\n \n let ack = VersionAck(\n agreedVersion: 0,\n serverVersion: Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String ?? \"1.0\",\n platform: getPlatformString(),\n rejected: true,\n reason: \"No compatible protocol version. Client supports: \\(hello.supportedVersions), server supports: \\(ourVersions)\"\n )\n \n sendVersionAck(ack, to: peerID)\n \n // Disconnect after a short delay\n if let peripheral = peripheral {\n DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in\n self?.centralManager?.cancelPeripheralConnection(peripheral)\n }\n }\n }\n }\n \n private func handleVersionAck(from peerID: String, data: Data) {\n // Create a copy to avoid potential race conditions\n let dataCopy = Data(data)\n \n // Safety check for empty data\n guard !dataCopy.isEmpty else {\n SecureLogger.log(\"Received empty version ack data from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n // Try JSON first if it looks like JSON\n let ack: VersionAck?\n if let firstByte = dataCopy.first, firstByte == 0x7B { // '{' character\n ack = VersionAck.decode(from: dataCopy) ?? VersionAck.fromBinaryData(dataCopy)\n } else {\n ack = VersionAck.fromBinaryData(dataCopy) ?? VersionAck.decode(from: dataCopy)\n }\n \n guard let ack = ack else {\n SecureLogger.log(\"Failed to decode version ack from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n if ack.rejected {\n SecureLogger.log(\"Version negotiation rejected by \\(peerID): \\(ack.reason ?? \"Unknown reason\")\", \n category: SecureLogger.session, level: .error)\n versionNegotiationState[peerID] = .failed(reason: ack.reason ?? \"Version rejected\")\n \n // Clean up state for incompatible peer\n collectionsQueue.sync(flags: .barrier) {\n _ = self.activePeers.remove(peerID)\n _ = self.peerNicknames.removeValue(forKey: peerID)\n _ = self.lastHeardFromPeer.removeValue(forKey: peerID)\n }\n announcedPeers.remove(peerID)\n \n // Clean up any Noise session\n cleanupPeerCryptoState(peerID)\n \n // Notify delegate about incompatible peer disconnection\n DispatchQueue.main.async { [weak self] in\n self?.delegate?.didDisconnectFromPeer(peerID)\n }\n } else {\n // Version negotiation successful\n negotiatedVersions[peerID] = ack.agreedVersion\n versionNegotiationState[peerID] = .ackReceived(version: ack.agreedVersion)\n \n // If we were the initiator (sent hello first), proceed with Noise handshake\n // Note: Since we're handling their ACK, they initiated, so we should not initiate again\n // The peer who sent hello will initiate the Noise handshake\n }\n }\n \n private func sendVersionHello(to peripheral: CBPeripheral? = nil) {\n let hello = VersionHello(\n clientVersion: Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String ?? \"1.0\",\n platform: getPlatformString()\n )\n \n let helloData = hello.toBinaryData()\n \n let packet = BitchatPacket(\n type: MessageType.versionHello.rawValue,\n ttl: 1, // Version negotiation is direct, no relay\n senderID: myPeerID,\n payload: helloData )\n \n // Mark that we initiated version negotiation\n // We don't know the peer ID yet from peripheral, so we'll track it when we get the response\n \n if let peripheral = peripheral,\n let characteristic = peripheralCharacteristics[peripheral] {\n // Send directly to specific peripheral\n if let data = packet.toBinaryData() {\n writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: nil)\n }\n } else {\n // Broadcast to all\n broadcastPacket(packet)\n }\n }\n \n private func sendVersionAck(_ ack: VersionAck, to peerID: String) {\n let ackData = ack.toBinaryData()\n \n let packet = BitchatPacket(\n type: MessageType.versionAck.rawValue,\n senderID: Data(myPeerID.utf8),\n recipientID: Data(peerID.utf8),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: ackData,\n signature: nil,\n ttl: 1 // Direct response, no relay\n )\n \n // Version ACKs should go directly to the peer when possible\n if !sendDirectToRecipient(packet, recipientPeerID: peerID) {\n // Fall back to selective relay if direct delivery fails\n sendViaSelectiveRelay(packet, recipientPeerID: peerID)\n }\n }\n \n private func getPlatformString() -> String {\n #if os(iOS)\n return \"iOS\"\n #elseif os(macOS)\n return \"macOS\"\n #else\n return \"Unknown\"\n #endif\n }\n \n // MARK: - Protocol ACK/NACK Handling\n \n private func handleProtocolAck(from peerID: String, data: Data) {\n guard let ack = ProtocolAck.fromBinaryData(data) else {\n SecureLogger.log(\"Failed to decode protocol ACK from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n SecureLogger.log(\"Received protocol ACK from \\(peerID) for packet \\(ack.originalPacketID), type: \\(ack.packetType), ackID: \\(ack.ackID)\", \n category: SecureLogger.session, level: .debug)\n \n // Remove from pending ACKs and mark as acknowledged\n // Note: readUUID returns uppercase, but we track with lowercase\n let normalizedPacketID = ack.originalPacketID.lowercased()\n _ = collectionsQueue.sync(flags: .barrier) {\n pendingAcks.removeValue(forKey: normalizedPacketID)\n }\n \n // Track this packet as acknowledged to prevent future retries\n acknowledgedPacketsLock.lock()\n acknowledgedPackets.insert(ack.originalPacketID)\n // Keep only recent acknowledged packets (last 1000)\n if acknowledgedPackets.count > 1000 {\n // Remove oldest entries (this is approximate since Set doesn't maintain order)\n acknowledgedPackets = Set(Array(acknowledgedPackets).suffix(1000))\n }\n acknowledgedPacketsLock.unlock()\n \n // Handle specific packet types that need ACK confirmation\n if let messageType = MessageType(rawValue: ack.packetType) {\n switch messageType {\n case .noiseHandshakeInit, .noiseHandshakeResp:\n SecureLogger.log(\"Handshake confirmed by \\(peerID)\", category: SecureLogger.handshake, level: .info)\n case .noiseEncrypted:\n // Encrypted message confirmed\n break\n default:\n break\n }\n }\n }\n \n private func handleProtocolNack(from peerID: String, data: Data) {\n guard let nack = ProtocolNack.fromBinaryData(data) else {\n SecureLogger.log(\"Failed to decode protocol NACK from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n SecureLogger.log(\"Received protocol NACK from \\(peerID) for packet \\(nack.originalPacketID): \\(nack.reason)\", \n category: SecureLogger.session, level: .warning)\n \n // Remove from pending ACKs\n _ = collectionsQueue.sync(flags: .barrier) {\n pendingAcks.removeValue(forKey: nack.originalPacketID)\n }\n \n // Handle specific error codes\n if let errorCode = ProtocolNack.ErrorCode(rawValue: nack.errorCode) {\n switch errorCode {\n case .decryptionFailed:\n // Session is out of sync - both sides need to clear and re-establish\n SecureLogger.log(\"Decryption failed at \\(peerID), clearing session and re-establishing\", \n category: SecureLogger.encryption, level: .warning)\n \n // Clear our session state and handshake coordinator state\n cleanupPeerCryptoState(peerID)\n handshakeCoordinator.resetHandshakeState(for: peerID)\n \n // Update connection state\n updatePeerConnectionState(peerID, state: .connected)\n \n // Use deterministic role assignment to prevent race conditions\n let shouldInitiate = handshakeCoordinator.determineHandshakeRole(\n myPeerID: myPeerID,\n remotePeerID: peerID\n ) == .initiator\n \n if shouldInitiate {\n // Small delay to ensure both sides have cleared state\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n guard let self = self else { return }\n SecureLogger.log(\"Initiating handshake after decryption failure with \\(peerID)\", \n category: SecureLogger.session, level: .info)\n self.attemptHandshakeIfNeeded(with: peerID, forceIfStale: true)\n }\n } else {\n // Send identity announcement to signal we're ready\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n guard let self = self else { return }\n SecureLogger.log(\"Sending identity announcement after decryption failure to \\(peerID)\", \n category: SecureLogger.session, level: .info)\n self.sendNoiseIdentityAnnounce(to: peerID)\n }\n }\n case .sessionExpired:\n // Clear session and re-handshake\n SecureLogger.log(\"Session expired at \\(peerID), clearing and re-handshaking\", \n category: SecureLogger.session, level: .warning)\n cleanupPeerCryptoState(peerID)\n handshakeCoordinator.resetHandshakeState(for: peerID)\n attemptHandshakeIfNeeded(with: peerID, forceIfStale: true)\n default:\n break\n }\n }\n }\n \n private func handleHandshakeRequest(from peerID: String, data: Data) {\n guard let request = HandshakeRequest.fromBinaryData(data) else {\n SecureLogger.log(\"Failed to decode handshake request from \\(peerID)\", category: SecureLogger.noise, level: .error)\n return\n }\n \n // Verify this request is for us\n guard request.targetID == myPeerID else {\n // This request is not for us, might need to relay\n return\n }\n \n SecureLogger.log(\"Received handshake request from \\(request.requesterID) (\\(request.requesterNickname)) with \\(request.pendingMessageCount) pending messages\", \n category: SecureLogger.noise, level: .info)\n \n // Don't show handshake request notification in UI\n // User requested to remove this notification\n /*\n DispatchQueue.main.async { [weak self] in\n if let chatVM = self?.delegate as? ChatViewModel {\n // Notify the UI that someone wants to send messages\n chatVM.handleHandshakeRequest(from: request.requesterID, \n nickname: request.requesterNickname,\n pendingCount: request.pendingMessageCount)\n }\n }\n */\n \n // Check if we already have a session\n if noiseService.hasEstablishedSession(with: peerID) {\n // We already have a session, no action needed\n SecureLogger.log(\"Already have session with \\(peerID), ignoring handshake request\", category: SecureLogger.noise, level: .debug)\n return\n }\n \n // Apply tie-breaker logic for handshake initiation\n if myPeerID < peerID {\n // We have lower ID, initiate handshake\n SecureLogger.log(\"Initiating handshake with \\(peerID) in response to handshake request\", category: SecureLogger.noise, level: .info)\n initiateNoiseHandshake(with: peerID)\n } else {\n // We have higher ID, send identity announce to prompt them\n SecureLogger.log(\"Sending identity announce to \\(peerID) in response to handshake request\", category: SecureLogger.noise, level: .info)\n sendNoiseIdentityAnnounce(to: peerID)\n }\n }\n \n // Send protocol ACK for important packets\n private func sendProtocolAck(for packet: BitchatPacket, to peerID: String, hopCount: UInt8 = 0) {\n // Generate packet ID from packet content hash\n let packetID = generatePacketID(for: packet)\n \n // Debug: log packet details\n _ = packet.senderID.prefix(4).hexEncodedString()\n _ = packet.recipientID?.prefix(4).hexEncodedString() ?? \"nil\"\n // Send protocol ACK\n \n let ack = ProtocolAck(\n originalPacketID: packetID,\n senderID: packet.senderID.hexEncodedString(),\n receiverID: myPeerID,\n packetType: packet.type,\n hopCount: hopCount\n )\n \n let ackPacket = BitchatPacket(\n type: MessageType.protocolAck.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: peerID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: ack.toBinaryData(),\n signature: nil,\n ttl: 3 // ACKs don't need to travel far\n )\n \n // Protocol ACKs should go directly to the sender when possible\n if !sendDirectToRecipient(ackPacket, recipientPeerID: peerID) {\n // Fall back to selective relay if direct delivery fails\n sendViaSelectiveRelay(ackPacket, recipientPeerID: peerID)\n }\n }\n \n // Send protocol NACK for failed packets\n private func sendProtocolNack(for packet: BitchatPacket, to peerID: String, reason: String, errorCode: ProtocolNack.ErrorCode) {\n let packetID = generatePacketID(for: packet)\n \n let nack = ProtocolNack(\n originalPacketID: packetID,\n senderID: packet.senderID.hexEncodedString(),\n receiverID: myPeerID,\n packetType: packet.type,\n reason: reason,\n errorCode: errorCode\n )\n \n let nackPacket = BitchatPacket(\n type: MessageType.protocolNack.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: peerID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: nack.toBinaryData(),\n signature: nil,\n ttl: 3 // NACKs don't need to travel far\n )\n \n // Protocol NACKs should go directly to the sender when possible\n if !sendDirectToRecipient(nackPacket, recipientPeerID: peerID) {\n // Fall back to selective relay if direct delivery fails\n sendViaSelectiveRelay(nackPacket, recipientPeerID: peerID)\n }\n }\n \n // Generate unique packet ID from immutable packet fields\n private func generatePacketID(for packet: BitchatPacket) -> String {\n // Use only immutable fields for ID generation to ensure consistency\n // across network hops (TTL changes, so can't use full packet data)\n \n // Create a deterministic ID using SHA256 of immutable fields\n var data = Data()\n data.append(packet.senderID)\n data.append(contentsOf: withUnsafeBytes(of: packet.timestamp) { Array($0) })\n data.append(packet.type)\n // Add first 32 bytes of payload for uniqueness\n data.append(packet.payload.prefix(32))\n \n let hash = SHA256.hash(data: data)\n let hashData = Data(hash)\n \n // Take first 16 bytes for UUID format\n let bytes = Array(hashData.prefix(16))\n \n // Format as UUID\n let p1 = String(format: \"%02x%02x%02x%02x\", bytes[0], bytes[1], bytes[2], bytes[3])\n let p2 = String(format: \"%02x%02x\", bytes[4], bytes[5])\n let p3 = String(format: \"%02x%02x\", bytes[6], bytes[7])\n let p4 = String(format: \"%02x%02x\", bytes[8], bytes[9])\n let p5 = String(format: \"%02x%02x%02x%02x%02x%02x\", bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15])\n \n let result = \"\\(p1)-\\(p2)-\\(p3)-\\(p4)-\\(p5)\"\n \n // Generated packet ID for tracking\n \n return result\n }\n \n // Track packets that need ACKs\n private func trackPacketForAck(_ packet: BitchatPacket) {\n let packetID = generatePacketID(for: packet)\n \n // Debug: log packet details\n _ = packet.senderID.prefix(4).hexEncodedString()\n _ = packet.recipientID?.prefix(4).hexEncodedString() ?? \"nil\"\n // Track packet for ACK\n \n collectionsQueue.sync(flags: .barrier) {\n pendingAcks[packetID] = (packet: packet, timestamp: Date(), retries: 0)\n }\n \n // Schedule timeout check with initial delay (using exponential backoff starting at 1s)\n let initialDelay = calculateExponentialBackoff(retry: 1) // 1 second initial delay\n DispatchQueue.main.asyncAfter(deadline: .now() + initialDelay) { [weak self] in\n self?.checkAckTimeout(for: packetID)\n }\n }\n \n // Check for ACK timeout and retry if needed\n private func checkAckTimeout(for packetID: String) {\n // Check if already acknowledged\n acknowledgedPacketsLock.lock()\n let isAcknowledged = acknowledgedPackets.contains(packetID)\n acknowledgedPacketsLock.unlock()\n \n if isAcknowledged {\n // Already acknowledged, remove from pending and don't retry\n _ = collectionsQueue.sync(flags: .barrier) {\n pendingAcks.removeValue(forKey: packetID)\n }\n SecureLogger.log(\"Packet \\(packetID) already acknowledged, cancelling retries\", \n category: SecureLogger.session, level: .debug)\n return\n }\n \n collectionsQueue.sync(flags: .barrier) { [weak self] in\n guard let self = self,\n let pending = self.pendingAcks[packetID] else { return }\n \n // Check if this is a handshake packet and we already have an established session\n if pending.packet.type == MessageType.noiseHandshakeInit.rawValue ||\n pending.packet.type == MessageType.noiseHandshakeResp.rawValue {\n // Extract peer ID from packet\n let peerID = pending.packet.recipientID?.hexEncodedString() ?? \"\"\n if !peerID.isEmpty && self.noiseService.hasEstablishedSession(with: peerID) {\n // We have an established session, don't retry handshake packets\n SecureLogger.log(\"Not retrying handshake packet \\(packetID) - session already established with \\(peerID)\", \n category: SecureLogger.handshake, level: .info)\n self.pendingAcks.removeValue(forKey: packetID)\n return\n }\n }\n \n if pending.retries < self.maxAckRetries {\n // Retry sending the packet\n SecureLogger.log(\"ACK timeout for packet \\(packetID), retrying (attempt \\(pending.retries + 1))\", \n category: SecureLogger.session, level: .warning)\n \n self.pendingAcks[packetID] = (packet: pending.packet, \n timestamp: Date(), \n retries: pending.retries + 1)\n \n // Resend the packet\n SecureLogger.log(\"Resending packet due to ACK timeout (retry \\(pending.retries + 1))\", \n category: SecureLogger.session, level: .debug)\n DispatchQueue.main.async {\n self.broadcastPacket(pending.packet)\n }\n \n // Schedule next timeout check with exponential backoff\n let backoffDelay = self.calculateExponentialBackoff(retry: pending.retries + 1)\n DispatchQueue.main.asyncAfter(deadline: .now() + backoffDelay) {\n self.checkAckTimeout(for: packetID)\n }\n } else {\n // Max retries reached, give up\n SecureLogger.log(\"Max ACK retries reached for packet \\(packetID), giving up\", \n category: SecureLogger.session, level: .error)\n self.pendingAcks.removeValue(forKey: packetID)\n \n // Could notify upper layer about delivery failure here\n }\n }\n }\n \n // Check all pending ACKs for timeouts (called by timer)\n private func checkAckTimeouts() {\n let now = Date()\n var timedOutPackets: [String] = []\n \n collectionsQueue.sync {\n for (packetID, pending) in pendingAcks {\n if now.timeIntervalSince(pending.timestamp) > ackTimeout {\n timedOutPackets.append(packetID)\n }\n }\n }\n \n // Process timeouts outside the sync block\n for packetID in timedOutPackets {\n checkAckTimeout(for: packetID)\n }\n }\n \n // Update RSSI for all connected peripherals\n private func updateAllPeripheralRSSI() {\n \n // Read RSSI for all connected peripherals\n for (_, peripheral) in connectedPeripherals {\n if peripheral.state == .connected {\n peripheral.readRSSI()\n }\n }\n }\n \n // Check peer availability based on last heard time\n private func checkPeerAvailability() {\n let now = Date()\n var stateChanges: [(peerID: String, available: Bool)] = []\n \n collectionsQueue.sync(flags: .barrier) {\n // Check all active peers\n for peerID in activePeers {\n let lastHeard = lastHeardFromPeer[peerID] ?? Date.distantPast\n let timeSinceLastHeard = now.timeIntervalSince(lastHeard)\n let wasAvailable = peerAvailabilityState[peerID] ?? true\n \n // Check connection state\n let connectionState = peerConnectionStates[peerID] ?? .disconnected\n let hasConnection = connectionState == .connected || connectionState == .authenticating || connectionState == .authenticated\n \n // Peer is available if:\n // 1. We have an active connection (regardless of last heard time), OR\n // 2. We're authenticated and heard from them within timeout period\n let isAvailable = hasConnection || \n (connectionState == .authenticated && timeSinceLastHeard < peerAvailabilityTimeout)\n \n if wasAvailable != isAvailable {\n peerAvailabilityState[peerID] = isAvailable\n stateChanges.append((peerID: peerID, available: isAvailable))\n }\n }\n \n // Remove availability state for peers no longer active\n let inactivePeers = peerAvailabilityState.keys.filter { !activePeers.contains($0) }\n for peerID in inactivePeers {\n peerAvailabilityState.removeValue(forKey: peerID)\n }\n }\n \n // Notify about availability changes\n for change in stateChanges {\n SecureLogger.log(\"Peer \\(change.peerID) availability changed to: \\(change.available)\", \n category: SecureLogger.session, level: .info)\n \n // Notify delegate about availability change\n DispatchQueue.main.async { [weak self] in\n self?.delegate?.peerAvailabilityChanged(change.peerID, available: change.available)\n }\n }\n }\n \n // Update peer availability when we hear from them\n private func updatePeerAvailability(_ peerID: String) {\n collectionsQueue.sync(flags: .barrier) {\n lastHeardFromPeer[peerID] = Date()\n \n // If peer wasn't available, mark as available now\n if peerAvailabilityState[peerID] != true {\n peerAvailabilityState[peerID] = true\n \n SecureLogger.log(\"Peer \\(peerID) marked as available after hearing from them\", \n category: SecureLogger.session, level: .info)\n \n DispatchQueue.main.async { [weak self] in\n self?.delegate?.peerAvailabilityChanged(peerID, available: true)\n }\n }\n }\n }\n \n // Check if a peer is currently available\n func isPeerAvailable(_ peerID: String) -> Bool {\n return collectionsQueue.sync {\n return peerAvailabilityState[peerID] ?? false\n }\n }\n \n private func sendNoiseIdentityAnnounce(to specificPeerID: String? = nil) {\n // Rate limit identity announcements\n let now = Date()\n \n // If targeting a specific peer, check rate limit\n if let peerID = specificPeerID {\n if let lastTime = lastIdentityAnnounceTimes[peerID],\n now.timeIntervalSince(lastTime) < identityAnnounceMinInterval {\n // Too soon, skip this announcement\n return\n }\n lastIdentityAnnounceTimes[peerID] = now\n } else {\n // Broadcasting to all - check global rate limit\n if let lastTime = lastIdentityAnnounceTimes[\"*broadcast*\"],\n now.timeIntervalSince(lastTime) < identityAnnounceMinInterval {\n return\n }\n lastIdentityAnnounceTimes[\"*broadcast*\"] = now\n }\n \n // Get our Noise static public key and signing public key\n let staticKey = noiseService.getStaticPublicKeyData()\n let signingKey = noiseService.getSigningPublicKeyData()\n \n // Get nickname from delegate\n let nickname = (delegate as? ChatViewModel)?.nickname ?? \"Anonymous\"\n \n // Create the binding data to sign (peerID + publicKey + timestamp)\n let timestampData = String(Int64(now.timeIntervalSince1970 * 1000)).data(using: .utf8)!\n let bindingData = myPeerID.data(using: .utf8)! + staticKey + timestampData\n \n // Sign the binding with our Ed25519 signing key\n let signature = noiseService.signData(bindingData) ?? Data()\n \n // Create the identity announcement\n let announcement = NoiseIdentityAnnouncement(\n peerID: myPeerID,\n publicKey: staticKey,\n signingPublicKey: signingKey,\n nickname: nickname,\n timestamp: now,\n previousPeerID: previousPeerID,\n signature: signature\n )\n \n // Encode the announcement\n let announcementData = announcement.toBinaryData()\n \n let packet = BitchatPacket(\n type: MessageType.noiseIdentityAnnounce.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: specificPeerID.flatMap { Data(hexString: $0) }, // Targeted or broadcast\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: announcementData,\n signature: nil,\n ttl: adaptiveTTL )\n \n if let targetPeer = specificPeerID {\n SecureLogger.log(\"Sending targeted identity announce to \\(targetPeer)\", \n category: SecureLogger.noise, level: .info)\n \n // Try direct delivery for targeted announces\n if !sendDirectToRecipient(packet, recipientPeerID: targetPeer) {\n // Fall back to selective relay if direct delivery fails\n SecureLogger.log(\"Recipient \\(targetPeer) not directly connected for identity announce, using relay\", \n category: SecureLogger.session, level: .info)\n sendViaSelectiveRelay(packet, recipientPeerID: targetPeer)\n }\n } else {\n SecureLogger.log(\"Broadcasting identity announce to all peers\", \n category: SecureLogger.noise, level: .info)\n broadcastPacket(packet)\n }\n }\n \n // Removed sendPacket method - all packets should use broadcastPacket to ensure mesh delivery\n \n // Send private message using Noise Protocol\n private func sendPrivateMessageViaNoise(_ content: String, to recipientPeerID: String, recipientNickname: String, messageID: String? = nil) {\n SecureLogger.log(\"sendPrivateMessageViaNoise called - content: '\\(content.prefix(50))...', to: \\(recipientPeerID), messageID: \\(messageID ?? \"nil\")\", \n category: SecureLogger.noise, level: .info)\n \n // Use per-peer encryption queue to prevent nonce desynchronization\n let encryptionQueue = getEncryptionQueue(for: recipientPeerID)\n \n encryptionQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Use noiseService directly\n \n // Check if we have a Noise session with this peer\n let hasSession = self.noiseService.hasEstablishedSession(with: recipientPeerID)\n \n // Check if session is stale (no successful communication for a while)\n var sessionIsStale = false\n if hasSession {\n let lastSuccess = lastSuccessfulMessageTime[recipientPeerID] ?? Date.distantPast\n let sessionAge = Date().timeIntervalSince(lastSuccess)\n // Increase session validity to 24 hours - sessions should persist across temporary disconnects\n if sessionAge > 86400.0 { // More than 24 hours since last successful message\n sessionIsStale = true\n SecureLogger.log(\"Session with \\(recipientPeerID) is stale (last success: \\(Int(sessionAge))s ago), will re-establish\", category: SecureLogger.noise, level: .info)\n }\n }\n \n if !hasSession || sessionIsStale {\n if sessionIsStale {\n // Clear stale session first\n cleanupPeerCryptoState(recipientPeerID)\n }\n \n // Update state to handshakeQueued\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[recipientPeerID] = .handshakeQueued\n }\n \n SecureLogger.log(\"No valid Noise session with \\(recipientPeerID), initiating handshake (lazy mode)\", category: SecureLogger.noise, level: .info)\n \n // Notify UI that we're establishing encryption\n DispatchQueue.main.async { [weak self] in\n if let chatVM = self?.delegate as? ChatViewModel {\n // This will update the UI to show \"establishing encryption\" state\n chatVM.updateEncryptionStatusForPeer(recipientPeerID)\n }\n }\n \n // Queue message for sending after handshake completes\n collectionsQueue.sync(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n if self.pendingPrivateMessages[recipientPeerID] == nil {\n self.pendingPrivateMessages[recipientPeerID] = []\n }\n self.pendingPrivateMessages[recipientPeerID]?.append((content, recipientNickname, messageID ?? UUID().uuidString))\n let count = self.pendingPrivateMessages[recipientPeerID]?.count ?? 0\n SecureLogger.log(\"Queued private message for \\(recipientPeerID), \\(count) messages pending\", category: SecureLogger.noise, level: .info)\n }\n \n // Send handshake request to notify recipient of pending messages\n sendHandshakeRequest(to: recipientPeerID, pendingCount: UInt8(pendingPrivateMessages[recipientPeerID]?.count ?? 1))\n \n // Apply tie-breaker logic for handshake initiation\n if myPeerID < recipientPeerID {\n // We have lower ID, initiate handshake\n initiateNoiseHandshake(with: recipientPeerID)\n } else {\n // We have higher ID, send targeted identity announce to prompt them to initiate\n sendNoiseIdentityAnnounce(to: recipientPeerID)\n }\n \n return\n }\n \n // Use provided message ID or generate a new one\n let msgID = messageID ?? UUID().uuidString\n \n // Check if we're already processing this message\n let sendKey = \"\\(msgID)-\\(recipientPeerID)\"\n let alreadySending = self.collectionsQueue.sync(flags: .barrier) {\n if self.recentlySentMessages.contains(sendKey) {\n return true\n }\n self.recentlySentMessages.insert(sendKey)\n // Clean up old entries after 10 seconds\n DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) { [weak self] in\n self?.collectionsQueue.sync(flags: .barrier) {\n _ = self?.recentlySentMessages.remove(sendKey)\n }\n }\n return false\n }\n \n if alreadySending {\n return\n }\n \n \n // Get sender nickname from delegate\n let nickname = self.delegate as? ChatViewModel\n let senderNick = nickname?.nickname ?? self.myPeerID\n \n // Create the inner message\n let message = BitchatMessage(\n id: msgID,\n sender: senderNick,\n content: content,\n timestamp: Date(),\n isRelay: false,\n isPrivate: true,\n recipientNickname: recipientNickname,\n senderPeerID: myPeerID\n )\n \n // Use binary payload format to match the receiver's expectations\n guard let messageData = message.toBinaryPayload() else { \n return \n }\n \n // Create inner packet\n let innerPacket = BitchatPacket(\n type: MessageType.message.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: recipientPeerID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: messageData,\n signature: nil,\n ttl: self.adaptiveTTL // Inner packet needs valid TTL for processing after decryption\n )\n \n guard let innerData = innerPacket.toBinaryData() else { return }\n \n do {\n // Encrypt with Noise\n SecureLogger.log(\"Encrypting private message \\(msgID) for \\(recipientPeerID)\", category: SecureLogger.encryption, level: .debug)\n let encryptedData = try noiseService.encrypt(innerData, for: recipientPeerID)\n SecureLogger.log(\"Successfully encrypted message, size: \\(encryptedData.count)\", category: SecureLogger.encryption, level: .debug)\n \n // Update last successful message time\n lastSuccessfulMessageTime[recipientPeerID] = Date()\n \n // Send as Noise encrypted message\n let outerPacket = BitchatPacket(\n type: MessageType.noiseEncrypted.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: recipientPeerID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: encryptedData,\n signature: nil,\n ttl: adaptiveTTL )\n \n SecureLogger.log(\"Sending encrypted private message \\(msgID) to \\(recipientPeerID)\", category: SecureLogger.session, level: .info)\n \n // Track packet for ACK\n trackPacketForAck(outerPacket)\n \n // Try direct delivery first\n if !sendDirectToRecipient(outerPacket, recipientPeerID: recipientPeerID) {\n // Recipient not directly connected, use selective relay\n SecureLogger.log(\"Recipient \\(recipientPeerID) not directly connected, using relay strategy\", \n category: SecureLogger.session, level: .info)\n sendViaSelectiveRelay(outerPacket, recipientPeerID: recipientPeerID)\n }\n } catch {\n // Failed to encrypt message\n SecureLogger.log(\"Failed to encrypt private message \\(msgID) for \\(recipientPeerID): \\(error)\", category: SecureLogger.encryption, level: .error)\n }\n } // End of encryptionQueue.async\n }\n \n // MARK: - Targeted Message Delivery\n \n private func sendDirectToRecipient(_ packet: BitchatPacket, recipientPeerID: String) -> Bool {\n // Try to send directly to the recipient if they're connected\n if let peripheral = connectedPeripherals[recipientPeerID],\n let characteristic = peripheralCharacteristics[peripheral],\n peripheral.state == .connected {\n \n guard let data = packet.toBinaryData() else { return false }\n \n // Send only to the intended recipient\n writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: recipientPeerID)\n SecureLogger.log(\"Sent private message directly to \\(recipientPeerID)\", category: SecureLogger.session, level: .info)\n return true\n }\n \n // Check if recipient is connected as a central (we're peripheral)\n if !subscribedCentrals.isEmpty {\n // We can't target specific centrals, so return false to trigger relay\n return false\n }\n \n return false\n }\n \n private func sendHandshakeRequest(to targetPeerID: String, pendingCount: UInt8) {\n // Create handshake request\n let request = HandshakeRequest(requesterID: myPeerID,\n requesterNickname: (delegate as? ChatViewModel)?.nickname ?? myPeerID,\n targetID: targetPeerID,\n pendingMessageCount: pendingCount)\n \n let requestData = request.toBinaryData()\n \n // Create packet for handshake request\n let packet = BitchatPacket(type: MessageType.handshakeRequest.rawValue,\n ttl: 6,\n senderID: myPeerID,\n payload: requestData)\n \n // Try direct delivery first\n if sendDirectToRecipient(packet, recipientPeerID: targetPeerID) {\n SecureLogger.log(\"Sent handshake request directly to \\(targetPeerID)\", category: SecureLogger.noise, level: .info)\n } else {\n // Use selective relay if direct delivery fails\n sendViaSelectiveRelay(packet, recipientPeerID: targetPeerID)\n SecureLogger.log(\"Sent handshake request via relay to \\(targetPeerID)\", category: SecureLogger.noise, level: .info)\n }\n }\n \n private func selectBestRelayPeers(excluding: String, maxPeers: Int = 3) -> [String] {\n // Select peers with best RSSI for relay, excluding the target recipient\n var candidates: [(peerID: String, rssi: Int)] = []\n \n for (peerID, _) in connectedPeripherals {\n if peerID != excluding && peerID != myPeerID {\n let rssiValue = peerRSSI[peerID]?.intValue ?? -80\n candidates.append((peerID: peerID, rssi: rssiValue))\n }\n }\n \n // Sort by RSSI (strongest first) and take top N\n candidates.sort { $0.rssi > $1.rssi }\n return candidates.prefix(maxPeers).map { $0.peerID }\n }\n \n private func sendViaSelectiveRelay(_ packet: BitchatPacket, recipientPeerID: String) {\n // Select best relay candidates\n let relayPeers = selectBestRelayPeers(excluding: recipientPeerID)\n \n if relayPeers.isEmpty {\n // No relay candidates, fall back to broadcast\n SecureLogger.log(\"No relay candidates for private message to \\(recipientPeerID), using broadcast\", \n category: SecureLogger.session, level: .warning)\n broadcastPacket(packet)\n return\n }\n \n // Limit TTL for relay\n var relayPacket = packet\n relayPacket.ttl = min(packet.ttl, 2) // Max 2 hops for private message relay\n \n guard let data = relayPacket.toBinaryData() else { return }\n \n // Send to selected relay peers\n var sentCount = 0\n for relayPeerID in relayPeers {\n if let peripheral = connectedPeripherals[relayPeerID],\n let characteristic = peripheralCharacteristics[peripheral],\n peripheral.state == .connected {\n writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: relayPeerID)\n sentCount += 1\n }\n }\n \n SecureLogger.log(\"Sent private message to \\(sentCount) relay peers (targeting \\(recipientPeerID))\", \n category: SecureLogger.session, level: .info)\n \n // If no relays worked, fall back to broadcast\n if sentCount == 0 {\n SecureLogger.log(\"Failed to send to relay peers, falling back to broadcast\", \n category: SecureLogger.session, level: .warning)\n broadcastPacket(packet)\n }\n }\n \n // MARK: - Connection Pool Management\n \n private func findLeastRecentlyUsedPeripheral() -> String? {\n var lruPeripheralID: String?\n var oldestActivityTime = Date()\n \n for (peripheralID, peripheral) in connectionPool {\n // Only consider connected peripherals\n guard peripheral.state == .connected else { continue }\n \n // Skip if this peripheral has an active peer connection\n if let peerID = peerIDByPeripheralID[peripheralID],\n activePeers.contains(peerID) {\n continue\n }\n \n // Find the least recently used peripheral based on last activity\n if let lastActivity = lastActivityByPeripheralID[peripheralID],\n lastActivity < oldestActivityTime {\n oldestActivityTime = lastActivity\n lruPeripheralID = peripheralID\n } else if lastActivityByPeripheralID[peripheralID] == nil {\n // If no activity recorded, it's a candidate for removal\n lruPeripheralID = peripheralID\n break\n }\n }\n \n return lruPeripheralID\n }\n \n // Track activity for peripherals\n private func updatePeripheralActivity(_ peripheralID: String) {\n lastActivityByPeripheralID[peripheralID] = Date()\n }\n}\n"], ["/bitchat/bitchat/Views/ContentView.swift", "//\n// ContentView.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport SwiftUI\n\n// MARK: - Supporting Types\n\n// Pre-computed peer data for performance\nstruct PeerDisplayData: Identifiable {\n let id: String\n let displayName: String\n let rssi: Int?\n let isFavorite: Bool\n let isMe: Bool\n let hasUnreadMessages: Bool\n let encryptionStatus: EncryptionStatus\n}\n\n// MARK: - Lazy Link Preview\n\n// Lazy loading wrapper for link previews\nstruct LazyLinkPreviewView: View {\n let url: URL\n let title: String?\n @State private var isVisible = false\n \n var body: some View {\n GeometryReader { geometry in\n if isVisible {\n LinkPreviewView(url: url, title: title)\n } else {\n // Placeholder while not visible\n RoundedRectangle(cornerRadius: 10)\n .fill(Color.gray.opacity(0.1))\n .frame(height: 80)\n .onAppear {\n // Only load when view appears on screen\n isVisible = true\n }\n }\n }\n .frame(height: 80)\n }\n}\n\n// MARK: - Main Content View\n\nstruct ContentView: View {\n // MARK: - Properties\n \n @EnvironmentObject var viewModel: ChatViewModel\n @State private var messageText = \"\"\n @State private var textFieldSelection: NSRange? = nil\n @FocusState private var isTextFieldFocused: Bool\n @Environment(\\.colorScheme) var colorScheme\n @State private var showPeerList = false\n @State private var showSidebar = false\n @State private var sidebarDragOffset: CGFloat = 0\n @State private var showAppInfo = false\n @State private var showCommandSuggestions = false\n @State private var commandSuggestions: [String] = []\n @State private var backSwipeOffset: CGFloat = 0\n @State private var showPrivateChat = false\n @State private var showMessageActions = false\n @State private var selectedMessageSender: String?\n @State private var selectedMessageSenderID: String?\n @FocusState private var isNicknameFieldFocused: Bool\n @State private var lastScrollTime: Date = .distantPast\n @State private var scrollThrottleTimer: Timer?\n @State private var autocompleteDebounceTimer: Timer?\n \n // MARK: - Computed Properties\n \n private var backgroundColor: Color {\n colorScheme == .dark ? Color.black : Color.white\n }\n \n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n private var secondaryTextColor: Color {\n colorScheme == .dark ? Color.green.opacity(0.8) : Color(red: 0, green: 0.5, blue: 0).opacity(0.8)\n }\n \n // MARK: - Body\n \n var body: some View {\n GeometryReader { geometry in\n ZStack {\n // Base layer - Main public chat (always visible)\n mainChatView\n \n // Private chat slide-over\n if viewModel.selectedPrivateChatPeer != nil {\n privateChatView\n .frame(width: geometry.size.width)\n .background(backgroundColor)\n .transition(.asymmetric(\n insertion: .move(edge: .trailing),\n removal: .move(edge: .trailing)\n ))\n .offset(x: showPrivateChat ? -1 : max(0, geometry.size.width))\n .offset(x: backSwipeOffset.isNaN ? 0 : backSwipeOffset)\n .gesture(\n DragGesture()\n .onChanged { value in\n if value.translation.width > 0 && !value.translation.width.isNaN {\n let maxWidth = max(0, geometry.size.width)\n backSwipeOffset = min(value.translation.width, maxWidth.isNaN ? 0 : maxWidth)\n }\n }\n .onEnded { value in\n let translation = value.translation.width.isNaN ? 0 : value.translation.width\n let velocity = value.velocity.width.isNaN ? 0 : value.velocity.width\n if translation > 50 || (translation > 30 && velocity > 300) {\n withAnimation(.easeOut(duration: 0.2)) {\n showPrivateChat = false\n backSwipeOffset = 0\n viewModel.endPrivateChat()\n }\n } else {\n withAnimation(.easeOut(duration: 0.15)) {\n backSwipeOffset = 0\n }\n }\n }\n )\n }\n \n // Sidebar overlay\n HStack(spacing: 0) {\n // Tap to dismiss area\n Color.clear\n .contentShape(Rectangle())\n .onTapGesture {\n withAnimation(.easeInOut(duration: 0.2)) {\n showSidebar = false\n sidebarDragOffset = 0\n }\n }\n \n // Only render sidebar content when it's visible or animating\n if showSidebar || sidebarDragOffset != 0 {\n sidebarView\n #if os(macOS)\n .frame(width: min(300, max(0, geometry.size.width.isNaN ? 300 : geometry.size.width) * 0.4))\n #else\n .frame(width: max(0, geometry.size.width.isNaN ? 300 : geometry.size.width) * 0.7)\n #endif\n .transition(.move(edge: .trailing))\n } else {\n // Empty placeholder when hidden\n Color.clear\n #if os(macOS)\n .frame(width: min(300, max(0, geometry.size.width.isNaN ? 300 : geometry.size.width) * 0.4))\n #else\n .frame(width: max(0, geometry.size.width.isNaN ? 300 : geometry.size.width) * 0.7)\n #endif\n }\n }\n .offset(x: {\n let dragOffset = sidebarDragOffset.isNaN ? 0 : sidebarDragOffset\n let width = geometry.size.width.isNaN ? 0 : max(0, geometry.size.width)\n return showSidebar ? -dragOffset : width - dragOffset\n }())\n .animation(.easeInOut(duration: 0.25), value: showSidebar)\n }\n }\n #if os(macOS)\n .frame(minWidth: 600, minHeight: 400)\n #endif\n .onChange(of: viewModel.selectedPrivateChatPeer) { newValue in\n withAnimation(.easeInOut(duration: 0.2)) {\n showPrivateChat = newValue != nil\n }\n }\n .sheet(isPresented: $showAppInfo) {\n AppInfoView()\n }\n .sheet(isPresented: Binding(\n get: { viewModel.showingFingerprintFor != nil },\n set: { _ in viewModel.showingFingerprintFor = nil }\n )) {\n if let peerID = viewModel.showingFingerprintFor {\n FingerprintView(viewModel: viewModel, peerID: peerID)\n }\n }\n .confirmationDialog(\n selectedMessageSender.map { \"@\\($0)\" } ?? \"Actions\",\n isPresented: $showMessageActions,\n titleVisibility: .visible\n ) {\n Button(\"private message\") {\n if let peerID = selectedMessageSenderID {\n viewModel.startPrivateChat(with: peerID)\n withAnimation(.easeInOut(duration: 0.2)) {\n showSidebar = false\n sidebarDragOffset = 0\n }\n }\n }\n \n Button(\"hug\") {\n if let sender = selectedMessageSender {\n viewModel.sendMessage(\"/hug @\\(sender)\")\n }\n }\n \n Button(\"slap\") {\n if let sender = selectedMessageSender {\n viewModel.sendMessage(\"/slap @\\(sender)\")\n }\n }\n \n Button(\"BLOCK\", role: .destructive) {\n if let sender = selectedMessageSender {\n viewModel.sendMessage(\"/block \\(sender)\")\n }\n }\n \n Button(\"cancel\", role: .cancel) {}\n }\n .onDisappear {\n // Clean up timers\n scrollThrottleTimer?.invalidate()\n autocompleteDebounceTimer?.invalidate()\n }\n }\n \n // MARK: - Message List View\n \n private func messagesView(privatePeer: String?) -> some View {\n ScrollViewReader { proxy in\n ScrollView {\n VStack(alignment: .leading, spacing: 0) {\n // Extract messages based on context (private or public chat)\n let messages: [BitchatMessage] = {\n if let privatePeer = privatePeer {\n let msgs = viewModel.getPrivateChatMessages(for: privatePeer)\n return msgs\n } else {\n return viewModel.messages\n }\n }()\n \n // Implement windowing - show last 100 messages for performance\n let windowedMessages = messages.suffix(100)\n \n ForEach(windowedMessages, id: \\.id) { message in\n VStack(alignment: .leading, spacing: 0) {\n // Check if current user is mentioned\n let _ = message.mentions?.contains(viewModel.nickname) ?? false\n \n if message.sender == \"system\" {\n // System messages\n Text(viewModel.formatMessageAsText(message, colorScheme: colorScheme))\n .textSelection(.enabled)\n .fixedSize(horizontal: false, vertical: true)\n .frame(maxWidth: .infinity, alignment: .leading)\n } else {\n // Regular messages with natural text wrapping\n VStack(alignment: .leading, spacing: 0) {\n HStack(alignment: .top, spacing: 0) {\n // Single text view for natural wrapping\n Text(viewModel.formatMessageAsText(message, colorScheme: colorScheme))\n .textSelection(.enabled)\n .fixedSize(horizontal: false, vertical: true)\n .frame(maxWidth: .infinity, alignment: .leading)\n \n // Delivery status indicator for private messages\n if message.isPrivate && message.sender == viewModel.nickname,\n let status = message.deliveryStatus {\n DeliveryStatusView(status: status, colorScheme: colorScheme)\n .padding(.leading, 4)\n }\n }\n \n // Check for plain URLs\n let urls = message.content.extractURLs()\n if !urls.isEmpty {\n ForEach(urls.prefix(3).indices, id: \\.self) { index in\n let urlInfo = urls[index]\n LazyLinkPreviewView(url: urlInfo.url, title: nil)\n .padding(.top, 3)\n .padding(.horizontal, 1)\n .id(\"\\(message.id)-\\(urlInfo.url.absoluteString)\")\n }\n }\n }\n }\n }\n .id(message.id)\n .contentShape(Rectangle())\n .onTapGesture {\n // Only show actions for messages from other users (not system or self)\n if message.sender != \"system\" && message.sender != viewModel.nickname {\n selectedMessageSender = message.sender\n selectedMessageSenderID = message.senderPeerID\n showMessageActions = true\n }\n }\n .padding(.horizontal, 12)\n .padding(.vertical, 2)\n }\n }\n .padding(.vertical, 4)\n }\n .background(backgroundColor)\n .onTapGesture(count: 3) {\n // Triple-tap to clear current chat\n viewModel.sendMessage(\"/clear\")\n }\n .onChange(of: viewModel.messages.count) { _ in\n if privatePeer == nil && !viewModel.messages.isEmpty {\n // Throttle scroll animations to prevent excessive UI updates\n let now = Date()\n if now.timeIntervalSince(lastScrollTime) > 0.5 {\n // Immediate scroll if enough time has passed\n lastScrollTime = now\n proxy.scrollTo(viewModel.messages.suffix(100).last?.id, anchor: .bottom)\n } else {\n // Schedule a delayed scroll\n scrollThrottleTimer?.invalidate()\n scrollThrottleTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in\n lastScrollTime = Date()\n proxy.scrollTo(viewModel.messages.suffix(100).last?.id, anchor: .bottom)\n }\n }\n }\n }\n .onChange(of: viewModel.privateChats) { _ in\n if let peerID = privatePeer,\n let messages = viewModel.privateChats[peerID],\n !messages.isEmpty {\n // Same throttling for private chats\n let now = Date()\n if now.timeIntervalSince(lastScrollTime) > 0.5 {\n lastScrollTime = now\n proxy.scrollTo(messages.suffix(100).last?.id, anchor: .bottom)\n } else {\n scrollThrottleTimer?.invalidate()\n scrollThrottleTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in\n lastScrollTime = Date()\n proxy.scrollTo(messages.suffix(100).last?.id, anchor: .bottom)\n }\n }\n }\n }\n .onAppear {\n // Also check when view appears\n if let peerID = privatePeer {\n // Try multiple times to ensure read receipts are sent\n viewModel.markPrivateMessagesAsRead(from: peerID)\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {\n viewModel.markPrivateMessagesAsRead(from: peerID)\n }\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {\n viewModel.markPrivateMessagesAsRead(from: peerID)\n }\n }\n }\n }\n }\n \n // MARK: - Input View\n \n private var inputView: some View {\n VStack(spacing: 0) {\n // @mentions autocomplete\n if viewModel.showAutocomplete && !viewModel.autocompleteSuggestions.isEmpty {\n VStack(alignment: .leading, spacing: 0) {\n ForEach(viewModel.autocompleteSuggestions, id: \\.self) { suggestion in\n Button(action: {\n _ = viewModel.completeNickname(suggestion, in: &messageText)\n }) {\n HStack {\n Text(\"@\\(suggestion)\")\n .font(.system(size: 11, design: .monospaced))\n .foregroundColor(textColor)\n .fontWeight(.medium)\n Spacer()\n }\n .padding(.horizontal, 12)\n .padding(.vertical, 3)\n .frame(maxWidth: .infinity, alignment: .leading)\n }\n .buttonStyle(.plain)\n .background(Color.gray.opacity(0.1))\n }\n }\n .background(backgroundColor)\n .overlay(\n RoundedRectangle(cornerRadius: 4)\n .stroke(secondaryTextColor.opacity(0.3), lineWidth: 1)\n )\n .padding(.horizontal, 12)\n }\n \n // Command suggestions\n if showCommandSuggestions && !commandSuggestions.isEmpty {\n VStack(alignment: .leading, spacing: 0) {\n // Define commands with aliases and syntax\n let commandInfo: [(commands: [String], syntax: String?, description: String)] = [\n ([\"/block\"], \"[nickname]\", \"block or list blocked peers\"),\n ([\"/clear\"], nil, \"clear chat messages\"),\n ([\"/hug\"], \"\", \"send someone a warm hug\"),\n ([\"/m\", \"/msg\"], \" [message]\", \"send private message\"),\n ([\"/slap\"], \"\", \"slap someone with a trout\"),\n ([\"/unblock\"], \"\", \"unblock a peer\"),\n ([\"/w\"], nil, \"see who's online\")\n ]\n \n // Build the display\n let allCommands = commandInfo\n \n // Show matching commands\n ForEach(commandSuggestions, id: \\.self) { command in\n // Find the command info for this suggestion\n if let info = allCommands.first(where: { $0.commands.contains(command) }) {\n Button(action: {\n // Replace current text with selected command\n messageText = command + \" \"\n showCommandSuggestions = false\n commandSuggestions = []\n }) {\n HStack {\n // Show all aliases together\n Text(info.commands.joined(separator: \", \"))\n .font(.system(size: 11, design: .monospaced))\n .foregroundColor(textColor)\n .fontWeight(.medium)\n \n // Show syntax if any\n if let syntax = info.syntax {\n Text(syntax)\n .font(.system(size: 10, design: .monospaced))\n .foregroundColor(secondaryTextColor.opacity(0.8))\n }\n \n Spacer()\n \n // Show description\n Text(info.description)\n .font(.system(size: 10, design: .monospaced))\n .foregroundColor(secondaryTextColor)\n }\n .padding(.horizontal, 12)\n .padding(.vertical, 3)\n .frame(maxWidth: .infinity, alignment: .leading)\n }\n .buttonStyle(.plain)\n .background(Color.gray.opacity(0.1))\n }\n }\n }\n .background(backgroundColor)\n .overlay(\n RoundedRectangle(cornerRadius: 4)\n .stroke(secondaryTextColor.opacity(0.3), lineWidth: 1)\n )\n .padding(.horizontal, 12)\n }\n \n HStack(alignment: .center, spacing: 4) {\n TextField(\"type a message...\", text: $messageText)\n .textFieldStyle(.plain)\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(textColor)\n .focused($isTextFieldFocused)\n .padding(.leading, 12)\n .autocorrectionDisabled(true)\n #if os(iOS)\n .textInputAutocapitalization(.never)\n #endif\n .onChange(of: messageText) { newValue in\n // Cancel previous debounce timer\n autocompleteDebounceTimer?.invalidate()\n \n // Debounce autocomplete updates to reduce calls during rapid typing\n autocompleteDebounceTimer = Timer.scheduledTimer(withTimeInterval: 0.15, repeats: false) { _ in\n // Get cursor position (approximate - end of text for now)\n let cursorPosition = newValue.count\n viewModel.updateAutocomplete(for: newValue, cursorPosition: cursorPosition)\n }\n \n // Check for command autocomplete (instant, no debounce needed)\n if newValue.hasPrefix(\"/\") && newValue.count >= 1 {\n // Build context-aware command list\n let commandDescriptions = [\n (\"/block\", \"block or list blocked peers\"),\n (\"/clear\", \"clear chat messages\"),\n (\"/hug\", \"send someone a warm hug\"),\n (\"/m\", \"send private message\"),\n (\"/slap\", \"slap someone with a trout\"),\n (\"/unblock\", \"unblock a peer\"),\n (\"/w\", \"see who's online\")\n ]\n \n let input = newValue.lowercased()\n \n // Map of aliases to primary commands\n let aliases: [String: String] = [\n \"/join\": \"/j\",\n \"/msg\": \"/m\"\n ]\n \n // Filter commands, but convert aliases to primary\n commandSuggestions = commandDescriptions\n .filter { $0.0.starts(with: input) }\n .map { $0.0 }\n \n // Also check if input matches an alias\n for (alias, primary) in aliases {\n if alias.starts(with: input) && !commandSuggestions.contains(primary) {\n if commandDescriptions.contains(where: { $0.0 == primary }) {\n commandSuggestions.append(primary)\n }\n }\n }\n \n // Remove duplicates and sort\n commandSuggestions = Array(Set(commandSuggestions)).sorted()\n showCommandSuggestions = !commandSuggestions.isEmpty\n } else {\n showCommandSuggestions = false\n commandSuggestions = []\n }\n }\n .onSubmit {\n sendMessage()\n }\n \n Button(action: sendMessage) {\n Image(systemName: \"arrow.up.circle.fill\")\n .font(.system(size: 20))\n .foregroundColor(messageText.isEmpty ? Color.gray :\n viewModel.selectedPrivateChatPeer != nil\n ? Color.orange : textColor)\n }\n .buttonStyle(.plain)\n .padding(.trailing, 12)\n .accessibilityLabel(\"Send message\")\n .accessibilityHint(messageText.isEmpty ? \"Enter a message to send\" : \"Double tap to send\")\n }\n .padding(.vertical, 8)\n .background(backgroundColor.opacity(0.95))\n }\n .onAppear {\n // Delay keyboard focus to avoid iOS constraint warnings\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {\n isTextFieldFocused = true\n }\n }\n }\n \n // MARK: - Actions\n \n private func sendMessage() {\n viewModel.sendMessage(messageText)\n messageText = \"\"\n }\n \n // MARK: - Sidebar View\n \n private var sidebarView: some View {\n HStack(spacing: 0) {\n // Grey vertical bar for visual continuity\n Rectangle()\n .fill(Color.gray.opacity(0.3))\n .frame(width: 1)\n \n VStack(alignment: .leading, spacing: 0) {\n // Header - match main toolbar height\n HStack {\n Text(\"NETWORK\")\n .font(.system(size: 16, weight: .bold, design: .monospaced))\n .foregroundColor(textColor)\n Spacer()\n }\n .frame(height: 44) // Match header height\n .padding(.horizontal, 12)\n .background(backgroundColor.opacity(0.95))\n \n Divider()\n \n // Rooms and People list\n ScrollView {\n VStack(alignment: .leading, spacing: 12) {\n // People section\n VStack(alignment: .leading, spacing: 8) {\n // Show appropriate header based on context\n if !viewModel.connectedPeers.isEmpty {\n HStack(spacing: 4) {\n Image(systemName: \"person.2.fill\")\n .font(.system(size: 10))\n .accessibilityHidden(true)\n Text(\"PEOPLE\")\n .font(.system(size: 11, weight: .bold, design: .monospaced))\n }\n .foregroundColor(secondaryTextColor)\n .padding(.horizontal, 12)\n }\n \n if viewModel.connectedPeers.isEmpty {\n Text(\"nobody around...\")\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(secondaryTextColor)\n .padding(.horizontal)\n } else {\n // Extract peer data for display\n let peerNicknames = viewModel.meshService.getPeerNicknames()\n let peerRSSI = viewModel.meshService.getPeerRSSI()\n let myPeerID = viewModel.meshService.myPeerID\n \n // Show all connected peers\n let peersToShow: [String] = viewModel.connectedPeers\n let _ = print(\"ContentView: Showing \\(peersToShow.count) peers: \\(peersToShow.joined(separator: \", \"))\")\n \n // Pre-compute peer data outside ForEach to reduce overhead\n let peerData = peersToShow.map { peerID in\n let rssiValue = peerRSSI[peerID]?.intValue\n if rssiValue == nil {\n print(\"ContentView: No RSSI for peer \\(peerID) in dictionary with \\(peerRSSI.count) entries\")\n print(\"ContentView: peerRSSI keys: \\(peerRSSI.keys.joined(separator: \", \"))\")\n } else {\n print(\"ContentView: RSSI for peer \\(peerID) is \\(rssiValue!)\")\n }\n return PeerDisplayData(\n id: peerID,\n displayName: peerID == myPeerID ? viewModel.nickname : (peerNicknames[peerID] ?? \"anon\\(peerID.prefix(4))\"),\n rssi: rssiValue,\n isFavorite: viewModel.isFavorite(peerID: peerID),\n isMe: peerID == myPeerID,\n hasUnreadMessages: viewModel.unreadPrivateMessages.contains(peerID),\n encryptionStatus: viewModel.getEncryptionStatus(for: peerID)\n )\n }.sorted { (peer1: PeerDisplayData, peer2: PeerDisplayData) in\n // Sort: favorites first, then alphabetically by nickname\n if peer1.isFavorite != peer2.isFavorite {\n return peer1.isFavorite\n }\n return peer1.displayName < peer2.displayName\n }\n \n ForEach(peerData) { peer in\n HStack(spacing: 8) {\n // Signal strength indicator or unread message icon\n if peer.isMe {\n Image(systemName: \"person.fill\")\n .font(.system(size: 10))\n .foregroundColor(textColor)\n .accessibilityLabel(\"You\")\n } else if peer.hasUnreadMessages {\n Image(systemName: \"envelope.fill\")\n .font(.system(size: 12))\n .foregroundColor(Color.orange)\n .accessibilityLabel(\"Unread message from \\(peer.displayName)\")\n } else if let rssi = peer.rssi {\n Image(systemName: \"circle.fill\")\n .font(.system(size: 8))\n .foregroundColor(viewModel.getRSSIColor(rssi: rssi, colorScheme: colorScheme))\n .accessibilityLabel(\"Signal strength: \\(rssi > -60 ? \"excellent\" : rssi > -70 ? \"good\" : rssi > -80 ? \"fair\" : \"poor\")\")\n } else {\n // No RSSI data available\n Image(systemName: \"circle\")\n .font(.system(size: 8))\n .foregroundColor(Color.secondary.opacity(0.5))\n .accessibilityLabel(\"Signal strength: unknown\")\n }\n \n // Peer name\n if peer.isMe {\n HStack {\n Text(peer.displayName + \" (you)\")\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(textColor)\n \n Spacer()\n }\n } else {\n Text(peer.displayName)\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(peerNicknames[peer.id] != nil ? textColor : secondaryTextColor)\n \n // Encryption status icon (after peer name)\n if let icon = peer.encryptionStatus.icon {\n Image(systemName: icon)\n .font(.system(size: 10))\n .foregroundColor(peer.encryptionStatus == .noiseVerified ? Color.green : \n peer.encryptionStatus == .noiseSecured ? textColor :\n peer.encryptionStatus == .noiseHandshaking ? Color.orange :\n Color.red)\n .accessibilityLabel(\"Encryption: \\(peer.encryptionStatus == .noiseVerified ? \"verified\" : peer.encryptionStatus == .noiseSecured ? \"secured\" : peer.encryptionStatus == .noiseHandshaking ? \"establishing\" : \"none\")\")\n }\n \n Spacer()\n \n // Favorite star\n Button(action: {\n viewModel.toggleFavorite(peerID: peer.id)\n }) {\n Image(systemName: peer.isFavorite ? \"star.fill\" : \"star\")\n .font(.system(size: 12))\n .foregroundColor(peer.isFavorite ? Color.yellow : secondaryTextColor)\n }\n .buttonStyle(.plain)\n .accessibilityLabel(peer.isFavorite ? \"Remove \\(peer.displayName) from favorites\" : \"Add \\(peer.displayName) to favorites\")\n }\n }\n .padding(.horizontal)\n .padding(.vertical, 8)\n .contentShape(Rectangle())\n .onTapGesture {\n if !peer.isMe && peerNicknames[peer.id] != nil {\n viewModel.startPrivateChat(with: peer.id)\n withAnimation(.easeInOut(duration: 0.2)) {\n showSidebar = false\n sidebarDragOffset = 0\n }\n }\n }\n .onTapGesture(count: 2) {\n if !peer.isMe {\n // Show fingerprint on double tap\n viewModel.showFingerprint(for: peer.id)\n }\n }\n }\n }\n }\n }\n .padding(.vertical, 8)\n }\n \n Spacer()\n }\n .background(backgroundColor)\n }\n }\n \n // MARK: - View Components\n \n private var mainChatView: some View {\n VStack(spacing: 0) {\n mainHeaderView\n Divider()\n messagesView(privatePeer: nil)\n Divider()\n inputView\n }\n .background(backgroundColor)\n .foregroundColor(textColor)\n .gesture(\n DragGesture()\n .onChanged { value in\n let translation = value.translation.width.isNaN ? 0 : value.translation.width\n if !showSidebar && translation < 0 {\n sidebarDragOffset = max(translation, -300)\n } else if showSidebar && translation > 0 {\n sidebarDragOffset = min(-300 + translation, 0)\n }\n }\n .onEnded { value in\n let translation = value.translation.width.isNaN ? 0 : value.translation.width\n let velocity = value.velocity.width.isNaN ? 0 : value.velocity.width\n withAnimation(.easeOut(duration: 0.2)) {\n if !showSidebar {\n if translation < -100 || (translation < -50 && velocity < -500) {\n showSidebar = true\n sidebarDragOffset = 0\n } else {\n sidebarDragOffset = 0\n }\n } else {\n if translation > 100 || (translation > 50 && velocity > 500) {\n showSidebar = false\n sidebarDragOffset = 0\n } else {\n sidebarDragOffset = 0\n }\n }\n }\n }\n )\n }\n \n private var privateChatView: some View {\n HStack(spacing: 0) {\n // Vertical separator bar\n Rectangle()\n .fill(Color.gray.opacity(0.3))\n .frame(width: 1)\n \n VStack(spacing: 0) {\n privateHeaderView\n Divider()\n messagesView(privatePeer: viewModel.selectedPrivateChatPeer)\n Divider()\n inputView\n }\n .background(backgroundColor)\n .foregroundColor(textColor)\n }\n }\n \n \n private var mainHeaderView: some View {\n HStack(spacing: 0) {\n Text(\"bitchat/\")\n .font(.system(size: 18, weight: .medium, design: .monospaced))\n .foregroundColor(textColor)\n .onTapGesture(count: 3) {\n // PANIC: Triple-tap to clear all data\n viewModel.panicClearAllData()\n }\n .onTapGesture(count: 1) {\n // Single tap for app info\n showAppInfo = true\n }\n \n HStack(spacing: 0) {\n Text(\"@\")\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(secondaryTextColor)\n \n TextField(\"nickname\", text: $viewModel.nickname)\n .textFieldStyle(.plain)\n .font(.system(size: 14, design: .monospaced))\n .frame(maxWidth: 100)\n .foregroundColor(textColor)\n .focused($isNicknameFieldFocused)\n .autocorrectionDisabled(true)\n #if os(iOS)\n .textInputAutocapitalization(.never)\n #endif\n .onChange(of: isNicknameFieldFocused) { isFocused in\n if !isFocused {\n // Only validate when losing focus\n viewModel.validateAndSaveNickname()\n }\n }\n .onSubmit {\n viewModel.validateAndSaveNickname()\n }\n }\n \n Spacer()\n \n // People counter with unread indicator\n HStack(spacing: 4) {\n if !viewModel.unreadPrivateMessages.isEmpty {\n Image(systemName: \"envelope.fill\")\n .font(.system(size: 12))\n .foregroundColor(Color.orange)\n .accessibilityLabel(\"Unread private messages\")\n }\n \n let otherPeersCount = viewModel.connectedPeers.filter { $0 != viewModel.meshService.myPeerID }.count\n \n HStack(spacing: 4) {\n // People icon with count\n Image(systemName: \"person.2.fill\")\n .font(.system(size: 11))\n .accessibilityLabel(\"\\(otherPeersCount) connected \\(otherPeersCount == 1 ? \"person\" : \"people\")\")\n Text(\"\\(otherPeersCount)\")\n .font(.system(size: 12, design: .monospaced))\n .accessibilityHidden(true)\n }\n .foregroundColor(viewModel.isConnected ? textColor : Color.red)\n }\n .onTapGesture {\n withAnimation(.easeInOut(duration: 0.2)) {\n showSidebar.toggle()\n sidebarDragOffset = 0\n }\n }\n }\n .frame(height: 44)\n .padding(.horizontal, 12)\n .background(backgroundColor.opacity(0.95))\n }\n \n private var privateHeaderView: some View {\n Group {\n if let privatePeerID = viewModel.selectedPrivateChatPeer,\n let privatePeerNick = viewModel.meshService.getPeerNicknames()[privatePeerID] {\n HStack {\n Button(action: {\n withAnimation(.easeInOut(duration: 0.2)) {\n showPrivateChat = false\n viewModel.endPrivateChat()\n }\n }) {\n HStack(spacing: 4) {\n Image(systemName: \"chevron.left\")\n .font(.system(size: 12))\n Text(\"back\")\n .font(.system(size: 14, design: .monospaced))\n }\n .foregroundColor(textColor)\n }\n .buttonStyle(.plain)\n .accessibilityLabel(\"Back to main chat\")\n \n Spacer()\n \n Button(action: {\n viewModel.showFingerprint(for: privatePeerID)\n }) {\n HStack(spacing: 6) {\n Text(\"\\(privatePeerNick)\")\n .font(.system(size: 16, weight: .medium, design: .monospaced))\n .foregroundColor(Color.orange)\n // Dynamic encryption status icon\n let encryptionStatus = viewModel.getEncryptionStatus(for: privatePeerID)\n if let icon = encryptionStatus.icon {\n Image(systemName: icon)\n .font(.system(size: 14))\n .foregroundColor(encryptionStatus == .noiseVerified ? Color.green : \n encryptionStatus == .noiseSecured ? Color.orange :\n Color.red)\n .accessibilityLabel(\"Encryption status: \\(encryptionStatus == .noiseVerified ? \"verified\" : encryptionStatus == .noiseSecured ? \"secured\" : \"not encrypted\")\")\n }\n }\n .frame(maxWidth: .infinity)\n .accessibilityLabel(\"Private chat with \\(privatePeerNick)\")\n .accessibilityHint(\"Tap to view encryption fingerprint\")\n }\n .buttonStyle(.plain)\n \n Spacer()\n \n // Favorite button\n Button(action: {\n viewModel.toggleFavorite(peerID: privatePeerID)\n }) {\n Image(systemName: viewModel.isFavorite(peerID: privatePeerID) ? \"star.fill\" : \"star\")\n .font(.system(size: 16))\n .foregroundColor(viewModel.isFavorite(peerID: privatePeerID) ? Color.yellow : textColor)\n }\n .buttonStyle(.plain)\n .accessibilityLabel(viewModel.isFavorite(peerID: privatePeerID) ? \"Remove from favorites\" : \"Add to favorites\")\n .accessibilityHint(\"Double tap to toggle favorite status\")\n }\n .frame(height: 44)\n .padding(.horizontal, 12)\n .background(backgroundColor.opacity(0.95))\n } else {\n EmptyView()\n }\n }\n }\n \n}\n\n// MARK: - Helper Views\n\n// Helper view for rendering message content with clickable hashtags\nstruct MessageContentView: View {\n let message: BitchatMessage\n let viewModel: ChatViewModel\n let colorScheme: ColorScheme\n let isMentioned: Bool\n \n var body: some View {\n let content = message.content\n let hashtagPattern = \"#([a-zA-Z0-9_]+)\"\n let mentionPattern = \"@([a-zA-Z0-9_]+)\"\n \n let hashtagRegex = try? NSRegularExpression(pattern: hashtagPattern, options: [])\n let mentionRegex = try? NSRegularExpression(pattern: mentionPattern, options: [])\n \n let hashtagMatches = hashtagRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n let mentionMatches = mentionRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n \n // Combine all matches and sort by location\n var allMatches: [(range: NSRange, type: String)] = []\n for match in hashtagMatches {\n allMatches.append((match.range(at: 0), \"hashtag\"))\n }\n for match in mentionMatches {\n allMatches.append((match.range(at: 0), \"mention\"))\n }\n allMatches.sort { $0.range.location < $1.range.location }\n \n // Build the text as a concatenated Text view for natural wrapping\n let segments = buildTextSegments()\n var result = Text(\"\")\n \n for segment in segments {\n if segment.type == \"hashtag\" {\n // Note: We can't have clickable links in concatenated Text, so hashtags won't be clickable\n result = result + Text(segment.text)\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(Color.blue)\n .underline()\n } else if segment.type == \"mention\" {\n result = result + Text(segment.text)\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(Color.orange)\n } else {\n result = result + Text(segment.text)\n .font(.system(size: 14, design: .monospaced))\n .fontWeight(isMentioned ? .bold : .regular)\n }\n }\n \n return result\n .textSelection(.enabled)\n }\n \n // MARK: - Helper Methods\n \n private func buildTextSegments() -> [(text: String, type: String)] {\n var segments: [(text: String, type: String)] = []\n let content = message.content\n var lastEnd = content.startIndex\n \n let hashtagPattern = \"#([a-zA-Z0-9_]+)\"\n let mentionPattern = \"@([a-zA-Z0-9_]+)\"\n \n let hashtagRegex = try? NSRegularExpression(pattern: hashtagPattern, options: [])\n let mentionRegex = try? NSRegularExpression(pattern: mentionPattern, options: [])\n \n let hashtagMatches = hashtagRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n let mentionMatches = mentionRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n \n // Combine all matches and sort by location\n var allMatches: [(range: NSRange, type: String)] = []\n for match in hashtagMatches {\n allMatches.append((match.range(at: 0), \"hashtag\"))\n }\n for match in mentionMatches {\n allMatches.append((match.range(at: 0), \"mention\"))\n }\n allMatches.sort { $0.range.location < $1.range.location }\n \n for (matchRange, matchType) in allMatches {\n if let range = Range(matchRange, in: content) {\n // Add text before the match\n if lastEnd < range.lowerBound {\n let beforeText = String(content[lastEnd..\n//\n\n///\n/// # BitchatProtocol\n///\n/// Defines the application-layer protocol for BitChat mesh networking, including\n/// message types, packet structures, and encoding/decoding logic.\n///\n/// ## Overview\n/// BitchatProtocol implements a binary protocol optimized for Bluetooth LE's\n/// constrained bandwidth and MTU limitations. It provides:\n/// - Efficient binary message encoding\n/// - Message fragmentation for large payloads\n/// - TTL-based routing for mesh networks\n/// - Privacy features like padding and timing obfuscation\n/// - Integration points for end-to-end encryption\n///\n/// ## Protocol Design\n/// The protocol uses a compact binary format to minimize overhead:\n/// - 1-byte message type identifier\n/// - Variable-length fields with length prefixes\n/// - Network byte order (big-endian) for multi-byte values\n/// - PKCS#7-style padding for privacy\n///\n/// ## Message Flow\n/// 1. **Creation**: Messages are created with type, content, and metadata\n/// 2. **Encoding**: Converted to binary format with proper field ordering\n/// 3. **Fragmentation**: Split if larger than BLE MTU (512 bytes)\n/// 4. **Transmission**: Sent via BluetoothMeshService\n/// 5. **Routing**: Relayed by intermediate nodes (TTL decrements)\n/// 6. **Reassembly**: Fragments collected and reassembled\n/// 7. **Decoding**: Binary data parsed back to message objects\n///\n/// ## Security Considerations\n/// - Message padding obscures actual content length\n/// - Timing obfuscation prevents traffic analysis\n/// - Integration with Noise Protocol for E2E encryption\n/// - No persistent identifiers in protocol headers\n///\n/// ## Message Types\n/// - **Announce/Leave**: Peer presence notifications\n/// - **Message**: User chat messages (broadcast or directed)\n/// - **Fragment**: Multi-part message handling\n/// - **Delivery/Read**: Message acknowledgments\n/// - **Noise**: Encrypted channel establishment\n/// - **Version**: Protocol compatibility negotiation\n///\n/// ## Future Extensions\n/// The protocol is designed to be extensible:\n/// - Reserved message type ranges for future use\n/// - Version negotiation for backward compatibility\n/// - Optional fields for new features\n///\n\nimport Foundation\nimport CryptoKit\n\n// MARK: - Message Padding\n\n/// Provides privacy-preserving message padding to obscure actual content length.\n/// Uses PKCS#7-style padding with random bytes to prevent traffic analysis.\nstruct MessagePadding {\n // Standard block sizes for padding\n static let blockSizes = [256, 512, 1024, 2048]\n \n // Add PKCS#7-style padding to reach target size\n static func pad(_ data: Data, toSize targetSize: Int) -> Data {\n guard data.count < targetSize else { return data }\n \n let paddingNeeded = targetSize - data.count\n \n // PKCS#7 only supports padding up to 255 bytes\n // If we need more padding than that, don't pad - return original data\n guard paddingNeeded <= 255 else { return data }\n \n var padded = data\n \n // Standard PKCS#7 padding\n var randomBytes = [UInt8](repeating: 0, count: paddingNeeded - 1)\n _ = SecRandomCopyBytes(kSecRandomDefault, paddingNeeded - 1, &randomBytes)\n padded.append(contentsOf: randomBytes)\n padded.append(UInt8(paddingNeeded))\n \n return padded\n }\n \n // Remove padding from data\n static func unpad(_ data: Data) -> Data {\n guard !data.isEmpty else { return data }\n \n // Last byte tells us how much padding to remove\n let paddingLength = Int(data[data.count - 1])\n guard paddingLength > 0 && paddingLength <= data.count else { \n // Debug logging for 243-byte packets\n if data.count == 243 {\n }\n return data \n }\n \n let result = data.prefix(data.count - paddingLength)\n \n // Debug logging for 243-byte packets\n if data.count == 243 {\n }\n \n return result\n }\n \n // Find optimal block size for data\n static func optimalBlockSize(for dataSize: Int) -> Int {\n // Account for encryption overhead (~16 bytes for AES-GCM tag)\n let totalSize = dataSize + 16\n \n // Find smallest block that fits\n for blockSize in blockSizes {\n if totalSize <= blockSize {\n return blockSize\n }\n }\n \n // For very large messages, just use the original size\n // (will be fragmented anyway)\n return dataSize\n }\n}\n\n// MARK: - Message Types\n\n/// Defines all message types in the BitChat protocol.\n/// Each type has a unique identifier for efficient binary encoding.\n/// Types are grouped by function: user messages, protocol control, encryption, etc.\nenum MessageType: UInt8 {\n case announce = 0x01\n case leave = 0x03\n case message = 0x04 // All user messages (private and broadcast)\n case fragmentStart = 0x05\n case fragmentContinue = 0x06\n case fragmentEnd = 0x07\n case deliveryAck = 0x0A // Acknowledge message received\n case deliveryStatusRequest = 0x0B // Request delivery status update\n case readReceipt = 0x0C // Message has been read/viewed\n \n // Noise Protocol messages\n case noiseHandshakeInit = 0x10 // Noise handshake initiation\n case noiseHandshakeResp = 0x11 // Noise handshake response\n case noiseEncrypted = 0x12 // Noise encrypted transport message\n case noiseIdentityAnnounce = 0x13 // Announce static public key for discovery\n \n // Protocol version negotiation\n case versionHello = 0x20 // Initial version announcement\n case versionAck = 0x21 // Version acknowledgment\n \n // Protocol-level acknowledgments\n case protocolAck = 0x22 // Generic protocol acknowledgment\n case protocolNack = 0x23 // Negative acknowledgment (failure)\n case systemValidation = 0x24 // Session validation ping\n case handshakeRequest = 0x25 // Request handshake for pending messages\n \n var description: String {\n switch self {\n case .announce: return \"announce\"\n case .leave: return \"leave\"\n case .message: return \"message\"\n case .fragmentStart: return \"fragmentStart\"\n case .fragmentContinue: return \"fragmentContinue\"\n case .fragmentEnd: return \"fragmentEnd\"\n case .deliveryAck: return \"deliveryAck\"\n case .deliveryStatusRequest: return \"deliveryStatusRequest\"\n case .readReceipt: return \"readReceipt\"\n case .noiseHandshakeInit: return \"noiseHandshakeInit\"\n case .noiseHandshakeResp: return \"noiseHandshakeResp\"\n case .noiseEncrypted: return \"noiseEncrypted\"\n case .noiseIdentityAnnounce: return \"noiseIdentityAnnounce\"\n case .versionHello: return \"versionHello\"\n case .versionAck: return \"versionAck\"\n case .protocolAck: return \"protocolAck\"\n case .protocolNack: return \"protocolNack\"\n case .systemValidation: return \"systemValidation\"\n case .handshakeRequest: return \"handshakeRequest\"\n }\n }\n}\n\n// MARK: - Handshake State\n\n// Lazy handshake state tracking\nenum LazyHandshakeState {\n case none // No session, no handshake attempted\n case handshakeQueued // User action requires handshake\n case handshaking // Currently in handshake process\n case established // Session ready for use\n case failed(Error) // Handshake failed\n}\n\n// MARK: - Special Recipients\n\n/// Defines special recipient identifiers used in the protocol.\n/// These magic values indicate broadcast or system-level recipients\n/// rather than specific peer IDs.\nstruct SpecialRecipients {\n static let broadcast = Data(repeating: 0xFF, count: 8) // All 0xFF = broadcast\n}\n\n// MARK: - Core Protocol Structures\n\n/// The core packet structure for all BitChat protocol messages.\n/// Encapsulates all data needed for routing through the mesh network,\n/// including TTL for hop limiting and optional encryption.\n/// - Note: Packets larger than BLE MTU (512 bytes) are automatically fragmented\nstruct BitchatPacket: Codable {\n let version: UInt8\n let type: UInt8\n let senderID: Data\n let recipientID: Data?\n let timestamp: UInt64\n let payload: Data\n let signature: Data?\n var ttl: UInt8\n \n init(type: UInt8, senderID: Data, recipientID: Data?, timestamp: UInt64, payload: Data, signature: Data?, ttl: UInt8) {\n self.version = 1\n self.type = type\n self.senderID = senderID\n self.recipientID = recipientID\n self.timestamp = timestamp\n self.payload = payload\n self.signature = signature\n self.ttl = ttl\n }\n \n // Convenience initializer for new binary format\n init(type: UInt8, ttl: UInt8, senderID: String, payload: Data) {\n self.version = 1\n self.type = type\n // Convert hex string peer ID to binary data (8 bytes)\n var senderData = Data()\n var tempID = senderID\n while tempID.count >= 2 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n senderData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n self.senderID = senderData\n self.recipientID = nil\n self.timestamp = UInt64(Date().timeIntervalSince1970 * 1000) // milliseconds\n self.payload = payload\n self.signature = nil\n self.ttl = ttl\n }\n \n var data: Data? {\n BinaryProtocol.encode(self)\n }\n \n func toBinaryData() -> Data? {\n BinaryProtocol.encode(self)\n }\n \n static func from(_ data: Data) -> BitchatPacket? {\n BinaryProtocol.decode(data)\n }\n}\n\n// MARK: - Delivery Acknowledgments\n\n/// Acknowledgment sent when a message is successfully delivered to a recipient.\n/// Provides delivery confirmation for reliable messaging and UI feedback.\n/// - Note: Only sent for direct messages, not broadcasts\nstruct DeliveryAck: Codable {\n let originalMessageID: String\n let ackID: String\n let recipientID: String // Who received it\n let recipientNickname: String\n let timestamp: Date\n let hopCount: UInt8 // How many hops to reach recipient\n \n init(originalMessageID: String, recipientID: String, recipientNickname: String, hopCount: UInt8) {\n self.originalMessageID = originalMessageID\n self.ackID = UUID().uuidString\n self.recipientID = recipientID\n self.recipientNickname = recipientNickname\n self.timestamp = Date()\n self.hopCount = hopCount\n }\n \n // For binary decoding\n private init(originalMessageID: String, ackID: String, recipientID: String, recipientNickname: String, timestamp: Date, hopCount: UInt8) {\n self.originalMessageID = originalMessageID\n self.ackID = ackID\n self.recipientID = recipientID\n self.recipientNickname = recipientNickname\n self.timestamp = timestamp\n self.hopCount = hopCount\n }\n \n func encode() -> Data? {\n try? JSONEncoder().encode(self)\n }\n \n static func decode(from data: Data) -> DeliveryAck? {\n try? JSONDecoder().decode(DeliveryAck.self, from: data)\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUUID(originalMessageID)\n data.appendUUID(ackID)\n // RecipientID as 8-byte hex string\n var recipientData = Data()\n var tempID = recipientID\n while tempID.count >= 2 && recipientData.count < 8 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n recipientData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n while recipientData.count < 8 {\n recipientData.append(0)\n }\n data.append(recipientData)\n data.appendUInt8(hopCount)\n data.appendDate(timestamp)\n data.appendString(recipientNickname)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> DeliveryAck? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size: 2 UUIDs (32) + recipientID (8) + hopCount (1) + timestamp (8) + min nickname\n guard dataCopy.count >= 50 else { return nil }\n \n var offset = 0\n \n guard let originalMessageID = dataCopy.readUUID(at: &offset),\n let ackID = dataCopy.readUUID(at: &offset) else { return nil }\n \n guard let recipientIDData = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n let recipientID = recipientIDData.hexEncodedString()\n \n guard let hopCount = dataCopy.readUInt8(at: &offset),\n let timestamp = dataCopy.readDate(at: &offset),\n let recipientNickname = dataCopy.readString(at: &offset) else { return nil }\n \n return DeliveryAck(originalMessageID: originalMessageID,\n ackID: ackID,\n recipientID: recipientID,\n recipientNickname: recipientNickname,\n timestamp: timestamp,\n hopCount: hopCount)\n }\n}\n\n// MARK: - Read Receipts\n\n// Read receipt structure\nstruct ReadReceipt: Codable {\n let originalMessageID: String\n let receiptID: String\n let readerID: String // Who read it\n let readerNickname: String\n let timestamp: Date\n \n init(originalMessageID: String, readerID: String, readerNickname: String) {\n self.originalMessageID = originalMessageID\n self.receiptID = UUID().uuidString\n self.readerID = readerID\n self.readerNickname = readerNickname\n self.timestamp = Date()\n }\n \n // For binary decoding\n private init(originalMessageID: String, receiptID: String, readerID: String, readerNickname: String, timestamp: Date) {\n self.originalMessageID = originalMessageID\n self.receiptID = receiptID\n self.readerID = readerID\n self.readerNickname = readerNickname\n self.timestamp = timestamp\n }\n \n func encode() -> Data? {\n try? JSONEncoder().encode(self)\n }\n \n static func decode(from data: Data) -> ReadReceipt? {\n try? JSONDecoder().decode(ReadReceipt.self, from: data)\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUUID(originalMessageID)\n data.appendUUID(receiptID)\n // ReaderID as 8-byte hex string\n var readerData = Data()\n var tempID = readerID\n while tempID.count >= 2 && readerData.count < 8 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n readerData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n while readerData.count < 8 {\n readerData.append(0)\n }\n data.append(readerData)\n data.appendDate(timestamp)\n data.appendString(readerNickname)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> ReadReceipt? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size: 2 UUIDs (32) + readerID (8) + timestamp (8) + min nickname\n guard dataCopy.count >= 49 else { return nil }\n \n var offset = 0\n \n guard let originalMessageID = dataCopy.readUUID(at: &offset),\n let receiptID = dataCopy.readUUID(at: &offset) else { return nil }\n \n guard let readerIDData = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n let readerID = readerIDData.hexEncodedString()\n \n guard let timestamp = dataCopy.readDate(at: &offset),\n let readerNickname = dataCopy.readString(at: &offset) else { return nil }\n \n return ReadReceipt(originalMessageID: originalMessageID,\n receiptID: receiptID,\n readerID: readerID,\n readerNickname: readerNickname,\n timestamp: timestamp)\n }\n}\n\n// MARK: - Handshake Requests\n\n// Handshake request for pending messages\nstruct HandshakeRequest: Codable {\n let requestID: String\n let requesterID: String // Who needs the handshake\n let requesterNickname: String // Nickname of requester\n let targetID: String // Who should initiate handshake\n let pendingMessageCount: UInt8 // Number of messages queued\n let timestamp: Date\n \n init(requesterID: String, requesterNickname: String, targetID: String, pendingMessageCount: UInt8) {\n self.requestID = UUID().uuidString\n self.requesterID = requesterID\n self.requesterNickname = requesterNickname\n self.targetID = targetID\n self.pendingMessageCount = pendingMessageCount\n self.timestamp = Date()\n }\n \n // For binary decoding\n private init(requestID: String, requesterID: String, requesterNickname: String, targetID: String, pendingMessageCount: UInt8, timestamp: Date) {\n self.requestID = requestID\n self.requesterID = requesterID\n self.requesterNickname = requesterNickname\n self.targetID = targetID\n self.pendingMessageCount = pendingMessageCount\n self.timestamp = timestamp\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUUID(requestID)\n \n // RequesterID as 8-byte hex string\n var requesterData = Data()\n var tempID = requesterID\n while tempID.count >= 2 && requesterData.count < 8 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n requesterData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n while requesterData.count < 8 {\n requesterData.append(0)\n }\n data.append(requesterData)\n \n // TargetID as 8-byte hex string\n var targetData = Data()\n tempID = targetID\n while tempID.count >= 2 && targetData.count < 8 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n targetData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n while targetData.count < 8 {\n targetData.append(0)\n }\n data.append(targetData)\n \n data.appendUInt8(pendingMessageCount)\n data.appendDate(timestamp)\n data.appendString(requesterNickname)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> HandshakeRequest? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size: UUID (16) + requesterID (8) + targetID (8) + count (1) + timestamp (8) + min nickname\n guard dataCopy.count >= 42 else { return nil }\n \n var offset = 0\n \n guard let requestID = dataCopy.readUUID(at: &offset) else { return nil }\n \n guard let requesterIDData = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n let requesterID = requesterIDData.hexEncodedString()\n \n guard let targetIDData = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n let targetID = targetIDData.hexEncodedString()\n \n guard let pendingMessageCount = dataCopy.readUInt8(at: &offset),\n let timestamp = dataCopy.readDate(at: &offset),\n let requesterNickname = dataCopy.readString(at: &offset) else { return nil }\n \n return HandshakeRequest(requestID: requestID,\n requesterID: requesterID,\n requesterNickname: requesterNickname,\n targetID: targetID,\n pendingMessageCount: pendingMessageCount,\n timestamp: timestamp)\n }\n}\n\n// MARK: - Protocol Acknowledgments\n\n// Protocol-level acknowledgment for reliable delivery\nstruct ProtocolAck: Codable {\n let originalPacketID: String // ID of the packet being acknowledged\n let ackID: String // Unique ID for this ACK\n let senderID: String // Who sent the original packet\n let receiverID: String // Who received and is acknowledging\n let packetType: UInt8 // Type of packet being acknowledged\n let timestamp: Date // When ACK was generated\n let hopCount: UInt8 // Hops taken to reach receiver\n \n init(originalPacketID: String, senderID: String, receiverID: String, packetType: UInt8, hopCount: UInt8) {\n self.originalPacketID = originalPacketID\n self.ackID = UUID().uuidString\n self.senderID = senderID\n self.receiverID = receiverID\n self.packetType = packetType\n self.timestamp = Date()\n self.hopCount = hopCount\n }\n \n // Private init for binary decoding\n private init(originalPacketID: String, ackID: String, senderID: String, receiverID: String, \n packetType: UInt8, timestamp: Date, hopCount: UInt8) {\n self.originalPacketID = originalPacketID\n self.ackID = ackID\n self.senderID = senderID\n self.receiverID = receiverID\n self.packetType = packetType\n self.timestamp = timestamp\n self.hopCount = hopCount\n }\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUUID(originalPacketID)\n data.appendUUID(ackID)\n \n // Sender and receiver IDs as 8-byte hex strings\n data.append(Data(hexString: senderID) ?? Data(repeating: 0, count: 8))\n data.append(Data(hexString: receiverID) ?? Data(repeating: 0, count: 8))\n \n data.appendUInt8(packetType)\n data.appendUInt8(hopCount)\n data.appendDate(timestamp)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> ProtocolAck? {\n let dataCopy = Data(data)\n guard dataCopy.count >= 50 else { return nil } // 2 UUIDs + 2 IDs + type + hop + timestamp\n \n var offset = 0\n guard let originalPacketID = dataCopy.readUUID(at: &offset),\n let ackID = dataCopy.readUUID(at: &offset),\n let senderIDData = dataCopy.readFixedBytes(at: &offset, count: 8),\n let receiverIDData = dataCopy.readFixedBytes(at: &offset, count: 8),\n let packetType = dataCopy.readUInt8(at: &offset),\n let hopCount = dataCopy.readUInt8(at: &offset),\n let timestamp = dataCopy.readDate(at: &offset) else { return nil }\n \n let senderID = senderIDData.hexEncodedString()\n let receiverID = receiverIDData.hexEncodedString()\n \n return ProtocolAck(originalPacketID: originalPacketID,\n ackID: ackID,\n senderID: senderID,\n receiverID: receiverID,\n packetType: packetType,\n timestamp: timestamp,\n hopCount: hopCount)\n }\n}\n\n// Protocol-level negative acknowledgment\nstruct ProtocolNack: Codable {\n let originalPacketID: String // ID of the packet that failed\n let nackID: String // Unique ID for this NACK\n let senderID: String // Who sent the original packet\n let receiverID: String // Who is reporting the failure\n let packetType: UInt8 // Type of packet that failed\n let timestamp: Date // When NACK was generated\n let reason: String // Reason for failure\n let errorCode: UInt8 // Numeric error code\n \n // Error codes\n enum ErrorCode: UInt8 {\n case unknown = 0\n case checksumFailed = 1\n case decryptionFailed = 2\n case malformedPacket = 3\n case unsupportedVersion = 4\n case resourceExhausted = 5\n case routingFailed = 6\n case sessionExpired = 7\n }\n \n init(originalPacketID: String, senderID: String, receiverID: String, \n packetType: UInt8, reason: String, errorCode: ErrorCode = .unknown) {\n self.originalPacketID = originalPacketID\n self.nackID = UUID().uuidString\n self.senderID = senderID\n self.receiverID = receiverID\n self.packetType = packetType\n self.timestamp = Date()\n self.reason = reason\n self.errorCode = errorCode.rawValue\n }\n \n // Private init for binary decoding\n private init(originalPacketID: String, nackID: String, senderID: String, receiverID: String,\n packetType: UInt8, timestamp: Date, reason: String, errorCode: UInt8) {\n self.originalPacketID = originalPacketID\n self.nackID = nackID\n self.senderID = senderID\n self.receiverID = receiverID\n self.packetType = packetType\n self.timestamp = timestamp\n self.reason = reason\n self.errorCode = errorCode\n }\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUUID(originalPacketID)\n data.appendUUID(nackID)\n \n // Sender and receiver IDs as 8-byte hex strings\n data.append(Data(hexString: senderID) ?? Data(repeating: 0, count: 8))\n data.append(Data(hexString: receiverID) ?? Data(repeating: 0, count: 8))\n \n data.appendUInt8(packetType)\n data.appendUInt8(errorCode)\n data.appendDate(timestamp)\n data.appendString(reason)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> ProtocolNack? {\n let dataCopy = Data(data)\n guard dataCopy.count >= 52 else { return nil } // Minimum size\n \n var offset = 0\n guard let originalPacketID = dataCopy.readUUID(at: &offset),\n let nackID = dataCopy.readUUID(at: &offset),\n let senderIDData = dataCopy.readFixedBytes(at: &offset, count: 8),\n let receiverIDData = dataCopy.readFixedBytes(at: &offset, count: 8),\n let packetType = dataCopy.readUInt8(at: &offset),\n let errorCode = dataCopy.readUInt8(at: &offset),\n let timestamp = dataCopy.readDate(at: &offset),\n let reason = dataCopy.readString(at: &offset) else { return nil }\n \n let senderID = senderIDData.hexEncodedString()\n let receiverID = receiverIDData.hexEncodedString()\n \n return ProtocolNack(originalPacketID: originalPacketID,\n nackID: nackID,\n senderID: senderID,\n receiverID: receiverID,\n packetType: packetType,\n timestamp: timestamp,\n reason: reason,\n errorCode: errorCode)\n }\n}\n\n// MARK: - Peer Identity Rotation\n\n/// Announces a peer's cryptographic identity to enable secure communication.\n/// Contains the peer's Noise static public key and supports identity rotation\n/// by binding ephemeral peer IDs to stable cryptographic fingerprints.\n/// - Note: Critical for establishing end-to-end encrypted channels\nstruct NoiseIdentityAnnouncement: Codable {\n let peerID: String // Current ephemeral peer ID\n let publicKey: Data // Noise static public key\n let signingPublicKey: Data // Ed25519 signing public key\n let nickname: String // Current nickname\n let timestamp: Date // When this binding was created\n let previousPeerID: String? // Previous peer ID (for smooth transition)\n let signature: Data // Signature proving ownership\n \n init(peerID: String, publicKey: Data, signingPublicKey: Data, nickname: String, timestamp: Date, previousPeerID: String? = nil, signature: Data) {\n self.peerID = peerID\n self.publicKey = publicKey\n self.signingPublicKey = signingPublicKey\n // Trim whitespace from nickname\n self.nickname = nickname.trimmingCharacters(in: .whitespacesAndNewlines)\n self.timestamp = timestamp\n self.previousPeerID = previousPeerID\n self.signature = signature\n }\n \n // Custom decoder to ensure nickname is trimmed\n init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n self.peerID = try container.decode(String.self, forKey: .peerID)\n self.publicKey = try container.decode(Data.self, forKey: .publicKey)\n self.signingPublicKey = try container.decode(Data.self, forKey: .signingPublicKey)\n // Trim whitespace from decoded nickname\n let rawNickname = try container.decode(String.self, forKey: .nickname)\n self.nickname = rawNickname.trimmingCharacters(in: .whitespacesAndNewlines)\n self.timestamp = try container.decode(Date.self, forKey: .timestamp)\n self.previousPeerID = try container.decodeIfPresent(String.self, forKey: .previousPeerID)\n self.signature = try container.decode(Data.self, forKey: .signature)\n }\n \n func encode() -> Data? {\n return try? JSONEncoder().encode(self)\n }\n \n static func decode(from data: Data) -> NoiseIdentityAnnouncement? {\n return try? JSONDecoder().decode(NoiseIdentityAnnouncement.self, from: data)\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n \n // Flags byte: bit 0 = hasPreviousPeerID\n var flags: UInt8 = 0\n if previousPeerID != nil { flags |= 0x01 }\n data.appendUInt8(flags)\n \n // PeerID as 8-byte hex string\n var peerData = Data()\n var tempID = peerID\n while tempID.count >= 2 && peerData.count < 8 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n peerData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n while peerData.count < 8 {\n peerData.append(0)\n }\n data.append(peerData)\n \n data.appendData(publicKey)\n data.appendData(signingPublicKey)\n data.appendString(nickname)\n data.appendDate(timestamp)\n \n if let previousPeerID = previousPeerID {\n // Previous PeerID as 8-byte hex string\n var prevData = Data()\n var tempPrevID = previousPeerID\n while tempPrevID.count >= 2 && prevData.count < 8 {\n let hexByte = String(tempPrevID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n prevData.append(byte)\n }\n tempPrevID = String(tempPrevID.dropFirst(2))\n }\n while prevData.count < 8 {\n prevData.append(0)\n }\n data.append(prevData)\n }\n \n data.appendData(signature)\n \n return data\n }\n \n static func fromBinaryData(_ data: Data) -> NoiseIdentityAnnouncement? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size check: flags(1) + peerID(8) + min data lengths\n guard dataCopy.count >= 20 else { return nil }\n \n var offset = 0\n \n guard let flags = dataCopy.readUInt8(at: &offset) else { return nil }\n let hasPreviousPeerID = (flags & 0x01) != 0\n \n // Read peerID using safe method\n guard let peerIDBytes = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n let peerID = peerIDBytes.hexEncodedString()\n \n guard let publicKey = dataCopy.readData(at: &offset),\n let signingPublicKey = dataCopy.readData(at: &offset),\n let rawNickname = dataCopy.readString(at: &offset),\n let timestamp = dataCopy.readDate(at: &offset) else { return nil }\n \n // Trim whitespace from nickname\n let nickname = rawNickname.trimmingCharacters(in: .whitespacesAndNewlines)\n \n var previousPeerID: String? = nil\n if hasPreviousPeerID {\n // Read previousPeerID using safe method\n guard let prevIDBytes = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n previousPeerID = prevIDBytes.hexEncodedString()\n }\n \n guard let signature = dataCopy.readData(at: &offset) else { return nil }\n \n return NoiseIdentityAnnouncement(peerID: peerID,\n publicKey: publicKey,\n signingPublicKey: signingPublicKey,\n nickname: nickname,\n timestamp: timestamp,\n previousPeerID: previousPeerID,\n signature: signature)\n }\n}\n\n// Binding between ephemeral peer ID and cryptographic identity\nstruct PeerIdentityBinding {\n let currentPeerID: String // Current ephemeral ID\n let fingerprint: String // Permanent cryptographic identity\n let publicKey: Data // Noise static public key\n let signingPublicKey: Data // Ed25519 signing public key\n let nickname: String // Last known nickname\n let bindingTimestamp: Date // When this binding was created\n let signature: Data // Cryptographic proof of binding\n \n // Verify the binding signature\n func verify() -> Bool {\n let bindingData = currentPeerID.data(using: .utf8)! + publicKey + \n String(Int64(bindingTimestamp.timeIntervalSince1970 * 1000)).data(using: .utf8)!\n \n do {\n let signingKey = try Curve25519.Signing.PublicKey(rawRepresentation: signingPublicKey)\n return signingKey.isValidSignature(signature, for: bindingData)\n } catch {\n return false\n }\n }\n}\n\n// MARK: - Protocol Version Negotiation\n\n// Protocol version constants\nstruct ProtocolVersion {\n static let current: UInt8 = 1\n static let minimum: UInt8 = 1\n static let maximum: UInt8 = 1\n \n // Future versions can be added here\n static let supportedVersions: Set = [1]\n \n static func isSupported(_ version: UInt8) -> Bool {\n return supportedVersions.contains(version)\n }\n \n static func negotiateVersion(clientVersions: [UInt8], serverVersions: [UInt8]) -> UInt8? {\n // Find the highest common version\n let clientSet = Set(clientVersions)\n let serverSet = Set(serverVersions)\n let common = clientSet.intersection(serverSet)\n \n return common.max()\n }\n}\n\n// Version negotiation hello message\nstruct VersionHello: Codable {\n let supportedVersions: [UInt8] // List of supported protocol versions\n let preferredVersion: UInt8 // Preferred version (usually the latest)\n let clientVersion: String // App version string (e.g., \"1.0.0\")\n let platform: String // Platform identifier (e.g., \"iOS\", \"macOS\")\n let capabilities: [String]? // Optional capability flags for future extensions\n \n init(supportedVersions: [UInt8] = Array(ProtocolVersion.supportedVersions), \n preferredVersion: UInt8 = ProtocolVersion.current,\n clientVersion: String,\n platform: String,\n capabilities: [String]? = nil) {\n self.supportedVersions = supportedVersions\n self.preferredVersion = preferredVersion\n self.clientVersion = clientVersion\n self.platform = platform\n self.capabilities = capabilities\n }\n \n func encode() -> Data? {\n return try? JSONEncoder().encode(self)\n }\n \n static func decode(from data: Data) -> VersionHello? {\n try? JSONDecoder().decode(VersionHello.self, from: data)\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n \n // Flags byte: bit 0 = hasCapabilities\n var flags: UInt8 = 0\n if capabilities != nil { flags |= 0x01 }\n data.appendUInt8(flags)\n \n // Supported versions array\n data.appendUInt8(UInt8(supportedVersions.count))\n for version in supportedVersions {\n data.appendUInt8(version)\n }\n \n data.appendUInt8(preferredVersion)\n data.appendString(clientVersion)\n data.appendString(platform)\n \n if let capabilities = capabilities {\n data.appendUInt8(UInt8(capabilities.count))\n for capability in capabilities {\n data.appendString(capability)\n }\n }\n \n return data\n }\n \n static func fromBinaryData(_ data: Data) -> VersionHello? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size check: flags(1) + versionCount(1) + at least one version(1) + preferredVersion(1) + min strings\n guard dataCopy.count >= 4 else { return nil }\n \n var offset = 0\n \n guard let flags = dataCopy.readUInt8(at: &offset) else { return nil }\n let hasCapabilities = (flags & 0x01) != 0\n \n guard let versionCount = dataCopy.readUInt8(at: &offset) else { return nil }\n var supportedVersions: [UInt8] = []\n for _ in 0.. Data? {\n return try? JSONEncoder().encode(self)\n }\n \n static func decode(from data: Data) -> VersionAck? {\n try? JSONDecoder().decode(VersionAck.self, from: data)\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n \n // Flags byte: bit 0 = hasCapabilities, bit 1 = hasReason\n var flags: UInt8 = 0\n if capabilities != nil { flags |= 0x01 }\n if reason != nil { flags |= 0x02 }\n data.appendUInt8(flags)\n \n data.appendUInt8(agreedVersion)\n data.appendString(serverVersion)\n data.appendString(platform)\n data.appendUInt8(rejected ? 1 : 0)\n \n if let capabilities = capabilities {\n data.appendUInt8(UInt8(capabilities.count))\n for capability in capabilities {\n data.appendString(capability)\n }\n }\n \n if let reason = reason {\n data.appendString(reason)\n }\n \n return data\n }\n \n static func fromBinaryData(_ data: Data) -> VersionAck? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size: flags(1) + version(1) + rejected(1) + min strings\n guard dataCopy.count >= 5 else { return nil }\n \n var offset = 0\n \n guard let flags = dataCopy.readUInt8(at: &offset) else { return nil }\n let hasCapabilities = (flags & 0x01) != 0\n let hasReason = (flags & 0x02) != 0\n \n guard let agreedVersion = dataCopy.readUInt8(at: &offset),\n let serverVersion = dataCopy.readString(at: &offset),\n let platform = dataCopy.readString(at: &offset),\n let rejectedByte = dataCopy.readUInt8(at: &offset) else { return nil }\n \n let rejected = rejectedByte != 0\n \n var capabilities: [String]? = nil\n if hasCapabilities {\n guard let capCount = dataCopy.readUInt8(at: &offset) else { return nil }\n capabilities = []\n for _ in 0.. AttributedString? {\n return _cachedFormattedText[\"\\(isDark)\"]\n }\n \n func setCachedFormattedText(_ text: AttributedString, isDark: Bool) {\n _cachedFormattedText[\"\\(isDark)\"] = text\n }\n \n // Codable implementation\n enum CodingKeys: String, CodingKey {\n case id, sender, content, timestamp, isRelay, originalSender\n case isPrivate, recipientNickname, senderPeerID, mentions, deliveryStatus\n }\n \n init(id: String? = nil, sender: String, content: String, timestamp: Date, isRelay: Bool, originalSender: String? = nil, isPrivate: Bool = false, recipientNickname: String? = nil, senderPeerID: String? = nil, mentions: [String]? = nil, deliveryStatus: DeliveryStatus? = nil) {\n self.id = id ?? UUID().uuidString\n self.sender = sender\n self.content = content\n self.timestamp = timestamp\n self.isRelay = isRelay\n self.originalSender = originalSender\n self.isPrivate = isPrivate\n self.recipientNickname = recipientNickname\n self.senderPeerID = senderPeerID\n self.mentions = mentions\n self.deliveryStatus = deliveryStatus ?? (isPrivate ? .sending : nil)\n }\n}\n\n// Equatable conformance for BitchatMessage\nextension BitchatMessage: Equatable {\n static func == (lhs: BitchatMessage, rhs: BitchatMessage) -> Bool {\n return lhs.id == rhs.id &&\n lhs.sender == rhs.sender &&\n lhs.content == rhs.content &&\n lhs.timestamp == rhs.timestamp &&\n lhs.isRelay == rhs.isRelay &&\n lhs.originalSender == rhs.originalSender &&\n lhs.isPrivate == rhs.isPrivate &&\n lhs.recipientNickname == rhs.recipientNickname &&\n lhs.senderPeerID == rhs.senderPeerID &&\n lhs.mentions == rhs.mentions &&\n lhs.deliveryStatus == rhs.deliveryStatus\n }\n}\n\n// MARK: - Delegate Protocol\n\nprotocol BitchatDelegate: AnyObject {\n func didReceiveMessage(_ message: BitchatMessage)\n func didConnectToPeer(_ peerID: String)\n func didDisconnectFromPeer(_ peerID: String)\n func didUpdatePeerList(_ peers: [String])\n \n // Optional method to check if a fingerprint belongs to a favorite peer\n func isFavorite(fingerprint: String) -> Bool\n \n // Delivery confirmation methods\n func didReceiveDeliveryAck(_ ack: DeliveryAck)\n func didReceiveReadReceipt(_ receipt: ReadReceipt)\n func didUpdateMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus)\n \n // Peer availability tracking\n func peerAvailabilityChanged(_ peerID: String, available: Bool)\n}\n\n// Provide default implementation to make it effectively optional\nextension BitchatDelegate {\n func isFavorite(fingerprint: String) -> Bool {\n return false\n }\n \n func didReceiveDeliveryAck(_ ack: DeliveryAck) {\n // Default empty implementation\n }\n \n func didReceiveReadReceipt(_ receipt: ReadReceipt) {\n // Default empty implementation\n }\n \n func didUpdateMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) {\n // Default empty implementation\n }\n \n func peerAvailabilityChanged(_ peerID: String, available: Bool) {\n // Default empty implementation\n }\n}\n"], ["/bitchat/bitchat/Identity/SecureIdentityStateManager.swift", "//\n// SecureIdentityStateManager.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # SecureIdentityStateManager\n///\n/// Manages the persistent storage and retrieval of identity mappings with\n/// encryption at rest. This singleton service maintains the relationship between\n/// ephemeral peer IDs, cryptographic fingerprints, and social identities.\n///\n/// ## Overview\n/// The SecureIdentityStateManager provides a secure, privacy-preserving way to\n/// maintain identity relationships across app launches. It implements:\n/// - Encrypted storage of identity mappings\n/// - In-memory caching for performance\n/// - Thread-safe access patterns\n/// - Automatic debounced persistence\n///\n/// ## Architecture\n/// The manager operates at three levels:\n/// 1. **In-Memory State**: Fast access to active identities\n/// 2. **Encrypted Cache**: Persistent storage in Keychain\n/// 3. **Privacy Controls**: User-configurable persistence settings\n///\n/// ## Security Features\n///\n/// ### Encryption at Rest\n/// - Identity cache encrypted with AES-GCM\n/// - Unique 256-bit encryption key per device\n/// - Key stored separately in Keychain\n/// - No plaintext identity data on disk\n///\n/// ### Privacy by Design\n/// - Persistence is optional (user-controlled)\n/// - Minimal data retention\n/// - No cloud sync or backup\n/// - Automatic cleanup of stale entries\n///\n/// ### Thread Safety\n/// - Concurrent read access via GCD barriers\n/// - Write operations serialized\n/// - Atomic state updates\n/// - No data races or corruption\n///\n/// ## Data Model\n/// Manages three types of identity data:\n/// 1. **Ephemeral Sessions**: Current peer connections\n/// 2. **Cryptographic Identities**: Public keys and fingerprints\n/// 3. **Social Identities**: User-assigned names and trust\n///\n/// ## Persistence Strategy\n/// - Changes batched and debounced (2-second window)\n/// - Automatic save on app termination\n/// - Crash-resistant with atomic writes\n/// - Migration support for schema changes\n///\n/// ## Usage Patterns\n/// ```swift\n/// // Register a new peer identity\n/// manager.registerPeerIdentity(peerID, publicKey, fingerprint)\n/// \n/// // Update social identity\n/// manager.updateSocialIdentity(fingerprint, nickname, trustLevel)\n/// \n/// // Query identity\n/// let identity = manager.resolvePeerIdentity(peerID)\n/// ```\n///\n/// ## Performance Optimizations\n/// - In-memory cache eliminates Keychain roundtrips\n/// - Debounced saves reduce I/O operations\n/// - Efficient data structures for lookups\n/// - Background queue for expensive operations\n///\n/// ## Privacy Considerations\n/// - Users can disable all persistence\n/// - Identity cache can be wiped instantly\n/// - No analytics or telemetry\n/// - Ephemeral mode for high-risk users\n///\n/// ## Future Enhancements\n/// - Selective identity export\n/// - Cross-device identity sync (optional)\n/// - Identity attestation support\n/// - Advanced conflict resolution\n///\n\nimport Foundation\nimport CryptoKit\n\n/// Singleton manager for secure identity state persistence and retrieval.\n/// Provides thread-safe access to identity mappings with encryption at rest.\n/// All identity data is stored encrypted in the device Keychain for security.\nclass SecureIdentityStateManager {\n static let shared = SecureIdentityStateManager()\n \n private let keychain = KeychainManager.shared\n private let cacheKey = \"bitchat.identityCache.v2\"\n private let encryptionKeyName = \"identityCacheEncryptionKey\"\n \n // In-memory state\n private var ephemeralSessions: [String: EphemeralIdentity] = [:]\n private var cryptographicIdentities: [String: CryptographicIdentity] = [:]\n private var cache: IdentityCache = IdentityCache()\n \n // Pending actions before handshake\n private var pendingActions: [String: PendingActions] = [:]\n \n // Thread safety\n private let queue = DispatchQueue(label: \"bitchat.identity.state\", attributes: .concurrent)\n \n // Debouncing for keychain saves\n private var saveTimer: Timer?\n private let saveDebounceInterval: TimeInterval = 2.0 // Save at most once every 2 seconds\n private var pendingSave = false\n \n // Encryption key\n private let encryptionKey: SymmetricKey\n \n private init() {\n // Generate or retrieve encryption key from keychain\n let loadedKey: SymmetricKey\n \n // Try to load from keychain\n if let keyData = keychain.getIdentityKey(forKey: encryptionKeyName) {\n loadedKey = SymmetricKey(data: keyData)\n SecureLogger.logKeyOperation(\"load\", keyType: \"identity cache encryption key\", success: true)\n }\n // Generate new key if needed\n else {\n loadedKey = SymmetricKey(size: .bits256)\n let keyData = loadedKey.withUnsafeBytes { Data($0) }\n // Save to keychain\n let saved = keychain.saveIdentityKey(keyData, forKey: encryptionKeyName)\n SecureLogger.logKeyOperation(\"generate\", keyType: \"identity cache encryption key\", success: saved)\n }\n \n self.encryptionKey = loadedKey\n \n // Load identity cache on init\n loadIdentityCache()\n }\n \n // MARK: - Secure Loading/Saving\n \n func loadIdentityCache() {\n guard let encryptedData = keychain.getIdentityKey(forKey: cacheKey) else {\n // No existing cache, start fresh\n return\n }\n \n do {\n let sealedBox = try AES.GCM.SealedBox(combined: encryptedData)\n let decryptedData = try AES.GCM.open(sealedBox, using: encryptionKey)\n cache = try JSONDecoder().decode(IdentityCache.self, from: decryptedData)\n } catch {\n // Log error but continue with empty cache\n SecureLogger.logError(error, context: \"Failed to load identity cache\", category: SecureLogger.security)\n }\n }\n \n deinit {\n // Force save any pending changes\n forceSave()\n }\n \n func saveIdentityCache() {\n // Mark that we need to save\n pendingSave = true\n \n // Cancel any existing timer\n saveTimer?.invalidate()\n \n // Schedule a new save after the debounce interval\n saveTimer = Timer.scheduledTimer(withTimeInterval: saveDebounceInterval, repeats: false) { [weak self] _ in\n self?.performSave()\n }\n }\n \n private func performSave() {\n guard pendingSave else { return }\n pendingSave = false\n \n do {\n let data = try JSONEncoder().encode(cache)\n let sealedBox = try AES.GCM.seal(data, using: encryptionKey)\n let saved = keychain.saveIdentityKey(sealedBox.combined!, forKey: cacheKey)\n if saved {\n SecureLogger.log(\"Identity cache saved to keychain\", category: SecureLogger.security, level: .debug)\n }\n } catch {\n SecureLogger.logError(error, context: \"Failed to save identity cache\", category: SecureLogger.security)\n }\n }\n \n // Force immediate save (for app termination)\n func forceSave() {\n saveTimer?.invalidate()\n if pendingSave {\n performSave()\n }\n }\n \n // MARK: - Identity Resolution\n \n func resolveIdentity(peerID: String, claimedNickname: String) -> IdentityHint {\n queue.sync {\n // Check if we have candidates based on nickname\n if let fingerprints = cache.nicknameIndex[claimedNickname] {\n if fingerprints.count == 1 {\n return .likelyKnown(fingerprint: fingerprints.first!)\n } else {\n return .ambiguous(candidates: fingerprints)\n }\n }\n return .unknown\n }\n }\n \n // MARK: - Social Identity Management\n \n func getSocialIdentity(for fingerprint: String) -> SocialIdentity? {\n queue.sync {\n return cache.socialIdentities[fingerprint]\n }\n }\n \n func getAllSocialIdentities() -> [SocialIdentity] {\n queue.sync {\n return Array(cache.socialIdentities.values)\n }\n }\n \n func updateSocialIdentity(_ identity: SocialIdentity) {\n queue.async(flags: .barrier) {\n self.cache.socialIdentities[identity.fingerprint] = identity\n \n // Update nickname index\n if let existingIdentity = self.cache.socialIdentities[identity.fingerprint] {\n // Remove old nickname from index if changed\n if existingIdentity.claimedNickname != identity.claimedNickname {\n self.cache.nicknameIndex[existingIdentity.claimedNickname]?.remove(identity.fingerprint)\n if self.cache.nicknameIndex[existingIdentity.claimedNickname]?.isEmpty == true {\n self.cache.nicknameIndex.removeValue(forKey: existingIdentity.claimedNickname)\n }\n }\n }\n \n // Add new nickname to index\n if self.cache.nicknameIndex[identity.claimedNickname] == nil {\n self.cache.nicknameIndex[identity.claimedNickname] = Set()\n }\n self.cache.nicknameIndex[identity.claimedNickname]?.insert(identity.fingerprint)\n \n // Save to keychain\n self.saveIdentityCache()\n }\n }\n \n // MARK: - Favorites Management\n \n func getFavorites() -> Set {\n queue.sync {\n let favorites = cache.socialIdentities.values\n .filter { $0.isFavorite }\n .map { $0.fingerprint }\n return Set(favorites)\n }\n }\n \n func setFavorite(_ fingerprint: String, isFavorite: Bool) {\n queue.async(flags: .barrier) {\n if var identity = self.cache.socialIdentities[fingerprint] {\n identity.isFavorite = isFavorite\n self.cache.socialIdentities[fingerprint] = identity\n } else {\n // Create new social identity for this fingerprint\n let newIdentity = SocialIdentity(\n fingerprint: fingerprint,\n localPetname: nil,\n claimedNickname: \"Unknown\",\n trustLevel: .unknown,\n isFavorite: isFavorite,\n isBlocked: false,\n notes: nil\n )\n self.cache.socialIdentities[fingerprint] = newIdentity\n }\n self.saveIdentityCache()\n }\n }\n \n func isFavorite(fingerprint: String) -> Bool {\n queue.sync {\n return cache.socialIdentities[fingerprint]?.isFavorite ?? false\n }\n }\n \n // MARK: - Blocked Users Management\n \n func isBlocked(fingerprint: String) -> Bool {\n queue.sync {\n return cache.socialIdentities[fingerprint]?.isBlocked ?? false\n }\n }\n \n func setBlocked(_ fingerprint: String, isBlocked: Bool) {\n SecureLogger.log(\"User \\(isBlocked ? \"blocked\" : \"unblocked\"): \\(fingerprint)\", category: SecureLogger.security, level: .info)\n \n queue.async(flags: .barrier) {\n if var identity = self.cache.socialIdentities[fingerprint] {\n identity.isBlocked = isBlocked\n if isBlocked {\n identity.isFavorite = false // Can't be both favorite and blocked\n }\n self.cache.socialIdentities[fingerprint] = identity\n } else {\n // Create new social identity for this fingerprint\n let newIdentity = SocialIdentity(\n fingerprint: fingerprint,\n localPetname: nil,\n claimedNickname: \"Unknown\",\n trustLevel: .unknown,\n isFavorite: false,\n isBlocked: isBlocked,\n notes: nil\n )\n self.cache.socialIdentities[fingerprint] = newIdentity\n }\n self.saveIdentityCache()\n }\n }\n \n // MARK: - Ephemeral Session Management\n \n func registerEphemeralSession(peerID: String, handshakeState: HandshakeState = .none) {\n queue.async(flags: .barrier) {\n self.ephemeralSessions[peerID] = EphemeralIdentity(\n peerID: peerID,\n sessionStart: Date(),\n handshakeState: handshakeState\n )\n }\n }\n \n func updateHandshakeState(peerID: String, state: HandshakeState) {\n queue.async(flags: .barrier) {\n self.ephemeralSessions[peerID]?.handshakeState = state\n \n // If handshake completed, update last interaction\n if case .completed(let fingerprint) = state {\n self.cache.lastInteractions[fingerprint] = Date()\n self.saveIdentityCache()\n }\n }\n }\n \n func getHandshakeState(peerID: String) -> HandshakeState? {\n queue.sync {\n return ephemeralSessions[peerID]?.handshakeState\n }\n }\n \n // MARK: - Pending Actions\n \n func setPendingAction(peerID: String, action: PendingActions) {\n queue.async(flags: .barrier) {\n self.pendingActions[peerID] = action\n }\n }\n \n func applyPendingActions(peerID: String, fingerprint: String) {\n queue.async(flags: .barrier) {\n guard let actions = self.pendingActions[peerID] else { return }\n \n // Get or create social identity\n var identity = self.cache.socialIdentities[fingerprint] ?? SocialIdentity(\n fingerprint: fingerprint,\n localPetname: nil,\n claimedNickname: \"Unknown\",\n trustLevel: .unknown,\n isFavorite: false,\n isBlocked: false,\n notes: nil\n )\n \n // Apply pending actions\n if let toggleFavorite = actions.toggleFavorite {\n identity.isFavorite = toggleFavorite\n }\n if let trustLevel = actions.setTrustLevel {\n identity.trustLevel = trustLevel\n }\n if let petname = actions.setPetname {\n identity.localPetname = petname\n }\n \n // Save updated identity\n self.cache.socialIdentities[fingerprint] = identity\n self.pendingActions.removeValue(forKey: peerID)\n self.saveIdentityCache()\n }\n }\n \n // MARK: - Cleanup\n \n func clearAllIdentityData() {\n SecureLogger.log(\"Clearing all identity data\", category: SecureLogger.security, level: .warning)\n \n queue.async(flags: .barrier) {\n self.cache = IdentityCache()\n self.ephemeralSessions.removeAll()\n self.cryptographicIdentities.removeAll()\n self.pendingActions.removeAll()\n \n // Delete from keychain\n let deleted = self.keychain.deleteIdentityKey(forKey: self.cacheKey)\n SecureLogger.logKeyOperation(\"delete\", keyType: \"identity cache\", success: deleted)\n }\n }\n \n func removeEphemeralSession(peerID: String) {\n queue.async(flags: .barrier) {\n self.ephemeralSessions.removeValue(forKey: peerID)\n self.pendingActions.removeValue(forKey: peerID)\n }\n }\n \n // MARK: - Verification\n \n func setVerified(fingerprint: String, verified: Bool) {\n SecureLogger.log(\"Fingerprint \\(verified ? \"verified\" : \"unverified\"): \\(fingerprint)\", category: SecureLogger.security, level: .info)\n \n queue.async(flags: .barrier) {\n if verified {\n self.cache.verifiedFingerprints.insert(fingerprint)\n } else {\n self.cache.verifiedFingerprints.remove(fingerprint)\n }\n \n // Update trust level if social identity exists\n if var identity = self.cache.socialIdentities[fingerprint] {\n identity.trustLevel = verified ? .verified : .casual\n self.cache.socialIdentities[fingerprint] = identity\n }\n \n self.saveIdentityCache()\n }\n }\n \n func isVerified(fingerprint: String) -> Bool {\n queue.sync {\n return cache.verifiedFingerprints.contains(fingerprint)\n }\n }\n \n func getVerifiedFingerprints() -> Set {\n queue.sync {\n return cache.verifiedFingerprints\n }\n }\n}"], ["/bitchat/bitchat/Services/NoiseEncryptionService.swift", "//\n// NoiseEncryptionService.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # NoiseEncryptionService\n///\n/// High-level encryption service that manages Noise Protocol sessions for secure\n/// peer-to-peer communication in BitChat. Acts as the bridge between the transport\n/// layer (BluetoothMeshService) and the cryptographic layer (NoiseProtocol).\n///\n/// ## Overview\n/// This service provides a simplified API for establishing and managing encrypted\n/// channels between peers. It handles:\n/// - Static identity key management\n/// - Session lifecycle (creation, maintenance, teardown)\n/// - Message encryption/decryption\n/// - Peer authentication and fingerprint tracking\n/// - Automatic rekeying for forward secrecy\n///\n/// ## Architecture\n/// The service operates at multiple levels:\n/// 1. **Identity Management**: Persistent Curve25519 keys stored in Keychain\n/// 2. **Session Management**: Per-peer Noise sessions with state tracking\n/// 3. **Message Processing**: Encryption/decryption with proper framing\n/// 4. **Security Features**: Rate limiting, fingerprint verification\n///\n/// ## Key Features\n///\n/// ### Identity Keys\n/// - Static Curve25519 key pair for Noise XX pattern\n/// - Ed25519 signing key pair for additional authentication\n/// - Keys persisted securely in iOS/macOS Keychain\n/// - Fingerprints derived from SHA256 of public keys\n///\n/// ### Session Management\n/// - Lazy session creation (on-demand when sending messages)\n/// - Automatic session recovery after disconnections\n/// - Configurable rekey intervals for forward secrecy\n/// - Graceful handling of simultaneous handshakes\n///\n/// ### Security Properties\n/// - Forward secrecy via ephemeral keys in handshakes\n/// - Mutual authentication via static key exchange\n/// - Protection against replay attacks\n/// - Rate limiting to prevent DoS attacks\n///\n/// ## Encryption Flow\n/// ```\n/// 1. Message arrives for encryption\n/// 2. Check if session exists for peer\n/// 3. If not, initiate Noise handshake\n/// 4. Once established, encrypt message\n/// 5. Add message type header for protocol handling\n/// 6. Return encrypted payload for transmission\n/// ```\n///\n/// ## Integration Points\n/// - **BluetoothMeshService**: Calls this service for all private messages\n/// - **ChatViewModel**: Monitors encryption status for UI indicators\n/// - **NoiseHandshakeCoordinator**: Prevents handshake race conditions\n/// - **KeychainManager**: Secure storage for identity keys\n///\n/// ## Thread Safety\n/// - Concurrent read access via reader-writer queue\n/// - Session operations protected by per-peer queues\n/// - Atomic updates for critical state changes\n///\n/// ## Error Handling\n/// - Graceful fallback for encryption failures\n/// - Clear error messages for debugging\n/// - Automatic retry with exponential backoff\n/// - User notification for critical failures\n///\n/// ## Performance Considerations\n/// - Sessions cached in memory for fast access\n/// - Minimal allocations in hot paths\n/// - Efficient binary message format\n/// - Background queue for CPU-intensive operations\n///\n\nimport Foundation\nimport CryptoKit\nimport os.log\n\n// MARK: - Encryption Status\n\n/// Represents the current encryption status of a peer connection.\n/// Used for UI indicators and decision-making about message handling.\nenum EncryptionStatus: Equatable {\n case none // Failed or incompatible\n case noHandshake // No handshake attempted yet\n case noiseHandshaking // Currently establishing\n case noiseSecured // Established but not verified\n case noiseVerified // Established and verified\n \n var icon: String? { // Made optional to hide icon when no handshake\n switch self {\n case .none:\n return \"lock.slash\" // Failed handshake\n case .noHandshake:\n return nil // No icon when no handshake attempted\n case .noiseHandshaking:\n return \"lock.rotation\"\n case .noiseSecured:\n return \"lock.fill\" // Changed from \"lock\" to \"lock.fill\" for filled lock\n case .noiseVerified:\n return \"lock.shield.fill\" // Changed to filled version for consistency\n }\n }\n \n var description: String {\n switch self {\n case .none:\n return \"Encryption failed\"\n case .noHandshake:\n return \"Not encrypted\"\n case .noiseHandshaking:\n return \"Establishing encryption...\"\n case .noiseSecured:\n return \"Encrypted\"\n case .noiseVerified:\n return \"Encrypted & Verified\"\n }\n }\n}\n\n// MARK: - Noise Encryption Service\n\n/// Manages end-to-end encryption for BitChat using the Noise Protocol Framework.\n/// Provides a high-level API for establishing secure channels between peers,\n/// handling all cryptographic operations transparently.\n/// - Important: This service maintains the device's cryptographic identity\nclass NoiseEncryptionService {\n // Static identity key (persistent across sessions)\n private let staticIdentityKey: Curve25519.KeyAgreement.PrivateKey\n public let staticIdentityPublicKey: Curve25519.KeyAgreement.PublicKey\n \n // Ed25519 signing key (persistent across sessions)\n private let signingKey: Curve25519.Signing.PrivateKey\n public let signingPublicKey: Curve25519.Signing.PublicKey\n \n // Session manager\n private let sessionManager: NoiseSessionManager\n \n // Peer fingerprints (SHA256 hash of static public key)\n private var peerFingerprints: [String: String] = [:] // peerID -> fingerprint\n private var fingerprintToPeerID: [String: String] = [:] // fingerprint -> peerID\n \n // Thread safety\n private let serviceQueue = DispatchQueue(label: \"chat.bitchat.noise.service\", attributes: .concurrent)\n \n // Security components\n private let rateLimiter = NoiseRateLimiter()\n \n // Session maintenance\n private var rekeyTimer: Timer?\n private let rekeyCheckInterval: TimeInterval = 60.0 // Check every minute\n \n // Callbacks\n var onPeerAuthenticated: ((String, String) -> Void)? // peerID, fingerprint\n var onHandshakeRequired: ((String) -> Void)? // peerID needs handshake\n \n init() {\n // Load or create static identity key (ONLY from keychain)\n let loadedKey: Curve25519.KeyAgreement.PrivateKey\n \n // Try to load from keychain\n if let identityData = KeychainManager.shared.getIdentityKey(forKey: \"noiseStaticKey\"),\n let key = try? Curve25519.KeyAgreement.PrivateKey(rawRepresentation: identityData) {\n loadedKey = key\n SecureLogger.logKeyOperation(\"load\", keyType: \"noiseStaticKey\", success: true)\n }\n // If no identity exists, create new one\n else {\n loadedKey = Curve25519.KeyAgreement.PrivateKey()\n let keyData = loadedKey.rawRepresentation\n \n // Save to keychain\n let saved = KeychainManager.shared.saveIdentityKey(keyData, forKey: \"noiseStaticKey\")\n SecureLogger.logKeyOperation(\"create\", keyType: \"noiseStaticKey\", success: saved)\n }\n \n // Now assign the final value\n self.staticIdentityKey = loadedKey\n self.staticIdentityPublicKey = staticIdentityKey.publicKey\n \n // Load or create signing key pair\n let loadedSigningKey: Curve25519.Signing.PrivateKey\n \n // Try to load from keychain\n if let signingData = KeychainManager.shared.getIdentityKey(forKey: \"ed25519SigningKey\"),\n let key = try? Curve25519.Signing.PrivateKey(rawRepresentation: signingData) {\n loadedSigningKey = key\n SecureLogger.logKeyOperation(\"load\", keyType: \"ed25519SigningKey\", success: true)\n }\n // If no signing key exists, create new one\n else {\n loadedSigningKey = Curve25519.Signing.PrivateKey()\n let keyData = loadedSigningKey.rawRepresentation\n \n // Save to keychain\n let saved = KeychainManager.shared.saveIdentityKey(keyData, forKey: \"ed25519SigningKey\")\n SecureLogger.logKeyOperation(\"create\", keyType: \"ed25519SigningKey\", success: saved)\n }\n \n // Now assign the signing keys\n self.signingKey = loadedSigningKey\n self.signingPublicKey = signingKey.publicKey\n \n // Initialize session manager\n self.sessionManager = NoiseSessionManager(localStaticKey: staticIdentityKey)\n \n // Set up session callbacks\n sessionManager.onSessionEstablished = { [weak self] peerID, remoteStaticKey in\n self?.handleSessionEstablished(peerID: peerID, remoteStaticKey: remoteStaticKey)\n }\n \n // Start session maintenance timer\n startRekeyTimer()\n }\n \n // MARK: - Public Interface\n \n /// Get our static public key for sharing\n func getStaticPublicKeyData() -> Data {\n return staticIdentityPublicKey.rawRepresentation\n }\n \n /// Get our signing public key for sharing\n func getSigningPublicKeyData() -> Data {\n return signingPublicKey.rawRepresentation\n }\n \n /// Get our identity fingerprint\n func getIdentityFingerprint() -> String {\n let hash = SHA256.hash(data: staticIdentityPublicKey.rawRepresentation)\n return hash.map { String(format: \"%02x\", $0) }.joined()\n }\n \n /// Get peer's public key data\n func getPeerPublicKeyData(_ peerID: String) -> Data? {\n return sessionManager.getRemoteStaticKey(for: peerID)?.rawRepresentation\n }\n \n /// Clear persistent identity (for panic mode)\n func clearPersistentIdentity() {\n // Clear from keychain\n let deletedStatic = KeychainManager.shared.deleteIdentityKey(forKey: \"noiseStaticKey\")\n let deletedSigning = KeychainManager.shared.deleteIdentityKey(forKey: \"ed25519SigningKey\")\n SecureLogger.logKeyOperation(\"delete\", keyType: \"identity keys\", success: deletedStatic && deletedSigning)\n SecureLogger.log(\"Panic mode activated - identity cleared\", category: SecureLogger.security, level: .warning)\n // Stop rekey timer\n stopRekeyTimer()\n }\n \n /// Sign data with our Ed25519 signing key\n func signData(_ data: Data) -> Data? {\n do {\n let signature = try signingKey.signature(for: data)\n return signature\n } catch {\n SecureLogger.logError(error, context: \"Failed to sign data\", category: SecureLogger.noise)\n return nil\n }\n }\n \n /// Verify signature with a peer's Ed25519 public key\n func verifySignature(_ signature: Data, for data: Data, publicKey: Data) -> Bool {\n do {\n let signingPublicKey = try Curve25519.Signing.PublicKey(rawRepresentation: publicKey)\n return signingPublicKey.isValidSignature(signature, for: data)\n } catch {\n SecureLogger.logError(error, context: \"Failed to verify signature\", category: SecureLogger.noise)\n return false\n }\n }\n \n // MARK: - Handshake Management\n \n /// Initiate a Noise handshake with a peer\n func initiateHandshake(with peerID: String) throws -> Data {\n \n // Validate peer ID\n guard NoiseSecurityValidator.validatePeerID(peerID) else {\n SecureLogger.logSecurityEvent(.authenticationFailed(peerID: peerID), level: .warning)\n throw NoiseSecurityError.invalidPeerID\n }\n \n // Check rate limit\n guard rateLimiter.allowHandshake(from: peerID) else {\n SecureLogger.logSecurityEvent(.authenticationFailed(peerID: \"Rate limited: \\(peerID)\"), level: .warning)\n throw NoiseSecurityError.rateLimitExceeded\n }\n \n SecureLogger.logSecurityEvent(.handshakeStarted(peerID: peerID))\n \n // Return raw handshake data without wrapper\n // The Noise protocol handles its own message format\n let handshakeData = try sessionManager.initiateHandshake(with: peerID)\n return handshakeData\n }\n \n /// Process an incoming handshake message\n func processHandshakeMessage(from peerID: String, message: Data) throws -> Data? {\n \n // Validate peer ID\n guard NoiseSecurityValidator.validatePeerID(peerID) else {\n SecureLogger.logSecurityEvent(.authenticationFailed(peerID: peerID), level: .warning)\n throw NoiseSecurityError.invalidPeerID\n }\n \n // Validate message size\n guard NoiseSecurityValidator.validateHandshakeMessageSize(message) else {\n SecureLogger.logSecurityEvent(.handshakeFailed(peerID: peerID, error: \"Message too large\"), level: .warning)\n throw NoiseSecurityError.messageTooLarge\n }\n \n // Check rate limit\n guard rateLimiter.allowHandshake(from: peerID) else {\n SecureLogger.logSecurityEvent(.authenticationFailed(peerID: \"Rate limited: \\(peerID)\"), level: .warning)\n throw NoiseSecurityError.rateLimitExceeded\n }\n \n // For handshakes, we process the raw data directly without NoiseMessage wrapper\n // The Noise protocol handles its own message format\n let responsePayload = try sessionManager.handleIncomingHandshake(from: peerID, message: message)\n \n \n // Return raw response without wrapper\n return responsePayload\n }\n \n /// Check if we have an established session with a peer\n func hasEstablishedSession(with peerID: String) -> Bool {\n return sessionManager.getSession(for: peerID)?.isEstablished() ?? false\n }\n \n /// Check if we have a session (established or handshaking) with a peer\n func hasSession(with peerID: String) -> Bool {\n return sessionManager.getSession(for: peerID) != nil\n }\n \n // MARK: - Encryption/Decryption\n \n /// Encrypt data for a specific peer\n func encrypt(_ data: Data, for peerID: String) throws -> Data {\n // Validate message size\n guard NoiseSecurityValidator.validateMessageSize(data) else {\n throw NoiseSecurityError.messageTooLarge\n }\n \n // Check rate limit\n guard rateLimiter.allowMessage(from: peerID) else {\n throw NoiseSecurityError.rateLimitExceeded\n }\n \n // Check if we have an established session\n guard hasEstablishedSession(with: peerID) else {\n // Signal that handshake is needed\n onHandshakeRequired?(peerID)\n throw NoiseEncryptionError.handshakeRequired\n }\n \n return try sessionManager.encrypt(data, for: peerID)\n }\n \n /// Decrypt data from a specific peer\n func decrypt(_ data: Data, from peerID: String) throws -> Data {\n // Validate message size\n guard NoiseSecurityValidator.validateMessageSize(data) else {\n throw NoiseSecurityError.messageTooLarge\n }\n \n // Check rate limit\n guard rateLimiter.allowMessage(from: peerID) else {\n throw NoiseSecurityError.rateLimitExceeded\n }\n \n // Check if we have an established session\n guard hasEstablishedSession(with: peerID) else {\n throw NoiseEncryptionError.sessionNotEstablished\n }\n \n return try sessionManager.decrypt(data, from: peerID)\n }\n \n // MARK: - Peer Management\n \n /// Get fingerprint for a peer\n func getPeerFingerprint(_ peerID: String) -> String? {\n return serviceQueue.sync {\n return peerFingerprints[peerID]\n }\n }\n \n /// Get peer ID for a fingerprint\n func getPeerID(for fingerprint: String) -> String? {\n return serviceQueue.sync {\n return fingerprintToPeerID[fingerprint]\n }\n }\n \n /// Remove a peer session\n func removePeer(_ peerID: String) {\n sessionManager.removeSession(for: peerID)\n \n serviceQueue.sync(flags: .barrier) {\n if let fingerprint = peerFingerprints[peerID] {\n fingerprintToPeerID.removeValue(forKey: fingerprint)\n }\n peerFingerprints.removeValue(forKey: peerID)\n }\n \n SecureLogger.logSecurityEvent(.sessionExpired(peerID: peerID))\n }\n \n /// Migrate session when peer ID changes\n func migratePeerSession(from oldPeerID: String, to newPeerID: String, fingerprint: String) {\n // First update the fingerprint mappings\n serviceQueue.sync(flags: .barrier) {\n // Remove old mapping\n if let oldFingerprint = peerFingerprints[oldPeerID], oldFingerprint == fingerprint {\n peerFingerprints.removeValue(forKey: oldPeerID)\n }\n \n // Add new mapping\n peerFingerprints[newPeerID] = fingerprint\n fingerprintToPeerID[fingerprint] = newPeerID\n }\n \n // Migrate the session in session manager\n sessionManager.migrateSession(from: oldPeerID, to: newPeerID)\n }\n \n // MARK: - Private Helpers\n \n private func handleSessionEstablished(peerID: String, remoteStaticKey: Curve25519.KeyAgreement.PublicKey) {\n // Calculate fingerprint\n let fingerprint = calculateFingerprint(for: remoteStaticKey)\n \n // Store fingerprint mapping\n serviceQueue.sync(flags: .barrier) {\n peerFingerprints[peerID] = fingerprint\n fingerprintToPeerID[fingerprint] = peerID\n }\n \n // Log security event\n SecureLogger.logSecurityEvent(.handshakeCompleted(peerID: peerID))\n \n // Notify about authentication\n onPeerAuthenticated?(peerID, fingerprint)\n }\n \n private func calculateFingerprint(for publicKey: Curve25519.KeyAgreement.PublicKey) -> String {\n let hash = SHA256.hash(data: publicKey.rawRepresentation)\n return hash.map { String(format: \"%02x\", $0) }.joined()\n }\n \n // MARK: - Session Maintenance\n \n private func startRekeyTimer() {\n rekeyTimer = Timer.scheduledTimer(withTimeInterval: rekeyCheckInterval, repeats: true) { [weak self] _ in\n self?.checkSessionsForRekey()\n }\n }\n \n private func stopRekeyTimer() {\n rekeyTimer?.invalidate()\n rekeyTimer = nil\n }\n \n private func checkSessionsForRekey() {\n let sessionsNeedingRekey = sessionManager.getSessionsNeedingRekey()\n \n for (peerID, needsRekey) in sessionsNeedingRekey where needsRekey {\n \n // Attempt to rekey the session\n do {\n try sessionManager.initiateRekey(for: peerID)\n SecureLogger.log(\"Key rotation initiated for peer: \\(peerID)\", category: SecureLogger.security, level: .info)\n \n // Signal that handshake is needed\n onHandshakeRequired?(peerID)\n } catch {\n SecureLogger.logError(error, context: \"Failed to initiate rekey for peer: \\(peerID)\", category: SecureLogger.session)\n }\n }\n }\n \n deinit {\n stopRekeyTimer()\n }\n}\n\n// MARK: - Protocol Message Types for Noise\n\n/// Message types for the Noise encryption protocol layer.\n/// These types wrap the underlying BitChat protocol messages with encryption metadata.\nenum NoiseMessageType: UInt8 {\n case handshakeInitiation = 0x10\n case handshakeResponse = 0x11\n case handshakeFinal = 0x12\n case encryptedMessage = 0x13\n case sessionRenegotiation = 0x14\n}\n\n// MARK: - Noise Message Wrapper\n\n/// Container for encrypted messages in the Noise protocol.\n/// Provides versioning and type information for proper message handling.\n/// The actual message content is encrypted in the payload field.\nstruct NoiseMessage: Codable {\n let type: UInt8\n let sessionID: String // Random ID for this handshake session\n let payload: Data\n \n init(type: NoiseMessageType, sessionID: String, payload: Data) {\n self.type = type.rawValue\n self.sessionID = sessionID\n self.payload = payload\n }\n \n func encode() -> Data? {\n do {\n let encoded = try JSONEncoder().encode(self)\n return encoded\n } catch {\n return nil\n }\n }\n \n static func decode(from data: Data) -> NoiseMessage? {\n return try? JSONDecoder().decode(NoiseMessage.self, from: data)\n }\n \n static func decodeWithError(from data: Data) -> NoiseMessage? {\n do {\n let decoded = try JSONDecoder().decode(NoiseMessage.self, from: data)\n return decoded\n } catch {\n return nil\n }\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUInt8(type)\n data.appendUUID(sessionID)\n data.appendData(payload)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> NoiseMessage? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n var offset = 0\n \n guard let type = dataCopy.readUInt8(at: &offset),\n let sessionID = dataCopy.readUUID(at: &offset),\n let payload = dataCopy.readData(at: &offset) else { return nil }\n \n guard let messageType = NoiseMessageType(rawValue: type) else { return nil }\n \n return NoiseMessage(type: messageType, sessionID: sessionID, payload: payload)\n }\n}\n\n// MARK: - Errors\n\nenum NoiseEncryptionError: Error {\n case handshakeRequired\n case sessionNotEstablished\n}\n"], ["/bitchat/bitchat/BitchatApp.swift", "//\n// BitchatApp.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport SwiftUI\nimport UserNotifications\n\n@main\nstruct BitchatApp: App {\n @StateObject private var chatViewModel = ChatViewModel()\n #if os(iOS)\n @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate\n #elseif os(macOS)\n @NSApplicationDelegateAdaptor(MacAppDelegate.self) var appDelegate\n #endif\n \n init() {\n UNUserNotificationCenter.current().delegate = NotificationDelegate.shared\n }\n \n var body: some Scene {\n WindowGroup {\n ContentView()\n .environmentObject(chatViewModel)\n .onAppear {\n NotificationDelegate.shared.chatViewModel = chatViewModel\n #if os(iOS)\n appDelegate.chatViewModel = chatViewModel\n #elseif os(macOS)\n appDelegate.chatViewModel = chatViewModel\n #endif\n // Check for shared content\n checkForSharedContent()\n }\n .onOpenURL { url in\n handleURL(url)\n }\n #if os(iOS)\n .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in\n // Check for shared content when app becomes active\n checkForSharedContent()\n }\n #endif\n }\n #if os(macOS)\n .windowStyle(.hiddenTitleBar)\n .windowResizability(.contentSize)\n #endif\n }\n \n private func handleURL(_ url: URL) {\n if url.scheme == \"bitchat\" && url.host == \"share\" {\n // Handle shared content\n checkForSharedContent()\n }\n }\n \n private func checkForSharedContent() {\n // Check app group for shared content from extension\n guard let userDefaults = UserDefaults(suiteName: \"group.chat.bitchat\") else {\n return\n }\n \n guard let sharedContent = userDefaults.string(forKey: \"sharedContent\"),\n let sharedDate = userDefaults.object(forKey: \"sharedContentDate\") as? Date else {\n return\n }\n \n // Only process if shared within last 30 seconds\n if Date().timeIntervalSince(sharedDate) < 30 {\n let contentType = userDefaults.string(forKey: \"sharedContentType\") ?? \"text\"\n \n // Clear the shared content\n userDefaults.removeObject(forKey: \"sharedContent\")\n userDefaults.removeObject(forKey: \"sharedContentType\")\n userDefaults.removeObject(forKey: \"sharedContentDate\")\n userDefaults.synchronize()\n \n // Show notification about shared content\n DispatchQueue.main.async {\n // Add system message about sharing\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"preparing to share \\(contentType)...\",\n timestamp: Date(),\n isRelay: false\n )\n self.chatViewModel.messages.append(systemMessage)\n }\n \n // Send the shared content after a short delay\n DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {\n if contentType == \"url\" {\n // Try to parse as JSON first\n if let data = sharedContent.data(using: .utf8),\n let urlData = try? JSONSerialization.jsonObject(with: data) as? [String: String],\n let url = urlData[\"url\"] {\n // Send plain URL\n self.chatViewModel.sendMessage(url)\n } else {\n // Fallback to simple URL\n self.chatViewModel.sendMessage(sharedContent)\n }\n } else {\n self.chatViewModel.sendMessage(sharedContent)\n }\n }\n }\n }\n}\n\n#if os(iOS)\nclass AppDelegate: NSObject, UIApplicationDelegate {\n weak var chatViewModel: ChatViewModel?\n \n func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {\n return true\n }\n}\n#endif\n\n#if os(macOS)\nimport AppKit\n\nclass MacAppDelegate: NSObject, NSApplicationDelegate {\n weak var chatViewModel: ChatViewModel?\n \n func applicationWillTerminate(_ notification: Notification) {\n chatViewModel?.applicationWillTerminate()\n }\n \n func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {\n return true\n }\n}\n#endif\n\nclass NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {\n static let shared = NotificationDelegate()\n weak var chatViewModel: ChatViewModel?\n \n func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {\n let identifier = response.notification.request.identifier\n let userInfo = response.notification.request.content.userInfo\n \n // Check if this is a private message notification\n if identifier.hasPrefix(\"private-\") {\n // Get peer ID from userInfo\n if let peerID = userInfo[\"peerID\"] as? String {\n DispatchQueue.main.async {\n self.chatViewModel?.startPrivateChat(with: peerID)\n }\n }\n }\n \n completionHandler()\n }\n \n func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {\n let identifier = notification.request.identifier\n let userInfo = notification.request.content.userInfo\n \n // Check if this is a private message notification\n if identifier.hasPrefix(\"private-\") {\n // Get peer ID from userInfo\n if let peerID = userInfo[\"peerID\"] as? String {\n // Don't show notification if the private chat is already open\n if chatViewModel?.selectedPrivateChatPeer == peerID {\n completionHandler([])\n return\n }\n }\n }\n \n // Show notification in all other cases\n completionHandler([.banner, .sound])\n }\n}\n\nextension String {\n var nilIfEmpty: String? {\n self.isEmpty ? nil : self\n }\n}"], ["/bitchat/bitchat/Services/MessageRetryService.swift", "//\n// MessageRetryService.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport Combine\nimport CryptoKit\n\nstruct RetryableMessage {\n let id: String\n let originalMessageID: String? \n let originalTimestamp: Date?\n let content: String\n let mentions: [String]?\n let isPrivate: Bool\n let recipientPeerID: String?\n let recipientNickname: String?\n let retryCount: Int\n let maxRetries: Int = 3\n let nextRetryTime: Date\n}\n\nclass MessageRetryService {\n static let shared = MessageRetryService()\n \n private var retryQueue: [RetryableMessage] = []\n private var retryTimer: Timer?\n private let retryInterval: TimeInterval = 2.0 // Retry every 2 seconds for faster sync\n private let maxQueueSize = 50\n \n weak var meshService: BluetoothMeshService?\n \n private init() {\n startRetryTimer()\n }\n \n deinit {\n retryTimer?.invalidate()\n }\n \n private func startRetryTimer() {\n retryTimer = Timer.scheduledTimer(withTimeInterval: retryInterval, repeats: true) { [weak self] _ in\n self?.processRetryQueue()\n }\n }\n \n func addMessageForRetry(\n content: String,\n mentions: [String]? = nil,\n isPrivate: Bool = false,\n recipientPeerID: String? = nil,\n recipientNickname: String? = nil,\n originalMessageID: String? = nil,\n originalTimestamp: Date? = nil\n ) {\n // Don't queue empty or whitespace-only messages\n guard !content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {\n return\n }\n \n // Don't queue if we're at capacity\n guard retryQueue.count < maxQueueSize else {\n return\n }\n \n // Check if this message is already in the queue\n if let messageID = originalMessageID {\n let alreadyQueued = retryQueue.contains { msg in\n msg.originalMessageID == messageID\n }\n if alreadyQueued {\n return // Don't add duplicate\n }\n }\n \n let retryMessage = RetryableMessage(\n id: UUID().uuidString,\n originalMessageID: originalMessageID,\n originalTimestamp: originalTimestamp,\n content: content,\n mentions: mentions,\n isPrivate: isPrivate,\n recipientPeerID: recipientPeerID,\n recipientNickname: recipientNickname,\n retryCount: 0,\n nextRetryTime: Date().addingTimeInterval(retryInterval)\n )\n \n retryQueue.append(retryMessage)\n \n // Sort the queue by original timestamp to maintain message order\n retryQueue.sort { (msg1, msg2) in\n let time1 = msg1.originalTimestamp ?? Date.distantPast\n let time2 = msg2.originalTimestamp ?? Date.distantPast\n return time1 < time2\n }\n }\n \n private func processRetryQueue() {\n guard meshService != nil else { return }\n \n let now = Date()\n var messagesToRetry: [RetryableMessage] = []\n var updatedQueue: [RetryableMessage] = []\n \n for message in retryQueue {\n if message.nextRetryTime <= now {\n messagesToRetry.append(message)\n } else {\n updatedQueue.append(message)\n }\n }\n \n retryQueue = updatedQueue\n \n // Sort messages by original timestamp to maintain order\n messagesToRetry.sort { (msg1, msg2) in\n let time1 = msg1.originalTimestamp ?? Date.distantPast\n let time2 = msg2.originalTimestamp ?? Date.distantPast\n return time1 < time2\n }\n \n // Send messages with delay to maintain order\n for (index, message) in messagesToRetry.enumerated() {\n // Check if we should still retry\n if message.retryCount >= message.maxRetries {\n continue\n }\n \n // Add delay between messages to ensure proper ordering\n let delay = Double(index) * 0.05 // 50ms between messages\n \n DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in\n guard let self = self,\n let meshService = self.meshService else { return }\n \n // Check connectivity before retrying\n let viewModel = meshService.delegate as? ChatViewModel\n let connectedPeers = viewModel?.connectedPeers ?? []\n \n if message.isPrivate {\n // For private messages, check if recipient is connected\n if let recipientID = message.recipientPeerID,\n connectedPeers.contains(recipientID) {\n // Retry private message\n meshService.sendPrivateMessage(\n message.content,\n to: recipientID,\n recipientNickname: message.recipientNickname ?? \"unknown\",\n messageID: message.originalMessageID\n )\n } else {\n // Recipient not connected, keep in queue with updated retry time\n var updatedMessage = message\n updatedMessage = RetryableMessage(\n id: message.id,\n originalMessageID: message.originalMessageID,\n originalTimestamp: message.originalTimestamp,\n content: message.content,\n mentions: message.mentions,\n isPrivate: message.isPrivate,\n recipientPeerID: message.recipientPeerID,\n recipientNickname: message.recipientNickname,\n retryCount: message.retryCount + 1,\n nextRetryTime: Date().addingTimeInterval(self.retryInterval * Double(message.retryCount + 2))\n )\n self.retryQueue.append(updatedMessage)\n }\n } else {\n // Regular message\n if !connectedPeers.isEmpty {\n meshService.sendMessage(\n message.content,\n mentions: message.mentions ?? [],\n to: nil,\n messageID: message.originalMessageID,\n timestamp: message.originalTimestamp\n )\n } else {\n // No peers connected, keep in queue\n var updatedMessage = message\n updatedMessage = RetryableMessage(\n id: message.id,\n originalMessageID: message.originalMessageID,\n originalTimestamp: message.originalTimestamp,\n content: message.content,\n mentions: message.mentions,\n isPrivate: message.isPrivate,\n recipientPeerID: message.recipientPeerID,\n recipientNickname: message.recipientNickname,\n retryCount: message.retryCount + 1,\n nextRetryTime: Date().addingTimeInterval(self.retryInterval * Double(message.retryCount + 2))\n )\n self.retryQueue.append(updatedMessage)\n }\n }\n }\n }\n }\n \n func clearRetryQueue() {\n retryQueue.removeAll()\n }\n \n func getRetryQueueCount() -> Int {\n return retryQueue.count\n }\n}\n"], ["/bitchat/bitchat/Services/DeliveryTracker.swift", "//\n// DeliveryTracker.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport Combine\n\nclass DeliveryTracker {\n static let shared = DeliveryTracker()\n \n // Track pending deliveries\n private var pendingDeliveries: [String: PendingDelivery] = [:]\n private let pendingLock = NSLock()\n \n // Track received ACKs to prevent duplicates\n private var receivedAckIDs = Set()\n private var sentAckIDs = Set()\n \n // Timeout configuration\n private let privateMessageTimeout: TimeInterval = 120 // 2 minutes\n private let roomMessageTimeout: TimeInterval = 180 // 3 minutes\n private let favoriteTimeout: TimeInterval = 600 // 10 minutes for favorites\n \n // Retry configuration\n private let maxRetries = 3\n private let retryDelay: TimeInterval = 5 // Base retry delay\n \n // Publishers for UI updates\n let deliveryStatusUpdated = PassthroughSubject<(messageID: String, status: DeliveryStatus), Never>()\n \n // Cleanup timer\n private var cleanupTimer: Timer?\n \n struct PendingDelivery {\n let messageID: String\n let sentAt: Date\n let recipientID: String\n let recipientNickname: String\n let retryCount: Int\n let isFavorite: Bool\n var timeoutTimer: Timer?\n \n var isTimedOut: Bool {\n let timeout: TimeInterval = isFavorite ? 300 : 30\n return Date().timeIntervalSince(sentAt) > timeout\n }\n \n var shouldRetry: Bool {\n return retryCount < 3 && isFavorite\n }\n }\n \n private init() {\n startCleanupTimer()\n }\n \n deinit {\n cleanupTimer?.invalidate()\n }\n \n // MARK: - Public Methods\n \n func trackMessage(_ message: BitchatMessage, recipientID: String, recipientNickname: String, isFavorite: Bool = false, expectedRecipients: Int = 1) {\n // Only track private messages\n guard message.isPrivate else { return }\n \n SecureLogger.log(\"Tracking message \\(message.id) - private: \\(message.isPrivate), recipient: \\(recipientNickname)\", category: SecureLogger.session, level: .info)\n \n \n let delivery = PendingDelivery(\n messageID: message.id,\n sentAt: Date(),\n recipientID: recipientID,\n recipientNickname: recipientNickname,\n retryCount: 0,\n isFavorite: isFavorite,\n timeoutTimer: nil\n )\n \n // Store the delivery with lock\n pendingLock.lock()\n pendingDeliveries[message.id] = delivery\n pendingLock.unlock()\n \n // Update status to sent (only if not already delivered)\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in\n guard let self = self else { return }\n \n self.pendingLock.lock()\n let stillPending = self.pendingDeliveries[message.id] != nil\n self.pendingLock.unlock()\n \n // Only update to sent if still pending (not already delivered)\n if stillPending {\n SecureLogger.log(\"Updating message \\(message.id) to sent status (still pending)\", category: SecureLogger.session, level: .debug)\n self.updateDeliveryStatus(message.id, status: .sent)\n } else {\n SecureLogger.log(\"Skipping sent status update for \\(message.id) - already delivered\", category: SecureLogger.session, level: .debug)\n }\n }\n \n // Schedule timeout (outside of lock)\n scheduleTimeout(for: message.id)\n }\n \n func processDeliveryAck(_ ack: DeliveryAck) {\n pendingLock.lock()\n defer { pendingLock.unlock() }\n \n SecureLogger.log(\"Processing delivery ACK for message \\(ack.originalMessageID) from \\(ack.recipientNickname)\", category: SecureLogger.session, level: .info)\n \n // Prevent duplicate ACK processing\n guard !receivedAckIDs.contains(ack.ackID) else {\n SecureLogger.log(\"Duplicate ACK \\(ack.ackID) - ignoring\", category: SecureLogger.session, level: .warning)\n return\n }\n receivedAckIDs.insert(ack.ackID)\n \n // Find the pending delivery\n guard let delivery = pendingDeliveries[ack.originalMessageID] else {\n // Message might have already been delivered or timed out\n SecureLogger.log(\"No pending delivery found for message \\(ack.originalMessageID)\", category: SecureLogger.session, level: .warning)\n return\n }\n \n // Cancel timeout timer\n delivery.timeoutTimer?.invalidate()\n \n // Direct message - mark as delivered\n SecureLogger.log(\"Marking private message \\(ack.originalMessageID) as delivered to \\(ack.recipientNickname)\", category: SecureLogger.session, level: .info)\n updateDeliveryStatus(ack.originalMessageID, status: .delivered(to: ack.recipientNickname, at: Date()))\n pendingDeliveries.removeValue(forKey: ack.originalMessageID)\n }\n \n func generateAck(for message: BitchatMessage, myPeerID: String, myNickname: String, hopCount: UInt8) -> DeliveryAck? {\n // Don't ACK our own messages\n guard message.senderPeerID != myPeerID else { \n return nil \n }\n \n // Only ACK private messages\n guard message.isPrivate else { \n return nil \n }\n \n // Don't ACK if we've already sent an ACK for this message\n guard !sentAckIDs.contains(message.id) else { \n return nil \n }\n sentAckIDs.insert(message.id)\n \n \n return DeliveryAck(\n originalMessageID: message.id,\n recipientID: myPeerID,\n recipientNickname: myNickname,\n hopCount: hopCount\n )\n }\n \n func clearDeliveryStatus(for messageID: String) {\n pendingLock.lock()\n defer { pendingLock.unlock() }\n \n if let delivery = pendingDeliveries[messageID] {\n delivery.timeoutTimer?.invalidate()\n }\n pendingDeliveries.removeValue(forKey: messageID)\n }\n \n // MARK: - Private Methods\n \n private func updateDeliveryStatus(_ messageID: String, status: DeliveryStatus) {\n SecureLogger.log(\"Updating delivery status for message \\(messageID): \\(status)\", category: SecureLogger.session, level: .debug)\n DispatchQueue.main.async { [weak self] in\n self?.deliveryStatusUpdated.send((messageID: messageID, status: status))\n }\n }\n \n private func scheduleTimeout(for messageID: String) {\n // Get delivery info with lock\n pendingLock.lock()\n guard let delivery = pendingDeliveries[messageID] else {\n pendingLock.unlock()\n return\n }\n let isFavorite = delivery.isFavorite\n pendingLock.unlock()\n \n let timeout = isFavorite ? favoriteTimeout : privateMessageTimeout\n \n let timer = Timer.scheduledTimer(withTimeInterval: timeout, repeats: false) { [weak self] _ in\n self?.handleTimeout(messageID: messageID)\n }\n \n pendingLock.lock()\n if var updatedDelivery = pendingDeliveries[messageID] {\n updatedDelivery.timeoutTimer = timer\n pendingDeliveries[messageID] = updatedDelivery\n }\n pendingLock.unlock()\n }\n \n private func handleTimeout(messageID: String) {\n pendingLock.lock()\n guard let delivery = pendingDeliveries[messageID] else {\n pendingLock.unlock()\n return\n }\n \n let shouldRetry = delivery.shouldRetry\n \n if shouldRetry {\n pendingLock.unlock()\n // Retry for favorites (outside of lock)\n retryDelivery(messageID: messageID)\n } else {\n // Mark as failed\n let reason = \"Message not delivered\"\n pendingDeliveries.removeValue(forKey: messageID)\n pendingLock.unlock()\n updateDeliveryStatus(messageID, status: .failed(reason: reason))\n }\n }\n \n private func retryDelivery(messageID: String) {\n pendingLock.lock()\n guard let delivery = pendingDeliveries[messageID] else {\n pendingLock.unlock()\n return\n }\n \n // Increment retry count\n let newDelivery = PendingDelivery(\n messageID: delivery.messageID,\n sentAt: delivery.sentAt,\n recipientID: delivery.recipientID,\n recipientNickname: delivery.recipientNickname,\n retryCount: delivery.retryCount + 1,\n isFavorite: delivery.isFavorite,\n timeoutTimer: nil\n )\n \n pendingDeliveries[messageID] = newDelivery\n let retryCount = delivery.retryCount\n pendingLock.unlock()\n \n // Exponential backoff for retry\n let delay = retryDelay * pow(2, Double(retryCount))\n \n DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in\n // Trigger resend through delegate or notification\n NotificationCenter.default.post(\n name: Notification.Name(\"bitchat.retryMessage\"),\n object: nil,\n userInfo: [\"messageID\": messageID]\n )\n \n // Schedule new timeout\n self?.scheduleTimeout(for: messageID)\n }\n }\n \n private func startCleanupTimer() {\n cleanupTimer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in\n self?.cleanupOldDeliveries()\n }\n }\n \n private func cleanupOldDeliveries() {\n pendingLock.lock()\n defer { pendingLock.unlock() }\n \n let now = Date()\n let maxAge: TimeInterval = 3600 // 1 hour\n \n // Clean up old pending deliveries\n pendingDeliveries = pendingDeliveries.filter { (_, delivery) in\n now.timeIntervalSince(delivery.sentAt) < maxAge\n }\n \n // Clean up old ACK IDs (keep last 1000)\n if receivedAckIDs.count > 1000 {\n receivedAckIDs.removeAll()\n }\n if sentAckIDs.count > 1000 {\n sentAckIDs.removeAll()\n }\n }\n}"], ["/bitchat/bitchat/Views/FingerprintView.swift", "//\n// FingerprintView.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport SwiftUI\n\nstruct FingerprintView: View {\n @ObservedObject var viewModel: ChatViewModel\n let peerID: String\n @Environment(\\.dismiss) var dismiss\n @Environment(\\.colorScheme) var colorScheme\n \n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n private var backgroundColor: Color {\n colorScheme == .dark ? Color.black : Color.white\n }\n \n var body: some View {\n VStack(spacing: 20) {\n // Header\n HStack {\n Text(\"SECURITY VERIFICATION\")\n .font(.system(size: 16, weight: .bold, design: .monospaced))\n .foregroundColor(textColor)\n \n Spacer()\n \n Button(\"DONE\") {\n dismiss()\n }\n .foregroundColor(textColor)\n }\n .padding()\n \n VStack(alignment: .leading, spacing: 16) {\n // Peer info\n let peerNickname = viewModel.meshService.getPeerNicknames()[peerID] ?? \"Unknown\"\n let encryptionStatus = viewModel.getEncryptionStatus(for: peerID)\n \n HStack {\n if let icon = encryptionStatus.icon {\n Image(systemName: icon)\n .font(.system(size: 20))\n .foregroundColor(encryptionStatus == .noiseVerified ? Color.green : textColor)\n }\n \n VStack(alignment: .leading, spacing: 4) {\n Text(peerNickname)\n .font(.system(size: 18, weight: .semibold, design: .monospaced))\n .foregroundColor(textColor)\n \n Text(encryptionStatus.description)\n .font(.system(size: 12, design: .monospaced))\n .foregroundColor(textColor.opacity(0.7))\n }\n \n Spacer()\n }\n .padding()\n .background(Color.gray.opacity(0.1))\n .cornerRadius(8)\n \n // Their fingerprint\n VStack(alignment: .leading, spacing: 8) {\n Text(\"THEIR FINGERPRINT:\")\n .font(.system(size: 12, weight: .bold, design: .monospaced))\n .foregroundColor(textColor.opacity(0.7))\n \n if let fingerprint = viewModel.getFingerprint(for: peerID) {\n Text(formatFingerprint(fingerprint))\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(textColor)\n .multilineTextAlignment(.leading)\n .lineLimit(nil)\n .fixedSize(horizontal: false, vertical: true)\n .padding()\n .frame(maxWidth: .infinity)\n .background(Color.gray.opacity(0.1))\n .cornerRadius(8)\n .contextMenu {\n Button(\"Copy\") {\n #if os(iOS)\n UIPasteboard.general.string = fingerprint\n #else\n NSPasteboard.general.clearContents()\n NSPasteboard.general.setString(fingerprint, forType: .string)\n #endif\n }\n }\n } else {\n Text(\"not available - handshake in progress\")\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(Color.orange)\n .padding()\n }\n }\n \n // My fingerprint\n VStack(alignment: .leading, spacing: 8) {\n Text(\"YOUR FINGERPRINT:\")\n .font(.system(size: 12, weight: .bold, design: .monospaced))\n .foregroundColor(textColor.opacity(0.7))\n \n let myFingerprint = viewModel.getMyFingerprint()\n Text(formatFingerprint(myFingerprint))\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(textColor)\n .multilineTextAlignment(.leading)\n .lineLimit(nil)\n .fixedSize(horizontal: false, vertical: true)\n .padding()\n .frame(maxWidth: .infinity)\n .background(Color.gray.opacity(0.1))\n .cornerRadius(8)\n .contextMenu {\n Button(\"Copy\") {\n #if os(iOS)\n UIPasteboard.general.string = myFingerprint\n #else\n NSPasteboard.general.clearContents()\n NSPasteboard.general.setString(myFingerprint, forType: .string)\n #endif\n }\n }\n }\n \n // Verification status\n if encryptionStatus == .noiseSecured || encryptionStatus == .noiseVerified {\n let isVerified = encryptionStatus == .noiseVerified\n \n VStack(spacing: 12) {\n Text(isVerified ? \"✓ VERIFIED\" : \"⚠️ NOT VERIFIED\")\n .font(.system(size: 14, weight: .bold, design: .monospaced))\n .foregroundColor(isVerified ? Color.green : Color.orange)\n .frame(maxWidth: .infinity)\n \n Text(isVerified ? \n \"you have verified this person's identity.\" :\n \"compare these fingerprints with \\(peerNickname) using a secure channel.\")\n .font(.system(size: 12, design: .monospaced))\n .foregroundColor(textColor.opacity(0.7))\n .multilineTextAlignment(.center)\n .lineLimit(nil)\n .fixedSize(horizontal: false, vertical: true)\n .frame(maxWidth: .infinity)\n \n if !isVerified {\n Button(action: {\n viewModel.verifyFingerprint(for: peerID)\n dismiss()\n }) {\n Text(\"MARK AS VERIFIED\")\n .font(.system(size: 14, weight: .bold, design: .monospaced))\n .foregroundColor(.white)\n .padding(.horizontal, 20)\n .padding(.vertical, 10)\n .background(Color.green)\n .cornerRadius(8)\n }\n .buttonStyle(PlainButtonStyle())\n }\n }\n .padding(.top)\n .frame(maxWidth: .infinity)\n }\n }\n .padding()\n .frame(maxWidth: 500) // Constrain max width for better readability\n \n Spacer()\n }\n .padding()\n .frame(maxWidth: .infinity, maxHeight: .infinity)\n .background(backgroundColor)\n .presentationDetents([.large])\n .presentationDragIndicator(.visible)\n }\n \n private func formatFingerprint(_ fingerprint: String) -> String {\n // Convert to uppercase and format into 4 lines (4 groups of 4 on each line)\n let uppercased = fingerprint.uppercased()\n var formatted = \"\"\n \n for (index, char) in uppercased.enumerated() {\n // Add space every 4 characters (but not at the start)\n if index > 0 && index % 4 == 0 {\n // Add newline after every 16 characters (4 groups of 4)\n if index % 16 == 0 {\n formatted += \"\\n\"\n } else {\n formatted += \" \"\n }\n }\n formatted += String(char)\n }\n \n return formatted\n }\n}\n"], ["/bitchat/bitchat/Protocols/BinaryProtocol.swift", "//\n// BinaryProtocol.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # BinaryProtocol\n///\n/// Low-level binary encoding and decoding for BitChat protocol messages.\n/// Optimized for Bluetooth LE's limited bandwidth and MTU constraints.\n///\n/// ## Overview\n/// BinaryProtocol implements an efficient binary wire format that minimizes\n/// overhead while maintaining extensibility. It handles:\n/// - Compact binary encoding with fixed headers\n/// - Optional field support via flags\n/// - Automatic compression for large payloads\n/// - Endianness handling for cross-platform compatibility\n///\n/// ## Wire Format\n/// ```\n/// Header (Fixed 13 bytes):\n/// +--------+------+-----+-----------+-------+----------------+\n/// |Version | Type | TTL | Timestamp | Flags | PayloadLength |\n/// |1 byte |1 byte|1byte| 8 bytes | 1 byte| 2 bytes |\n/// +--------+------+-----+-----------+-------+----------------+\n///\n/// Variable sections:\n/// +----------+-------------+---------+------------+\n/// | SenderID | RecipientID | Payload | Signature |\n/// | 8 bytes | 8 bytes* | Variable| 64 bytes* |\n/// +----------+-------------+---------+------------+\n/// * Optional fields based on flags\n/// ```\n///\n/// ## Design Rationale\n/// The protocol is designed for:\n/// - **Efficiency**: Minimal overhead for small messages\n/// - **Flexibility**: Optional fields via flag bits\n/// - **Compatibility**: Network byte order (big-endian)\n/// - **Performance**: Zero-copy where possible\n///\n/// ## Compression Strategy\n/// - Automatic compression for payloads > 256 bytes\n/// - LZ4 algorithm for speed over ratio\n/// - Original size stored for decompression\n/// - Flag bit indicates compressed payload\n///\n/// ## Flag Bits\n/// - Bit 0: Has recipient ID (directed message)\n/// - Bit 1: Has signature (authenticated message)\n/// - Bit 2: Is compressed (LZ4 compression applied)\n/// - Bits 3-7: Reserved for future use\n///\n/// ## Size Constraints\n/// - Maximum packet size: 65,535 bytes (16-bit length field)\n/// - Typical packet size: < 512 bytes (BLE MTU)\n/// - Minimum packet size: 21 bytes (header + sender ID)\n///\n/// ## Encoding Process\n/// 1. Construct header with fixed fields\n/// 2. Set appropriate flags\n/// 3. Compress payload if beneficial\n/// 4. Append variable-length fields\n/// 5. Calculate and append signature if needed\n///\n/// ## Decoding Process\n/// 1. Validate minimum packet size\n/// 2. Parse fixed header\n/// 3. Extract flags and determine field presence\n/// 4. Parse variable fields based on flags\n/// 5. Decompress payload if compressed\n/// 6. Verify signature if present\n///\n/// ## Error Handling\n/// - Graceful handling of malformed packets\n/// - Clear error messages for debugging\n/// - No crashes on invalid input\n/// - Logging of protocol violations\n///\n/// ## Performance Notes\n/// - Allocation-free for small messages\n/// - Streaming support for large payloads\n/// - Efficient bit manipulation\n/// - Platform-optimized byte swapping\n///\n\nimport Foundation\n\nextension Data {\n func trimmingNullBytes() -> Data {\n // Find the first null byte\n if let nullIndex = self.firstIndex(of: 0) {\n return self.prefix(nullIndex)\n }\n return self\n }\n}\n\n/// Implements binary encoding and decoding for BitChat protocol messages.\n/// Provides static methods for converting between BitchatPacket objects and\n/// their binary wire format representation.\n/// - Note: All multi-byte values use network byte order (big-endian)\nstruct BinaryProtocol {\n static let headerSize = 13\n static let senderIDSize = 8\n static let recipientIDSize = 8\n static let signatureSize = 64\n \n struct Flags {\n static let hasRecipient: UInt8 = 0x01\n static let hasSignature: UInt8 = 0x02\n static let isCompressed: UInt8 = 0x04\n }\n \n // Encode BitchatPacket to binary format\n static func encode(_ packet: BitchatPacket) -> Data? {\n var data = Data()\n \n \n // Try to compress payload if beneficial\n var payload = packet.payload\n var originalPayloadSize: UInt16? = nil\n var isCompressed = false\n \n if CompressionUtil.shouldCompress(payload) {\n if let compressedPayload = CompressionUtil.compress(payload) {\n // Store original size for decompression (2 bytes after payload)\n originalPayloadSize = UInt16(payload.count)\n payload = compressedPayload\n isCompressed = true\n \n } else {\n }\n } else {\n }\n \n // Header\n data.append(packet.version)\n data.append(packet.type)\n data.append(packet.ttl)\n \n // Timestamp (8 bytes, big-endian)\n for i in (0..<8).reversed() {\n data.append(UInt8((packet.timestamp >> (i * 8)) & 0xFF))\n }\n \n // Flags\n var flags: UInt8 = 0\n if packet.recipientID != nil {\n flags |= Flags.hasRecipient\n }\n if packet.signature != nil {\n flags |= Flags.hasSignature\n }\n if isCompressed {\n flags |= Flags.isCompressed\n }\n data.append(flags)\n \n // Payload length (2 bytes, big-endian) - includes original size if compressed\n let payloadDataSize = payload.count + (isCompressed ? 2 : 0)\n let payloadLength = UInt16(payloadDataSize)\n \n \n data.append(UInt8((payloadLength >> 8) & 0xFF))\n data.append(UInt8(payloadLength & 0xFF))\n \n // SenderID (exactly 8 bytes)\n let senderBytes = packet.senderID.prefix(senderIDSize)\n data.append(senderBytes)\n if senderBytes.count < senderIDSize {\n data.append(Data(repeating: 0, count: senderIDSize - senderBytes.count))\n }\n \n // RecipientID (if present)\n if let recipientID = packet.recipientID {\n let recipientBytes = recipientID.prefix(recipientIDSize)\n data.append(recipientBytes)\n if recipientBytes.count < recipientIDSize {\n data.append(Data(repeating: 0, count: recipientIDSize - recipientBytes.count))\n }\n }\n \n // Payload (with original size prepended if compressed)\n if isCompressed, let originalSize = originalPayloadSize {\n // Prepend original size (2 bytes, big-endian)\n data.append(UInt8((originalSize >> 8) & 0xFF))\n data.append(UInt8(originalSize & 0xFF))\n }\n data.append(payload)\n \n // Signature (if present)\n if let signature = packet.signature {\n data.append(signature.prefix(signatureSize))\n }\n \n \n // Apply padding to standard block sizes for traffic analysis resistance\n let optimalSize = MessagePadding.optimalBlockSize(for: data.count)\n let paddedData = MessagePadding.pad(data, toSize: optimalSize)\n \n \n return paddedData\n }\n \n // Decode binary data to BitchatPacket\n static func decode(_ data: Data) -> BitchatPacket? {\n // Remove padding first\n let unpaddedData = MessagePadding.unpad(data)\n \n \n guard unpaddedData.count >= headerSize + senderIDSize else { \n return nil \n }\n \n var offset = 0\n \n // Header\n let version = unpaddedData[offset]; offset += 1\n // Check if version is supported\n guard ProtocolVersion.isSupported(version) else { \n // Log unsupported version for debugging\n return nil \n }\n let type = unpaddedData[offset]; offset += 1\n let ttl = unpaddedData[offset]; offset += 1\n \n // Timestamp\n let timestampData = unpaddedData[offset..= expectedSize else { \n return nil \n }\n \n // SenderID\n let senderID = unpaddedData[offset..= 2 else { return nil }\n let originalSizeData = unpaddedData[offset.. Data? {\n var data = Data()\n \n // Message format:\n // - Flags: 1 byte (bit 0: isRelay, bit 1: isPrivate, bit 2: hasOriginalSender, bit 3: hasRecipientNickname, bit 4: hasSenderPeerID, bit 5: hasMentions)\n // - Timestamp: 8 bytes (seconds since epoch)\n // - ID length: 1 byte\n // - ID: variable\n // - Sender length: 1 byte\n // - Sender: variable\n // - Content length: 2 bytes\n // - Content: variable\n // Optional fields based on flags:\n // - Original sender length + data\n // - Recipient nickname length + data\n // - Sender peer ID length + data\n // - Mentions array\n \n var flags: UInt8 = 0\n if isRelay { flags |= 0x01 }\n if isPrivate { flags |= 0x02 }\n if originalSender != nil { flags |= 0x04 }\n if recipientNickname != nil { flags |= 0x08 }\n if senderPeerID != nil { flags |= 0x10 }\n if mentions != nil && !mentions!.isEmpty { flags |= 0x20 }\n \n data.append(flags)\n \n // Timestamp (in milliseconds)\n let timestampMillis = UInt64(timestamp.timeIntervalSince1970 * 1000)\n // Encode as 8 bytes, big-endian\n for i in (0..<8).reversed() {\n data.append(UInt8((timestampMillis >> (i * 8)) & 0xFF))\n }\n \n // ID\n if let idData = id.data(using: .utf8) {\n data.append(UInt8(min(idData.count, 255)))\n data.append(idData.prefix(255))\n } else {\n data.append(0)\n }\n \n // Sender\n if let senderData = sender.data(using: .utf8) {\n data.append(UInt8(min(senderData.count, 255)))\n data.append(senderData.prefix(255))\n } else {\n data.append(0)\n }\n \n // Content\n if let contentData = content.data(using: .utf8) {\n let length = UInt16(min(contentData.count, 65535))\n // Encode length as 2 bytes, big-endian\n data.append(UInt8((length >> 8) & 0xFF))\n data.append(UInt8(length & 0xFF))\n data.append(contentData.prefix(Int(length)))\n } else {\n data.append(contentsOf: [0, 0])\n }\n \n // Optional fields\n if let originalSender = originalSender, let origData = originalSender.data(using: .utf8) {\n data.append(UInt8(min(origData.count, 255)))\n data.append(origData.prefix(255))\n }\n \n if let recipientNickname = recipientNickname, let recipData = recipientNickname.data(using: .utf8) {\n data.append(UInt8(min(recipData.count, 255)))\n data.append(recipData.prefix(255))\n }\n \n if let senderPeerID = senderPeerID, let peerData = senderPeerID.data(using: .utf8) {\n data.append(UInt8(min(peerData.count, 255)))\n data.append(peerData.prefix(255))\n }\n \n // Mentions array\n if let mentions = mentions {\n data.append(UInt8(min(mentions.count, 255))) // Number of mentions\n for mention in mentions.prefix(255) {\n if let mentionData = mention.data(using: .utf8) {\n data.append(UInt8(min(mentionData.count, 255)))\n data.append(mentionData.prefix(255))\n } else {\n data.append(0)\n }\n }\n }\n \n \n return data\n }\n \n static func fromBinaryPayload(_ data: Data) -> BitchatMessage? {\n // Create an immutable copy to prevent threading issues\n let dataCopy = Data(data)\n \n \n guard dataCopy.count >= 13 else { \n return nil \n }\n \n var offset = 0\n \n // Flags\n guard offset < dataCopy.count else { \n return nil \n }\n let flags = dataCopy[offset]; offset += 1\n let isRelay = (flags & 0x01) != 0\n let isPrivate = (flags & 0x02) != 0\n let hasOriginalSender = (flags & 0x04) != 0\n let hasRecipientNickname = (flags & 0x08) != 0\n let hasSenderPeerID = (flags & 0x10) != 0\n let hasMentions = (flags & 0x20) != 0\n \n // Timestamp\n guard offset + 8 <= dataCopy.count else { \n return nil \n }\n let timestampData = dataCopy[offset.. 0 {\n mentions = []\n for _ in 0..\n//\n\n///\n/// # NoiseProtocol\n///\n/// A complete implementation of the Noise Protocol Framework for end-to-end\n/// encryption in BitChat. This file contains the core cryptographic primitives\n/// and handshake logic that enable secure communication between peers.\n///\n/// ## Overview\n/// The Noise Protocol Framework is a modern cryptographic framework designed\n/// for building secure protocols. BitChat uses Noise to provide:\n/// - Mutual authentication between peers\n/// - Forward secrecy for all messages\n/// - Protection against replay attacks\n/// - Minimal round trips for connection establishment\n///\n/// ## Implementation Details\n/// This implementation follows the Noise specification exactly, using:\n/// - **Pattern**: XX (most versatile, provides mutual authentication)\n/// - **DH**: Curve25519 (X25519 key exchange)\n/// - **Cipher**: ChaCha20-Poly1305 (AEAD encryption)\n/// - **Hash**: SHA-256 (for key derivation and authentication)\n///\n/// ## Security Properties\n/// The XX handshake pattern provides:\n/// 1. **Identity Hiding**: Both parties' identities are encrypted\n/// 2. **Forward Secrecy**: Past sessions remain secure if keys are compromised\n/// 3. **Key Compromise Impersonation Resistance**: Compromised static key doesn't allow impersonation to that party\n/// 4. **Mutual Authentication**: Both parties verify each other's identity\n///\n/// ## Handshake Flow (XX Pattern)\n/// ```\n/// Initiator Responder\n/// --------- ---------\n/// -> e (ephemeral key)\n/// <- e, ee, s, es (ephemeral, DH, static encrypted, DH)\n/// -> s, se (static encrypted, DH)\n/// ```\n///\n/// ## Key Components\n/// - **NoiseCipherState**: Manages symmetric encryption with nonce tracking\n/// - **NoiseSymmetricState**: Handles key derivation and handshake hashing\n/// - **NoiseHandshakeState**: Orchestrates the complete handshake process\n///\n/// ## Replay Protection\n/// Implements sliding window replay protection to prevent message replay attacks:\n/// - Tracks nonces within a 1024-message window\n/// - Rejects duplicate or too-old nonces\n/// - Handles out-of-order message delivery\n///\n/// ## Usage Example\n/// ```swift\n/// let handshake = NoiseHandshakeState(\n/// pattern: .XX,\n/// role: .initiator,\n/// localStatic: staticKeyPair\n/// )\n/// let messageBuffer = handshake.writeMessage(payload: Data())\n/// // Send messageBuffer to peer...\n/// ```\n///\n/// ## Security Considerations\n/// - Static keys must be generated using secure random sources\n/// - Keys should be stored securely (e.g., in Keychain)\n/// - Handshake state must not be reused after completion\n/// - Transport messages have a nonce limit (2^64-1)\n///\n/// ## References\n/// - Noise Protocol Framework: http://www.noiseprotocol.org/\n/// - Noise Specification: http://www.noiseprotocol.org/noise.html\n///\n\nimport Foundation\nimport CryptoKit\nimport os.log\n\n// Core Noise Protocol implementation\n// Based on the Noise Protocol Framework specification\n\n// MARK: - Constants and Types\n\n/// Supported Noise handshake patterns.\n/// Each pattern provides different security properties and authentication guarantees.\nenum NoisePattern {\n case XX // Most versatile, mutual authentication\n case IK // Initiator knows responder's static key\n case NK // Anonymous initiator\n}\n\nenum NoiseRole {\n case initiator\n case responder\n}\n\nenum NoiseMessagePattern {\n case e // Ephemeral key\n case s // Static key\n case ee // DH(ephemeral, ephemeral)\n case es // DH(ephemeral, static)\n case se // DH(static, ephemeral)\n case ss // DH(static, static)\n}\n\n// MARK: - Noise Protocol Configuration\n\nstruct NoiseProtocolName {\n let pattern: String\n let dh: String = \"25519\" // Curve25519\n let cipher: String = \"ChaChaPoly\" // ChaCha20-Poly1305\n let hash: String = \"SHA256\" // SHA-256\n \n var fullName: String {\n \"Noise_\\(pattern)_\\(dh)_\\(cipher)_\\(hash)\"\n }\n}\n\n// MARK: - Cipher State\n\n/// Manages symmetric encryption state for Noise protocol sessions.\n/// Handles ChaCha20-Poly1305 AEAD encryption with automatic nonce management\n/// and replay protection using a sliding window algorithm.\n/// - Warning: Nonce reuse would be catastrophic for security\nclass NoiseCipherState {\n // Constants for replay protection\n private static let NONCE_SIZE_BYTES = 4\n private static let REPLAY_WINDOW_SIZE = 1024\n private static let REPLAY_WINDOW_BYTES = REPLAY_WINDOW_SIZE / 8 // 128 bytes\n private static let HIGH_NONCE_WARNING_THRESHOLD: UInt64 = 1_000_000_000\n \n private var key: SymmetricKey?\n private var nonce: UInt64 = 0\n private var useExtractedNonce: Bool = false\n \n // Sliding window replay protection (only used when useExtractedNonce = true)\n private var highestReceivedNonce: UInt64 = 0\n private var replayWindow: [UInt8] = Array(repeating: 0, count: REPLAY_WINDOW_BYTES)\n \n init() {}\n \n init(key: SymmetricKey, useExtractedNonce: Bool = false) {\n self.key = key\n self.useExtractedNonce = useExtractedNonce\n }\n \n func initializeKey(_ key: SymmetricKey) {\n self.key = key\n self.nonce = 0\n }\n \n func hasKey() -> Bool {\n return key != nil\n }\n \n // MARK: - Sliding Window Replay Protection\n \n /// Check if nonce is valid for replay protection\n private func isValidNonce(_ receivedNonce: UInt64) -> Bool {\n if receivedNonce + UInt64(Self.REPLAY_WINDOW_SIZE) <= highestReceivedNonce {\n return false // Too old, outside window\n }\n \n if receivedNonce > highestReceivedNonce {\n return true // Always accept newer nonces\n }\n \n let offset = Int(highestReceivedNonce - receivedNonce)\n let byteIndex = offset / 8\n let bitIndex = offset % 8\n \n return (replayWindow[byteIndex] & (1 << bitIndex)) == 0 // Not yet seen\n }\n \n /// Mark nonce as seen in replay window\n private func markNonceAsSeen(_ receivedNonce: UInt64) {\n if receivedNonce > highestReceivedNonce {\n let shift = Int(receivedNonce - highestReceivedNonce)\n \n if shift >= Self.REPLAY_WINDOW_SIZE {\n // Clear entire window - shift is too large\n replayWindow = Array(repeating: 0, count: Self.REPLAY_WINDOW_BYTES)\n } else {\n // Shift window right by `shift` bits\n for i in stride(from: Self.REPLAY_WINDOW_BYTES - 1, through: 0, by: -1) {\n let sourceByteIndex = i - shift / 8\n var newByte: UInt8 = 0\n \n if sourceByteIndex >= 0 {\n newByte = replayWindow[sourceByteIndex] >> (shift % 8)\n if sourceByteIndex > 0 && shift % 8 != 0 {\n newByte |= replayWindow[sourceByteIndex - 1] << (8 - shift % 8)\n }\n }\n \n replayWindow[i] = newByte\n }\n }\n \n highestReceivedNonce = receivedNonce\n replayWindow[0] |= 1 // Mark most recent bit as seen\n } else {\n let offset = Int(highestReceivedNonce - receivedNonce)\n let byteIndex = offset / 8\n let bitIndex = offset % 8\n replayWindow[byteIndex] |= (1 << bitIndex)\n }\n }\n \n /// Extract nonce from combined payload \n /// Returns tuple of (nonce, ciphertext) or nil if invalid\n private func extractNonceFromCiphertextPayload(_ combinedPayload: Data) throws -> (nonce: UInt64, ciphertext: Data)? {\n guard combinedPayload.count >= Self.NONCE_SIZE_BYTES else {\n return nil\n }\n\n // Extract 4-byte nonce (big-endian)\n let nonceData = combinedPayload.prefix(Self.NONCE_SIZE_BYTES)\n let extractedNonce = nonceData.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> UInt64 in\n let byteArray = bytes.bindMemory(to: UInt8.self)\n var result: UInt64 = 0\n for i in 0.. Data {\n var bytes = Data(count: Self.NONCE_SIZE_BYTES)\n withUnsafeBytes(of: nonce.bigEndian) { ptr in\n // Copy only the last 4 bytes from the 8-byte UInt64 \n let sourceBytes = ptr.bindMemory(to: UInt8.self)\n bytes.replaceSubrange(0.. Data {\n guard let key = self.key else {\n throw NoiseError.uninitializedCipher\n }\n \n // Debug logging for nonce tracking\n let currentNonce = nonce\n \n // Check if nonce exceeds 4-byte limit (UInt32 max value)\n guard nonce <= UInt64(UInt32.max) - 1 else {\n throw NoiseError.nonceExceeded\n }\n \n // Create nonce from counter\n var nonceData = Data(count: 12)\n withUnsafeBytes(of: currentNonce.littleEndian) { bytes in\n nonceData.replaceSubrange(4..<12, with: bytes)\n }\n \n let sealedBox = try ChaChaPoly.seal(plaintext, using: key, nonce: ChaChaPoly.Nonce(data: nonceData), authenticating: associatedData)\n // increment local nonce\n nonce += 1\n \n // Create combined payload: \n let combinedPayload: Data\n if (useExtractedNonce) {\n let nonceBytes = nonceToBytes(currentNonce)\n combinedPayload = nonceBytes + sealedBox.ciphertext + sealedBox.tag\n } else {\n combinedPayload = sealedBox.ciphertext + sealedBox.tag\n }\n \n // Log high nonce values that might indicate issues\n if currentNonce > Self.HIGH_NONCE_WARNING_THRESHOLD {\n SecureLogger.log(\"High nonce value detected: \\(currentNonce) - consider rekeying\", category: SecureLogger.encryption, level: .warning)\n }\n \n return combinedPayload\n }\n \n func decrypt(ciphertext: Data, associatedData: Data = Data()) throws -> Data {\n guard let key = self.key else {\n throw NoiseError.uninitializedCipher\n }\n \n guard ciphertext.count >= 16 else {\n throw NoiseError.invalidCiphertext\n }\n \n let encryptedData: Data\n let tag: Data\n let decryptionNonce: UInt64\n \n if useExtractedNonce {\n // Extract nonce and ciphertext from combined payload\n guard let (extractedNonce, actualCiphertext) = try extractNonceFromCiphertextPayload(ciphertext) else {\n SecureLogger.log(\"Decrypt failed: Could not extract nonce from payload\")\n throw NoiseError.invalidCiphertext\n }\n \n // Validate nonce with sliding window replay protection\n guard isValidNonce(extractedNonce) else {\n SecureLogger.log(\"Replay attack detected: nonce \\(extractedNonce) rejected\")\n throw NoiseError.replayDetected\n }\n\n // Split ciphertext and tag\n encryptedData = actualCiphertext.prefix(actualCiphertext.count - 16)\n tag = actualCiphertext.suffix(16)\n decryptionNonce = extractedNonce\n } else {\n // Split ciphertext and tag\n encryptedData = ciphertext.prefix(ciphertext.count - 16)\n tag = ciphertext.suffix(16)\n decryptionNonce = nonce\n }\n \n // Create nonce from counter\n var nonceData = Data(count: 12)\n withUnsafeBytes(of: decryptionNonce.littleEndian) { bytes in\n nonceData.replaceSubrange(4..<12, with: bytes)\n }\n \n let sealedBox = try ChaChaPoly.SealedBox(\n nonce: ChaChaPoly.Nonce(data: nonceData),\n ciphertext: encryptedData,\n tag: tag\n )\n \n // Log high nonce values that might indicate issues\n if decryptionNonce > Self.HIGH_NONCE_WARNING_THRESHOLD {\n SecureLogger.log(\"High nonce value detected: \\(decryptionNonce) - consider rekeying\", category: SecureLogger.encryption, level: .warning)\n }\n \n do {\n let plaintext = try ChaChaPoly.open(sealedBox, using: key, authenticating: associatedData)\n \n if useExtractedNonce {\n // Mark nonce as seen after successful decryption\n markNonceAsSeen(decryptionNonce)\n }\n nonce += 1\n return plaintext\n } catch {\n SecureLogger.log(\"Decrypt failed: \\(error) for nonce \\(decryptionNonce)\")\n // Log authentication failures with nonce info\n SecureLogger.log(\"Decryption failed at nonce \\(decryptionNonce)\", category: SecureLogger.encryption, level: .error)\n throw error\n }\n }\n}\n\n// MARK: - Symmetric State\n\n/// Manages the symmetric cryptographic state during Noise handshakes.\n/// Responsible for key derivation, protocol name hashing, and maintaining\n/// the chaining key that provides key separation between handshake messages.\n/// - Note: This class implements the SymmetricState object from the Noise spec\nclass NoiseSymmetricState {\n private var cipherState: NoiseCipherState\n private var chainingKey: Data\n private var hash: Data\n \n init(protocolName: String) {\n self.cipherState = NoiseCipherState()\n \n // Initialize with protocol name\n let nameData = protocolName.data(using: .utf8)!\n if nameData.count <= 32 {\n self.hash = nameData + Data(repeating: 0, count: 32 - nameData.count)\n } else {\n self.hash = Data(SHA256.hash(data: nameData))\n }\n self.chainingKey = self.hash\n }\n \n func mixKey(_ inputKeyMaterial: Data) {\n let output = hkdf(chainingKey: chainingKey, inputKeyMaterial: inputKeyMaterial, numOutputs: 2)\n chainingKey = output[0]\n let tempKey = SymmetricKey(data: output[1])\n cipherState.initializeKey(tempKey)\n }\n \n func mixHash(_ data: Data) {\n hash = Data(SHA256.hash(data: hash + data))\n }\n \n func mixKeyAndHash(_ inputKeyMaterial: Data) {\n let output = hkdf(chainingKey: chainingKey, inputKeyMaterial: inputKeyMaterial, numOutputs: 3)\n chainingKey = output[0]\n mixHash(output[1])\n let tempKey = SymmetricKey(data: output[2])\n cipherState.initializeKey(tempKey)\n }\n \n func getHandshakeHash() -> Data {\n return hash\n }\n \n func hasCipherKey() -> Bool {\n return cipherState.hasKey()\n }\n \n func encryptAndHash(_ plaintext: Data) throws -> Data {\n if cipherState.hasKey() {\n let ciphertext = try cipherState.encrypt(plaintext: plaintext, associatedData: hash)\n mixHash(ciphertext)\n return ciphertext\n } else {\n mixHash(plaintext)\n return plaintext\n }\n }\n \n func decryptAndHash(_ ciphertext: Data) throws -> Data {\n if cipherState.hasKey() {\n let plaintext = try cipherState.decrypt(ciphertext: ciphertext, associatedData: hash)\n mixHash(ciphertext)\n return plaintext\n } else {\n mixHash(ciphertext)\n return ciphertext\n }\n }\n \n func split() -> (NoiseCipherState, NoiseCipherState) {\n let output = hkdf(chainingKey: chainingKey, inputKeyMaterial: Data(), numOutputs: 2)\n let tempKey1 = SymmetricKey(data: output[0])\n let tempKey2 = SymmetricKey(data: output[1])\n \n let c1 = NoiseCipherState(key: tempKey1, useExtractedNonce: true)\n let c2 = NoiseCipherState(key: tempKey2, useExtractedNonce: true)\n \n return (c1, c2)\n }\n \n // HKDF implementation\n private func hkdf(chainingKey: Data, inputKeyMaterial: Data, numOutputs: Int) -> [Data] {\n let tempKey = HMAC.authenticationCode(for: inputKeyMaterial, using: SymmetricKey(data: chainingKey))\n let tempKeyData = Data(tempKey)\n \n var outputs: [Data] = []\n var currentOutput = Data()\n \n for i in 1...numOutputs {\n currentOutput = Data(HMAC.authenticationCode(\n for: currentOutput + Data([UInt8(i)]),\n using: SymmetricKey(data: tempKeyData)\n ))\n outputs.append(currentOutput)\n }\n \n return outputs\n }\n}\n\n// MARK: - Handshake State\n\n/// Orchestrates the complete Noise handshake process.\n/// This is the main interface for establishing encrypted sessions between peers.\n/// Manages the handshake state machine, message patterns, and key derivation.\n/// - Important: Each handshake instance should only be used once\nclass NoiseHandshakeState {\n private let role: NoiseRole\n private let pattern: NoisePattern\n private var symmetricState: NoiseSymmetricState\n \n // Keys\n private var localStaticPrivate: Curve25519.KeyAgreement.PrivateKey?\n private var localStaticPublic: Curve25519.KeyAgreement.PublicKey?\n private var localEphemeralPrivate: Curve25519.KeyAgreement.PrivateKey?\n private var localEphemeralPublic: Curve25519.KeyAgreement.PublicKey?\n \n private var remoteStaticPublic: Curve25519.KeyAgreement.PublicKey?\n private var remoteEphemeralPublic: Curve25519.KeyAgreement.PublicKey?\n \n // Message patterns\n private var messagePatterns: [[NoiseMessagePattern]] = []\n private var currentPattern = 0\n \n init(role: NoiseRole, pattern: NoisePattern, localStaticKey: Curve25519.KeyAgreement.PrivateKey? = nil, remoteStaticKey: Curve25519.KeyAgreement.PublicKey? = nil) {\n self.role = role\n self.pattern = pattern\n \n // Initialize static keys\n if let localKey = localStaticKey {\n self.localStaticPrivate = localKey\n self.localStaticPublic = localKey.publicKey\n }\n self.remoteStaticPublic = remoteStaticKey\n \n // Initialize protocol name\n let protocolName = NoiseProtocolName(pattern: pattern.patternName)\n self.symmetricState = NoiseSymmetricState(protocolName: protocolName.fullName)\n \n // Initialize message patterns\n self.messagePatterns = pattern.messagePatterns\n \n // Mix pre-message keys according to pattern\n mixPreMessageKeys()\n }\n \n private func mixPreMessageKeys() {\n // Mix prologue (empty for XX pattern normally)\n symmetricState.mixHash(Data()) // Empty prologue for XX pattern\n // For XX pattern, no pre-message keys\n // For IK/NK patterns, we'd mix the responder's static key here\n switch pattern {\n case .XX:\n break // No pre-message keys\n case .IK, .NK:\n if role == .initiator, let remoteStatic = remoteStaticPublic {\n _ = symmetricState.getHandshakeHash()\n symmetricState.mixHash(remoteStatic.rawRepresentation)\n }\n }\n }\n \n func writeMessage(payload: Data = Data()) throws -> Data {\n guard currentPattern < messagePatterns.count else {\n throw NoiseError.handshakeComplete\n }\n \n var messageBuffer = Data()\n let patterns = messagePatterns[currentPattern]\n \n for pattern in patterns {\n switch pattern {\n case .e:\n // Generate ephemeral key\n localEphemeralPrivate = Curve25519.KeyAgreement.PrivateKey()\n localEphemeralPublic = localEphemeralPrivate!.publicKey\n messageBuffer.append(localEphemeralPublic!.rawRepresentation)\n symmetricState.mixHash(localEphemeralPublic!.rawRepresentation)\n \n case .s:\n // Send static key (encrypted if cipher is initialized)\n guard let staticPublic = localStaticPublic else {\n throw NoiseError.missingLocalStaticKey\n }\n let encrypted = try symmetricState.encryptAndHash(staticPublic.rawRepresentation)\n messageBuffer.append(encrypted)\n \n case .ee:\n // DH(local ephemeral, remote ephemeral)\n guard let localEphemeral = localEphemeralPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n \n case .es:\n // DH(ephemeral, static) - direction depends on role\n if role == .initiator {\n guard let localEphemeral = localEphemeralPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n } else {\n guard let localStatic = localStaticPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n }\n \n case .se:\n // DH(static, ephemeral) - direction depends on role\n if role == .initiator {\n guard let localStatic = localStaticPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n } else {\n guard let localEphemeral = localEphemeralPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n }\n \n case .ss:\n // DH(static, static)\n guard let localStatic = localStaticPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n }\n }\n \n // Encrypt payload\n let encryptedPayload = try symmetricState.encryptAndHash(payload)\n messageBuffer.append(encryptedPayload)\n \n currentPattern += 1\n return messageBuffer\n }\n \n func readMessage(_ message: Data, expectedPayloadLength: Int = 0) throws -> Data {\n \n guard currentPattern < messagePatterns.count else {\n throw NoiseError.handshakeComplete\n }\n \n var buffer = message\n let patterns = messagePatterns[currentPattern]\n \n for pattern in patterns {\n switch pattern {\n case .e:\n // Read ephemeral key\n guard buffer.count >= 32 else {\n throw NoiseError.invalidMessage\n }\n let ephemeralData = buffer.prefix(32)\n buffer = buffer.dropFirst(32)\n \n do {\n remoteEphemeralPublic = try NoiseHandshakeState.validatePublicKey(ephemeralData)\n } catch {\n SecureLogger.log(\"Invalid ephemeral public key received\", category: SecureLogger.security, level: .warning)\n throw NoiseError.invalidMessage\n }\n symmetricState.mixHash(ephemeralData)\n \n case .s:\n // Read static key (may be encrypted)\n let keyLength = symmetricState.hasCipherKey() ? 48 : 32 // 32 + 16 byte tag if encrypted\n guard buffer.count >= keyLength else {\n throw NoiseError.invalidMessage\n }\n let staticData = buffer.prefix(keyLength)\n buffer = buffer.dropFirst(keyLength)\n do {\n let decrypted = try symmetricState.decryptAndHash(staticData)\n remoteStaticPublic = try NoiseHandshakeState.validatePublicKey(decrypted)\n } catch {\n SecureLogger.logSecurityEvent(.authenticationFailed(peerID: \"Unknown - handshake\"), level: .error)\n throw NoiseError.authenticationFailure\n }\n \n case .ee, .es, .se, .ss:\n // Same DH operations as in writeMessage\n try performDHOperation(pattern)\n }\n }\n \n // Decrypt payload\n let payload = try symmetricState.decryptAndHash(buffer)\n currentPattern += 1\n \n return payload\n }\n \n private func performDHOperation(_ pattern: NoiseMessagePattern) throws {\n switch pattern {\n case .ee:\n guard let localEphemeral = localEphemeralPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n \n case .es:\n if role == .initiator {\n guard let localEphemeral = localEphemeralPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n } else {\n guard let localStatic = localStaticPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n }\n \n case .se:\n if role == .initiator {\n guard let localStatic = localStaticPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n } else {\n guard let localEphemeral = localEphemeralPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n }\n \n case .ss:\n guard let localStatic = localStaticPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n \n default:\n break\n }\n }\n \n func isHandshakeComplete() -> Bool {\n return currentPattern >= messagePatterns.count\n }\n \n func getTransportCiphers() throws -> (send: NoiseCipherState, receive: NoiseCipherState) {\n guard isHandshakeComplete() else {\n throw NoiseError.handshakeNotComplete\n }\n \n let (c1, c2) = symmetricState.split()\n \n // Initiator uses c1 for sending, c2 for receiving\n // Responder uses c2 for sending, c1 for receiving\n return role == .initiator ? (c1, c2) : (c2, c1)\n }\n \n func getRemoteStaticPublicKey() -> Curve25519.KeyAgreement.PublicKey? {\n return remoteStaticPublic\n }\n \n func getHandshakeHash() -> Data {\n return symmetricState.getHandshakeHash()\n }\n}\n\n// MARK: - Pattern Extensions\n\nextension NoisePattern {\n var patternName: String {\n switch self {\n case .XX: return \"XX\"\n case .IK: return \"IK\"\n case .NK: return \"NK\"\n }\n }\n \n var messagePatterns: [[NoiseMessagePattern]] {\n switch self {\n case .XX:\n return [\n [.e], // -> e\n [.e, .ee, .s, .es], // <- e, ee, s, es\n [.s, .se] // -> s, se\n ]\n case .IK:\n return [\n [.e, .es, .s, .ss], // -> e, es, s, ss\n [.e, .ee, .se] // <- e, ee, se\n ]\n case .NK:\n return [\n [.e, .es], // -> e, es\n [.e, .ee] // <- e, ee\n ]\n }\n }\n}\n\n// MARK: - Errors\n\nenum NoiseError: Error {\n case uninitializedCipher\n case invalidCiphertext\n case handshakeComplete\n case handshakeNotComplete\n case missingLocalStaticKey\n case missingKeys\n case invalidMessage\n case authenticationFailure\n case invalidPublicKey\n case replayDetected\n case nonceExceeded\n}\n\n// MARK: - Key Validation\n\nextension NoiseHandshakeState {\n /// Validate a Curve25519 public key\n /// Checks for weak/invalid keys that could compromise security\n static func validatePublicKey(_ keyData: Data) throws -> Curve25519.KeyAgreement.PublicKey {\n // Check key length\n guard keyData.count == 32 else {\n throw NoiseError.invalidPublicKey\n }\n \n // Check for all-zero key (point at infinity)\n if keyData.allSatisfy({ $0 == 0 }) {\n throw NoiseError.invalidPublicKey\n }\n \n // Check for low-order points that could enable small subgroup attacks\n // These are the known bad points for Curve25519\n let lowOrderPoints: [Data] = [\n Data(repeating: 0x00, count: 32), // Already checked above\n Data([0x01] + Data(repeating: 0x00, count: 31)), // Point of order 1\n Data([0x00] + Data(repeating: 0x00, count: 30) + [0x01]), // Another low-order point\n Data([0xe0, 0xeb, 0x7a, 0x7c, 0x3b, 0x41, 0xb8, 0xae, 0x16, 0x56, 0xe3,\n 0xfa, 0xf1, 0x9f, 0xc4, 0x6a, 0xda, 0x09, 0x8d, 0xeb, 0x9c, 0x32,\n 0xb1, 0xfd, 0x86, 0x62, 0x05, 0x16, 0x5f, 0x49, 0xb8, 0x00]), // Low order point\n Data([0x5f, 0x9c, 0x95, 0xbc, 0xa3, 0x50, 0x8c, 0x24, 0xb1, 0xd0, 0xb1,\n 0x55, 0x9c, 0x83, 0xef, 0x5b, 0x04, 0x44, 0x5c, 0xc4, 0x58, 0x1c,\n 0x8e, 0x86, 0xd8, 0x22, 0x4e, 0xdd, 0xd0, 0x9f, 0x11, 0x57]), // Low order point\n Data(repeating: 0xFF, count: 32), // All ones\n Data([0xda, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), // Another bad point\n Data([0xdb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]) // Another bad point\n ]\n \n // Check against known bad points\n if lowOrderPoints.contains(keyData) {\n SecureLogger.log(\"Low-order point detected\", category: SecureLogger.security, level: .warning)\n throw NoiseError.invalidPublicKey\n }\n \n // Try to create the key - CryptoKit will validate curve points internally\n do {\n let publicKey = try Curve25519.KeyAgreement.PublicKey(rawRepresentation: keyData)\n return publicKey\n } catch {\n // If CryptoKit rejects it, it's invalid\n SecureLogger.log(\"CryptoKit validation failed\", category: SecureLogger.security, level: .warning)\n throw NoiseError.invalidPublicKey\n }\n }\n}\n"], ["/bitchat/bitchat/Noise/NoiseSession.swift", "//\n// NoiseSession.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport CryptoKit\nimport os.log\n\n// MARK: - Noise Session State\n\nenum NoiseSessionState: Equatable {\n case uninitialized\n case handshaking\n case established\n case failed(Error)\n \n static func == (lhs: NoiseSessionState, rhs: NoiseSessionState) -> Bool {\n switch (lhs, rhs) {\n case (.uninitialized, .uninitialized),\n (.handshaking, .handshaking),\n (.established, .established):\n return true\n case (.failed, .failed):\n return true // We don't compare the errors\n default:\n return false\n }\n }\n}\n\n// MARK: - Noise Session\n\nclass NoiseSession {\n let peerID: String\n let role: NoiseRole\n private var state: NoiseSessionState = .uninitialized\n private var handshakeState: NoiseHandshakeState?\n private var sendCipher: NoiseCipherState?\n private var receiveCipher: NoiseCipherState?\n \n // Keys\n private let localStaticKey: Curve25519.KeyAgreement.PrivateKey\n private var remoteStaticPublicKey: Curve25519.KeyAgreement.PublicKey?\n \n // Handshake messages for retransmission\n private var sentHandshakeMessages: [Data] = []\n private var handshakeHash: Data?\n \n // Thread safety\n private let sessionQueue = DispatchQueue(label: \"chat.bitchat.noise.session\", attributes: .concurrent)\n \n init(peerID: String, role: NoiseRole, localStaticKey: Curve25519.KeyAgreement.PrivateKey, remoteStaticKey: Curve25519.KeyAgreement.PublicKey? = nil) {\n self.peerID = peerID\n self.role = role\n self.localStaticKey = localStaticKey\n self.remoteStaticPublicKey = remoteStaticKey\n }\n \n // MARK: - Handshake\n \n func startHandshake() throws -> Data {\n return try sessionQueue.sync(flags: .barrier) {\n guard case .uninitialized = state else {\n throw NoiseSessionError.invalidState\n }\n \n // For XX pattern, we don't need remote static key upfront\n handshakeState = NoiseHandshakeState(\n role: role,\n pattern: .XX,\n localStaticKey: localStaticKey,\n remoteStaticKey: nil\n )\n \n state = .handshaking\n \n // Only initiator writes the first message\n if role == .initiator {\n let message = try handshakeState!.writeMessage()\n sentHandshakeMessages.append(message)\n return message\n } else {\n // Responder doesn't send first message in XX pattern\n return Data()\n }\n }\n }\n \n func processHandshakeMessage(_ message: Data) throws -> Data? {\n return try sessionQueue.sync(flags: .barrier) {\n SecureLogger.log(\"NoiseSession[\\(peerID)]: Processing handshake message, current state: \\(state), role: \\(role)\", category: SecureLogger.noise, level: .info)\n \n // Initialize handshake state if needed (for responders)\n if state == .uninitialized && role == .responder {\n handshakeState = NoiseHandshakeState(\n role: role,\n pattern: .XX,\n localStaticKey: localStaticKey,\n remoteStaticKey: nil\n )\n state = .handshaking\n SecureLogger.log(\"NoiseSession[\\(peerID)]: Initialized handshake state for responder\", category: SecureLogger.noise, level: .info)\n }\n \n guard case .handshaking = state, let handshake = handshakeState else {\n throw NoiseSessionError.invalidState\n }\n \n // Process incoming message\n _ = try handshake.readMessage(message)\n SecureLogger.log(\"NoiseSession[\\(peerID)]: Read handshake message, checking if complete\", category: SecureLogger.noise, level: .info)\n \n // Check if handshake is complete\n if handshake.isHandshakeComplete() {\n // Get transport ciphers\n let (send, receive) = try handshake.getTransportCiphers()\n sendCipher = send\n receiveCipher = receive\n \n // Store remote static key\n remoteStaticPublicKey = handshake.getRemoteStaticPublicKey()\n \n // Store handshake hash for channel binding\n handshakeHash = handshake.getHandshakeHash()\n \n state = .established\n handshakeState = nil // Clear handshake state\n \n SecureLogger.log(\"NoiseSession[\\(peerID)]: Handshake complete (no response needed), transitioning to established\", category: SecureLogger.noise, level: .info)\n SecureLogger.logSecurityEvent(.handshakeCompleted(peerID: peerID))\n \n return nil\n } else {\n // Generate response\n let response = try handshake.writeMessage()\n sentHandshakeMessages.append(response)\n SecureLogger.log(\"NoiseSession[\\(peerID)]: Generated handshake response of size \\(response.count)\", category: SecureLogger.noise, level: .info)\n \n // Check if handshake is complete after writing\n if handshake.isHandshakeComplete() {\n // Get transport ciphers\n let (send, receive) = try handshake.getTransportCiphers()\n sendCipher = send\n receiveCipher = receive\n \n // Store remote static key\n remoteStaticPublicKey = handshake.getRemoteStaticPublicKey()\n \n // Store handshake hash for channel binding\n handshakeHash = handshake.getHandshakeHash()\n \n state = .established\n handshakeState = nil // Clear handshake state\n \n SecureLogger.log(\"NoiseSession[\\(peerID)]: Handshake complete after writing response, transitioning to established\", category: SecureLogger.noise, level: .info)\n SecureLogger.logSecurityEvent(.handshakeCompleted(peerID: peerID))\n }\n \n return response\n }\n }\n }\n \n // MARK: - Transport\n \n func encrypt(_ plaintext: Data) throws -> Data {\n return try sessionQueue.sync(flags: .barrier) {\n guard case .established = state, let cipher = sendCipher else {\n throw NoiseSessionError.notEstablished\n }\n \n return try cipher.encrypt(plaintext: plaintext)\n }\n }\n \n func decrypt(_ ciphertext: Data) throws -> Data {\n return try sessionQueue.sync(flags: .barrier) {\n guard case .established = state, let cipher = receiveCipher else {\n throw NoiseSessionError.notEstablished\n }\n \n return try cipher.decrypt(ciphertext: ciphertext)\n }\n }\n \n // MARK: - State Management\n \n func getState() -> NoiseSessionState {\n return sessionQueue.sync {\n return state\n }\n }\n \n func isEstablished() -> Bool {\n return sessionQueue.sync {\n if case .established = state {\n return true\n }\n return false\n }\n }\n \n func getRemoteStaticPublicKey() -> Curve25519.KeyAgreement.PublicKey? {\n return sessionQueue.sync {\n return remoteStaticPublicKey\n }\n }\n \n func getHandshakeHash() -> Data? {\n return sessionQueue.sync {\n return handshakeHash\n }\n }\n \n func reset() {\n sessionQueue.sync(flags: .barrier) {\n let wasEstablished = state == .established\n state = .uninitialized\n handshakeState = nil\n sendCipher = nil\n receiveCipher = nil\n sentHandshakeMessages.removeAll()\n handshakeHash = nil\n \n if wasEstablished {\n SecureLogger.logSecurityEvent(.sessionExpired(peerID: peerID))\n }\n }\n }\n}\n\n// MARK: - Session Manager\n\nclass NoiseSessionManager {\n private var sessions: [String: NoiseSession] = [:]\n private let localStaticKey: Curve25519.KeyAgreement.PrivateKey\n private let managerQueue = DispatchQueue(label: \"chat.bitchat.noise.manager\", attributes: .concurrent)\n \n // Callbacks\n var onSessionEstablished: ((String, Curve25519.KeyAgreement.PublicKey) -> Void)?\n var onSessionFailed: ((String, Error) -> Void)?\n \n init(localStaticKey: Curve25519.KeyAgreement.PrivateKey) {\n self.localStaticKey = localStaticKey\n }\n \n // MARK: - Session Management\n \n func createSession(for peerID: String, role: NoiseRole) -> NoiseSession {\n return managerQueue.sync(flags: .barrier) {\n let session = SecureNoiseSession(\n peerID: peerID,\n role: role,\n localStaticKey: localStaticKey\n )\n sessions[peerID] = session\n return session\n }\n }\n \n func getSession(for peerID: String) -> NoiseSession? {\n return managerQueue.sync {\n return sessions[peerID]\n }\n }\n \n func removeSession(for peerID: String) {\n managerQueue.sync(flags: .barrier) {\n if let session = sessions[peerID], session.isEstablished() {\n SecureLogger.logSecurityEvent(.sessionExpired(peerID: peerID))\n }\n _ = sessions.removeValue(forKey: peerID)\n }\n }\n \n func migrateSession(from oldPeerID: String, to newPeerID: String) {\n managerQueue.sync(flags: .barrier) {\n // Check if we have a session for the old peer ID\n if let session = sessions[oldPeerID] {\n // Move the session to the new peer ID\n sessions[newPeerID] = session\n _ = sessions.removeValue(forKey: oldPeerID)\n \n SecureLogger.log(\"Migrated Noise session from \\(oldPeerID) to \\(newPeerID)\", category: SecureLogger.noise, level: .info)\n }\n }\n }\n \n func getEstablishedSessions() -> [String: NoiseSession] {\n return managerQueue.sync {\n return sessions.filter { $0.value.isEstablished() }\n }\n }\n \n // MARK: - Handshake Helpers\n \n func initiateHandshake(with peerID: String) throws -> Data {\n return try managerQueue.sync(flags: .barrier) {\n // Check if we already have an established session\n if let existingSession = sessions[peerID], existingSession.isEstablished() {\n // Session already established, don't recreate\n throw NoiseSessionError.alreadyEstablished\n }\n \n // Remove any existing non-established session\n if let existingSession = sessions[peerID], !existingSession.isEstablished() {\n _ = sessions.removeValue(forKey: peerID)\n }\n \n // Create new initiator session\n let session = SecureNoiseSession(\n peerID: peerID,\n role: .initiator,\n localStaticKey: localStaticKey\n )\n sessions[peerID] = session\n \n do {\n let handshakeData = try session.startHandshake()\n return handshakeData\n } catch {\n // Clean up failed session\n _ = sessions.removeValue(forKey: peerID)\n SecureLogger.logSecurityEvent(.handshakeFailed(peerID: peerID, error: error.localizedDescription), level: .error)\n throw error\n }\n }\n }\n \n func handleIncomingHandshake(from peerID: String, message: Data) throws -> Data? {\n // Process everything within the synchronized block to prevent race conditions\n return try managerQueue.sync(flags: .barrier) {\n var shouldCreateNew = false\n var existingSession: NoiseSession? = nil\n \n if let existing = sessions[peerID] {\n // If we have an established session, the peer must have cleared their session\n // for a good reason (e.g., decryption failure, restart, etc.)\n // We should accept the new handshake to re-establish encryption\n if existing.isEstablished() {\n SecureLogger.log(\"Accepting handshake from \\(peerID) despite existing session - peer likely cleared their session\", \n category: SecureLogger.session, level: .info)\n _ = sessions.removeValue(forKey: peerID)\n shouldCreateNew = true\n } else {\n // If we're in the middle of a handshake and receive a new initiation,\n // reset and start fresh (the other side may have restarted)\n if existing.getState() == .handshaking && message.count == 32 {\n _ = sessions.removeValue(forKey: peerID)\n shouldCreateNew = true\n } else {\n existingSession = existing\n }\n }\n } else {\n shouldCreateNew = true\n }\n \n // Get or create session\n let session: NoiseSession\n if shouldCreateNew {\n let newSession = SecureNoiseSession(\n peerID: peerID,\n role: .responder,\n localStaticKey: localStaticKey\n )\n sessions[peerID] = newSession\n session = newSession\n } else {\n session = existingSession!\n }\n \n // Process the handshake message within the synchronized block\n do {\n let response = try session.processHandshakeMessage(message)\n \n // Check if session is established after processing\n if session.isEstablished() {\n if let remoteKey = session.getRemoteStaticPublicKey() {\n // Schedule callback outside the synchronized block to prevent deadlock\n DispatchQueue.global().async { [weak self] in\n self?.onSessionEstablished?(peerID, remoteKey)\n }\n }\n }\n \n return response\n } catch {\n // Reset the session on handshake failure so next attempt can start fresh\n _ = sessions.removeValue(forKey: peerID)\n \n // Schedule callback outside the synchronized block to prevent deadlock\n DispatchQueue.global().async { [weak self] in\n self?.onSessionFailed?(peerID, error)\n }\n \n SecureLogger.logSecurityEvent(.handshakeFailed(peerID: peerID, error: error.localizedDescription), level: .error)\n throw error\n }\n }\n }\n \n // MARK: - Encryption/Decryption\n \n func encrypt(_ plaintext: Data, for peerID: String) throws -> Data {\n guard let session = getSession(for: peerID) else {\n throw NoiseSessionError.sessionNotFound\n }\n \n return try session.encrypt(plaintext)\n }\n \n func decrypt(_ ciphertext: Data, from peerID: String) throws -> Data {\n guard let session = getSession(for: peerID) else {\n throw NoiseSessionError.sessionNotFound\n }\n \n return try session.decrypt(ciphertext)\n }\n \n // MARK: - Key Management\n \n func getRemoteStaticKey(for peerID: String) -> Curve25519.KeyAgreement.PublicKey? {\n return getSession(for: peerID)?.getRemoteStaticPublicKey()\n }\n \n func getHandshakeHash(for peerID: String) -> Data? {\n return getSession(for: peerID)?.getHandshakeHash()\n }\n \n // MARK: - Session Rekeying\n \n func getSessionsNeedingRekey() -> [(peerID: String, needsRekey: Bool)] {\n return managerQueue.sync {\n var needingRekey: [(peerID: String, needsRekey: Bool)] = []\n \n for (peerID, session) in sessions {\n if let secureSession = session as? SecureNoiseSession,\n secureSession.isEstablished(),\n secureSession.needsRenegotiation() {\n needingRekey.append((peerID: peerID, needsRekey: true))\n }\n }\n \n return needingRekey\n }\n }\n \n func initiateRekey(for peerID: String) throws {\n // Remove old session\n removeSession(for: peerID)\n \n // Initiate new handshake\n _ = try initiateHandshake(with: peerID)\n \n }\n}\n\n// MARK: - Errors\n\nenum NoiseSessionError: Error {\n case invalidState\n case notEstablished\n case sessionNotFound\n case handshakeFailed(Error)\n case alreadyEstablished\n}"], ["/bitchat/bitchat/Views/LinkPreviewView.swift", "//\n// LinkPreviewView.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport SwiftUI\n#if os(iOS)\nimport LinkPresentation\nimport UIKit\n#endif\n\n// MARK: - Link Metadata Cache\n\n/// Cache for link metadata to prevent repeated network requests\nprivate class LinkMetadataCache {\n static let shared = LinkMetadataCache()\n \n #if os(iOS)\n private let cache = NSCache()\n private let imageCache = NSCache()\n #endif\n private let queue = DispatchQueue(label: \"chat.bitchat.linkmetadata.cache\", attributes: .concurrent)\n \n private init() {\n #if os(iOS)\n cache.countLimit = 100 // Keep metadata for up to 100 URLs\n imageCache.countLimit = 50 // Keep images for up to 50 URLs\n imageCache.totalCostLimit = 50 * 1024 * 1024 // 50MB limit for images\n #endif\n }\n \n #if os(iOS)\n class CachedMetadata {\n let metadata: LPLinkMetadata?\n let title: String?\n let host: String?\n let error: Error?\n let timestamp: Date\n \n init(metadata: LPLinkMetadata? = nil, title: String? = nil, host: String? = nil, error: Error? = nil) {\n self.metadata = metadata\n self.title = title\n self.host = host\n self.error = error\n self.timestamp = Date()\n }\n }\n \n func getCachedMetadata(for url: URL) -> (metadata: LPLinkMetadata?, title: String?, host: String?, image: UIImage?)? {\n return queue.sync {\n guard let cached = cache.object(forKey: url as NSURL) else { return nil }\n \n // Check if cache is older than 24 hours\n if Date().timeIntervalSince(cached.timestamp) > 86400 {\n cache.removeObject(forKey: url as NSURL)\n imageCache.removeObject(forKey: url as NSURL)\n return nil\n }\n \n let image = imageCache.object(forKey: url as NSURL)\n return (cached.metadata, cached.title, cached.host, image)\n }\n }\n \n func cacheMetadata(_ metadata: LPLinkMetadata?, title: String?, host: String?, image: UIImage?, for url: URL) {\n queue.async(flags: .barrier) {\n let cached = CachedMetadata(metadata: metadata, title: title, host: host)\n self.cache.setObject(cached, forKey: url as NSURL)\n \n if let image = image {\n let cost = Int(image.size.width * image.size.height * 4) // Approximate memory usage\n self.imageCache.setObject(image, forKey: url as NSURL, cost: cost)\n }\n }\n }\n \n func cacheError(_ error: Error, for url: URL) {\n queue.async(flags: .barrier) {\n let cached = CachedMetadata(error: error)\n self.cache.setObject(cached, forKey: url as NSURL)\n }\n }\n #endif\n \n func clearCache() {\n queue.async(flags: .barrier) {\n #if os(iOS)\n self.cache.removeAllObjects()\n self.imageCache.removeAllObjects()\n #endif\n }\n }\n}\n\n// MARK: - Link Preview View\n\nstruct LinkPreviewView: View {\n let url: URL\n let title: String?\n @Environment(\\.colorScheme) var colorScheme\n #if os(iOS)\n @State private var metadata: LPLinkMetadata?\n @State private var cachedTitle: String?\n @State private var cachedHost: String?\n @State private var isLoading = false\n #endif\n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n private var backgroundColor: Color {\n colorScheme == .dark ? Color.black : Color.white\n }\n \n private var borderColor: Color {\n textColor.opacity(0.3)\n }\n \n var body: some View {\n // Always use our custom compact view for consistent appearance\n compactLinkView\n .onAppear {\n loadFromCacheOrFetch()\n }\n }\n \n #if os(iOS)\n @State private var previewImage: UIImage? = nil\n #endif\n \n private var compactLinkView: some View {\n Button(action: {\n #if os(iOS)\n UIApplication.shared.open(url)\n #else\n NSWorkspace.shared.open(url)\n #endif\n }) {\n HStack(spacing: 12) {\n // Preview image or icon\n Group {\n #if os(iOS)\n if let image = previewImage {\n Image(uiImage: image)\n .resizable()\n .aspectRatio(contentMode: .fill)\n .frame(width: 60, height: 60)\n .clipped()\n .cornerRadius(8)\n } else {\n // Favicon or default icon\n RoundedRectangle(cornerRadius: 8)\n .fill(Color.blue.opacity(0.1))\n .frame(width: 60, height: 60)\n .overlay(\n Image(systemName: \"link\")\n .font(.system(size: 24))\n .foregroundColor(Color.blue)\n )\n }\n #else\n RoundedRectangle(cornerRadius: 8)\n .fill(Color.blue.opacity(0.1))\n .frame(width: 60, height: 60)\n .overlay(\n Image(systemName: \"link\")\n .font(.system(size: 24))\n .foregroundColor(Color.blue)\n )\n #endif\n }\n \n VStack(alignment: .leading, spacing: 4) {\n // Title\n #if os(iOS)\n Text(cachedTitle ?? metadata?.title ?? title ?? url.host ?? \"Link\")\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(textColor)\n .lineLimit(2)\n .multilineTextAlignment(.leading)\n #else\n Text(title ?? url.host ?? \"Link\")\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(textColor)\n .lineLimit(2)\n .multilineTextAlignment(.leading)\n #endif\n \n // Host\n #if os(iOS)\n Text(cachedHost ?? url.host ?? url.absoluteString)\n .font(.system(size: 11, design: .monospaced))\n .foregroundColor(textColor.opacity(0.6))\n .lineLimit(1)\n #else\n Text(url.host ?? url.absoluteString)\n .font(.system(size: 11, design: .monospaced))\n .foregroundColor(textColor.opacity(0.6))\n .lineLimit(1)\n #endif\n }\n \n Spacer()\n }\n .padding(10)\n .frame(maxWidth: .infinity, alignment: .leading)\n .background(\n RoundedRectangle(cornerRadius: 10)\n .fill(colorScheme == .dark ? Color.gray.opacity(0.15) : Color.gray.opacity(0.08))\n )\n .overlay(\n RoundedRectangle(cornerRadius: 10)\n .stroke(borderColor, lineWidth: 1)\n )\n }\n .buttonStyle(.plain)\n }\n \n private var simpleLinkView: some View {\n Button(action: {\n #if os(iOS)\n UIApplication.shared.open(url)\n #else\n NSWorkspace.shared.open(url)\n #endif\n }) {\n HStack(spacing: 12) {\n // Link icon\n Image(systemName: \"link.circle.fill\")\n .font(.system(size: 32))\n .foregroundColor(Color.blue.opacity(0.8))\n .frame(width: 40, height: 40)\n \n VStack(alignment: .leading, spacing: 4) {\n // Title\n Text(title ?? url.host ?? \"Link\")\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(textColor)\n .lineLimit(2)\n .multilineTextAlignment(.leading)\n \n // URL\n Text(url.absoluteString)\n .font(.system(size: 11, design: .monospaced))\n .foregroundColor(Color.blue)\n .lineLimit(1)\n .truncationMode(.middle)\n }\n \n Spacer()\n \n // Arrow indicator\n Image(systemName: \"chevron.right\")\n .font(.system(size: 14))\n .foregroundColor(textColor.opacity(0.5))\n }\n .padding(12)\n .frame(maxWidth: .infinity, alignment: .leading)\n .background(\n RoundedRectangle(cornerRadius: 10)\n .fill(colorScheme == .dark ? Color.gray.opacity(0.15) : Color.gray.opacity(0.08))\n )\n .overlay(\n RoundedRectangle(cornerRadius: 10)\n .stroke(borderColor, lineWidth: 1)\n )\n }\n .buttonStyle(.plain)\n }\n \n private func loadFromCacheOrFetch() {\n #if os(iOS)\n // Check if we already have data in state\n guard metadata == nil && !isLoading else { \n return \n }\n \n // Check cache first\n if let cached = LinkMetadataCache.shared.getCachedMetadata(for: url) {\n // print(\"🔗 LinkPreviewView: Using CACHED metadata for: \\(url.absoluteString)\")\n self.metadata = cached.metadata\n self.cachedTitle = cached.title ?? cached.metadata?.title\n self.cachedHost = cached.host ?? url.host\n self.previewImage = cached.image\n return\n }\n \n // Not in cache, fetch it\n // print(\"🔗 LinkPreviewView: FETCHING metadata for: \\(url.absoluteString)\")\n isLoading = true\n \n let provider = LPMetadataProvider()\n provider.startFetchingMetadata(for: url) { fetchedMetadata, error in\n DispatchQueue.main.async {\n self.isLoading = false\n \n if let error = error {\n // Check if it's an ATS error for subresources (non-critical)\n let errorString = error.localizedDescription.lowercased()\n let isATSError = errorString.contains(\"app transport security\") || \n errorString.contains(\"secure connection\")\n \n if !isATSError {\n // Only log non-ATS errors\n // print(\"🔗 LinkPreviewView: Error fetching metadata: \\(error)\")\n }\n \n // Still try to show basic preview with URL info\n self.cachedTitle = self.title ?? self.url.host\n self.cachedHost = self.url.host\n \n // Cache even failed attempts to avoid repeated fetches\n LinkMetadataCache.shared.cacheMetadata(\n nil,\n title: self.cachedTitle,\n host: self.cachedHost,\n image: nil,\n for: self.url\n )\n return\n }\n \n if let fetchedMetadata = fetchedMetadata {\n // Use the fetched metadata, or create new with our title\n if let title = self.title, !title.isEmpty {\n fetchedMetadata.title = title\n }\n self.metadata = fetchedMetadata\n self.cachedTitle = fetchedMetadata.title ?? self.title\n self.cachedHost = self.url.host\n \n // Try to extract image\n if let imageProvider = fetchedMetadata.imageProvider {\n imageProvider.loadObject(ofClass: UIImage.self) { image, error in\n DispatchQueue.main.async {\n if let image = image as? UIImage {\n self.previewImage = image\n // Cache everything including the image\n LinkMetadataCache.shared.cacheMetadata(\n fetchedMetadata,\n title: self.cachedTitle,\n host: self.cachedHost,\n image: image,\n for: self.url\n )\n } else {\n // Cache without image\n LinkMetadataCache.shared.cacheMetadata(\n fetchedMetadata,\n title: self.cachedTitle,\n host: self.cachedHost,\n image: nil,\n for: self.url\n )\n }\n }\n }\n } else {\n // No image, cache what we have\n LinkMetadataCache.shared.cacheMetadata(\n fetchedMetadata,\n title: self.cachedTitle,\n host: self.cachedHost,\n image: nil,\n for: self.url\n )\n }\n }\n }\n }\n #endif\n }\n}\n\n#if os(iOS)\n// UIViewRepresentable wrapper for LPLinkView\nstruct LinkPreview: UIViewRepresentable {\n let metadata: LPLinkMetadata\n \n func makeUIView(context: Context) -> UIView {\n let containerView = UIView()\n containerView.backgroundColor = .clear\n \n let linkView = LPLinkView(metadata: metadata)\n linkView.isUserInteractionEnabled = false // We handle taps at the SwiftUI level\n linkView.translatesAutoresizingMaskIntoConstraints = false\n \n containerView.addSubview(linkView)\n NSLayoutConstraint.activate([\n linkView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),\n linkView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),\n linkView.topAnchor.constraint(equalTo: containerView.topAnchor),\n linkView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)\n ])\n \n return containerView\n }\n \n func updateUIView(_ uiView: UIView, context: Context) {\n // Update if needed\n }\n}\n#endif\n\n// Helper to extract URLs from text\nextension String {\n func extractURLs() -> [(url: URL, range: Range)] {\n var urls: [(URL, Range)] = []\n \n // Check for plain URLs\n let types: NSTextCheckingResult.CheckingType = .link\n if let detector = try? NSDataDetector(types: types.rawValue) {\n let matches = detector.matches(in: self, range: NSRange(location: 0, length: self.utf16.count))\n for match in matches {\n if let range = Range(match.range, in: self),\n let url = match.url {\n urls.append((url, range))\n }\n }\n }\n \n return urls\n }\n}\n\n#Preview {\n VStack {\n LinkPreviewView(url: URL(string: \"https://example.com\")!, title: \"Example Website\")\n .padding()\n }\n}\n"], ["/bitchat/bitchat/Noise/NoiseHandshakeCoordinator.swift", "//\n// NoiseHandshakeCoordinator.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\n\n/// Coordinates Noise handshakes to prevent race conditions and ensure reliable encryption establishment\nclass NoiseHandshakeCoordinator {\n \n // MARK: - Handshake State\n \n enum HandshakeState: Equatable {\n case idle\n case waitingToInitiate(since: Date)\n case initiating(attempt: Int, lastAttempt: Date)\n case responding(since: Date)\n case waitingForResponse(messagesSent: [Data], timeout: Date)\n case established(since: Date)\n case failed(reason: String, canRetry: Bool, lastAttempt: Date)\n \n var isActive: Bool {\n switch self {\n case .idle, .established, .failed:\n return false\n default:\n return true\n }\n }\n }\n \n // MARK: - Properties\n \n private var handshakeStates: [String: HandshakeState] = [:]\n private var handshakeQueue = DispatchQueue(label: \"chat.bitchat.noise.handshake\", attributes: .concurrent)\n \n // Configuration\n private let maxHandshakeAttempts = 3\n private let handshakeTimeout: TimeInterval = 10.0\n private let retryDelay: TimeInterval = 2.0\n private let minTimeBetweenHandshakes: TimeInterval = 1.0 // Reduced from 5.0 for faster recovery\n \n // Track handshake messages to detect duplicates\n private var processedHandshakeMessages: Set = []\n private let messageHistoryLimit = 100\n \n // MARK: - Role Determination\n \n /// Deterministically determine who should initiate the handshake\n /// Lower peer ID becomes the initiator to prevent simultaneous attempts\n func determineHandshakeRole(myPeerID: String, remotePeerID: String) -> NoiseRole {\n // Use simple string comparison for deterministic ordering\n return myPeerID < remotePeerID ? .initiator : .responder\n }\n \n /// Check if we should initiate handshake with a peer\n func shouldInitiateHandshake(myPeerID: String, remotePeerID: String, forceIfStale: Bool = false) -> Bool {\n return handshakeQueue.sync {\n // Check if we're already in an active handshake\n if let state = handshakeStates[remotePeerID], state.isActive {\n // Check if the handshake is stale and we should force a new one\n if forceIfStale {\n switch state {\n case .initiating(_, let lastAttempt):\n if Date().timeIntervalSince(lastAttempt) > handshakeTimeout {\n SecureLogger.log(\"Forcing new handshake with \\(remotePeerID) - previous stuck in initiating\", \n category: SecureLogger.handshake, level: .warning)\n return true\n }\n default:\n break\n }\n }\n \n SecureLogger.log(\"Already in active handshake with \\(remotePeerID), state: \\(state)\", \n category: SecureLogger.handshake, level: .debug)\n return false\n }\n \n // Check role\n let role = determineHandshakeRole(myPeerID: myPeerID, remotePeerID: remotePeerID)\n if role != .initiator {\n SecureLogger.log(\"Not initiator for handshake with \\(remotePeerID) (my: \\(myPeerID), their: \\(remotePeerID))\", \n category: SecureLogger.handshake, level: .debug)\n return false\n }\n \n // Check if we've failed recently and can't retry yet\n if case .failed(_, let canRetry, let lastAttempt) = handshakeStates[remotePeerID] {\n if !canRetry {\n return false\n }\n if Date().timeIntervalSince(lastAttempt) < retryDelay {\n return false\n }\n }\n \n return true\n }\n }\n \n /// Record that we're initiating a handshake\n func recordHandshakeInitiation(peerID: String) {\n handshakeQueue.async(flags: .barrier) {\n let attempt = self.getCurrentAttempt(for: peerID) + 1\n self.handshakeStates[peerID] = .initiating(attempt: attempt, lastAttempt: Date())\n SecureLogger.log(\"Recording handshake initiation with \\(peerID), attempt \\(attempt)\", \n category: SecureLogger.handshake, level: .info)\n }\n }\n \n /// Record that we're responding to a handshake\n func recordHandshakeResponse(peerID: String) {\n handshakeQueue.async(flags: .barrier) {\n self.handshakeStates[peerID] = .responding(since: Date())\n SecureLogger.log(\"Recording handshake response to \\(peerID)\", \n category: SecureLogger.handshake, level: .info)\n }\n }\n \n /// Record successful handshake completion\n func recordHandshakeSuccess(peerID: String) {\n handshakeQueue.async(flags: .barrier) {\n self.handshakeStates[peerID] = .established(since: Date())\n SecureLogger.log(\"Handshake successfully established with \\(peerID)\", \n category: SecureLogger.handshake, level: .info)\n }\n }\n \n /// Record handshake failure\n func recordHandshakeFailure(peerID: String, reason: String) {\n handshakeQueue.async(flags: .barrier) {\n let attempts = self.getCurrentAttempt(for: peerID)\n let canRetry = attempts < self.maxHandshakeAttempts\n self.handshakeStates[peerID] = .failed(reason: reason, canRetry: canRetry, lastAttempt: Date())\n SecureLogger.log(\"Handshake failed with \\(peerID): \\(reason), canRetry: \\(canRetry)\", \n category: SecureLogger.handshake, level: .warning)\n }\n }\n \n /// Check if we should accept an incoming handshake initiation\n func shouldAcceptHandshakeInitiation(myPeerID: String, remotePeerID: String) -> Bool {\n return handshakeQueue.sync {\n // If we're already established, reject new handshakes\n if case .established = handshakeStates[remotePeerID] {\n SecureLogger.log(\"Rejecting handshake from \\(remotePeerID) - already established\", \n category: SecureLogger.handshake, level: .debug)\n return false\n }\n \n let role = determineHandshakeRole(myPeerID: myPeerID, remotePeerID: remotePeerID)\n \n // If we're the initiator and already initiating, this is a race condition\n if role == .initiator {\n if case .initiating = handshakeStates[remotePeerID] {\n // They shouldn't be initiating, but accept it to recover from race condition\n SecureLogger.log(\"Accepting handshake from \\(remotePeerID) despite being initiator (race condition recovery)\", \n category: SecureLogger.handshake, level: .warning)\n return true\n }\n }\n \n // If we're the responder, we should accept\n return true\n }\n }\n \n /// Check if this is a duplicate handshake message\n func isDuplicateHandshakeMessage(_ data: Data) -> Bool {\n return handshakeQueue.sync {\n if processedHandshakeMessages.contains(data) {\n return true\n }\n \n // Add to processed messages with size limit\n if processedHandshakeMessages.count >= messageHistoryLimit {\n processedHandshakeMessages.removeAll()\n }\n processedHandshakeMessages.insert(data)\n return false\n }\n }\n \n /// Get time to wait before next handshake attempt\n func getRetryDelay(for peerID: String) -> TimeInterval? {\n return handshakeQueue.sync {\n guard let state = handshakeStates[peerID] else { return nil }\n \n switch state {\n case .failed(_, let canRetry, let lastAttempt):\n if !canRetry { return nil }\n let timeSinceFailure = Date().timeIntervalSince(lastAttempt)\n if timeSinceFailure >= retryDelay {\n return 0\n }\n return retryDelay - timeSinceFailure\n \n case .initiating(_, let lastAttempt):\n let timeSinceAttempt = Date().timeIntervalSince(lastAttempt)\n if timeSinceAttempt >= minTimeBetweenHandshakes {\n return 0\n }\n return minTimeBetweenHandshakes - timeSinceAttempt\n \n default:\n return nil\n }\n }\n }\n \n /// Reset handshake state for a peer\n func resetHandshakeState(for peerID: String) {\n handshakeQueue.async(flags: .barrier) {\n self.handshakeStates.removeValue(forKey: peerID)\n SecureLogger.log(\"Reset handshake state for \\(peerID)\", \n category: SecureLogger.handshake, level: .debug)\n }\n }\n \n /// Clean up stale handshake states\n func cleanupStaleHandshakes(staleTimeout: TimeInterval = 30.0) -> [String] {\n return handshakeQueue.sync {\n let now = Date()\n var stalePeerIDs: [String] = []\n \n for (peerID, state) in handshakeStates {\n var isStale = false\n \n switch state {\n case .initiating(_, let lastAttempt):\n if now.timeIntervalSince(lastAttempt) > staleTimeout {\n isStale = true\n }\n case .responding(let since):\n if now.timeIntervalSince(since) > staleTimeout {\n isStale = true\n }\n case .waitingForResponse(_, let timeout):\n if now > timeout {\n isStale = true\n }\n default:\n break\n }\n \n if isStale {\n stalePeerIDs.append(peerID)\n SecureLogger.log(\"Found stale handshake state for \\(peerID): \\(state)\", \n category: SecureLogger.handshake, level: .warning)\n }\n }\n \n // Clean up stale states\n for peerID in stalePeerIDs {\n handshakeStates.removeValue(forKey: peerID)\n }\n \n return stalePeerIDs\n }\n }\n \n /// Get current handshake state\n func getHandshakeState(for peerID: String) -> HandshakeState {\n return handshakeQueue.sync {\n return handshakeStates[peerID] ?? .idle\n }\n }\n \n /// Get current retry count for a peer\n func getRetryCount(for peerID: String) -> Int {\n return handshakeQueue.sync {\n switch handshakeStates[peerID] {\n case .initiating(let attempt, _):\n return attempt - 1 // Attempts start at 1, retries start at 0\n default:\n return 0\n }\n }\n }\n \n /// Increment retry count for a peer\n func incrementRetryCount(for peerID: String) {\n handshakeQueue.async(flags: .barrier) {\n let currentAttempt = self.getCurrentAttempt(for: peerID)\n self.handshakeStates[peerID] = .initiating(attempt: currentAttempt + 1, lastAttempt: Date())\n }\n }\n \n // MARK: - Private Helpers\n \n private func getCurrentAttempt(for peerID: String) -> Int {\n switch handshakeStates[peerID] {\n case .initiating(let attempt, _):\n return attempt\n case .failed(_, _, _):\n // Count previous attempts\n return 1 // Simplified for now\n default:\n return 0\n }\n }\n \n /// Log current handshake states for debugging\n func logHandshakeStates() {\n handshakeQueue.sync {\n SecureLogger.log(\"=== Handshake States ===\", category: SecureLogger.handshake, level: .debug)\n for (peerID, state) in handshakeStates {\n let stateDesc: String\n switch state {\n case .idle:\n stateDesc = \"idle\"\n case .waitingToInitiate(let since):\n stateDesc = \"waiting to initiate (since \\(since))\"\n case .initiating(let attempt, let lastAttempt):\n stateDesc = \"initiating (attempt \\(attempt), last: \\(lastAttempt))\"\n case .responding(let since):\n stateDesc = \"responding (since: \\(since))\"\n case .waitingForResponse(let messages, let timeout):\n stateDesc = \"waiting for response (\\(messages.count) messages, timeout: \\(timeout))\"\n case .established(let since):\n stateDesc = \"established (since \\(since))\"\n case .failed(let reason, let canRetry, let lastAttempt):\n stateDesc = \"failed: \\(reason) (canRetry: \\(canRetry), last: \\(lastAttempt))\"\n }\n SecureLogger.log(\" \\(peerID): \\(stateDesc)\", category: SecureLogger.handshake, level: .debug)\n }\n SecureLogger.log(\"========================\", category: SecureLogger.handshake, level: .debug)\n }\n }\n \n /// Clear all handshake states - used during panic mode\n func clearAllHandshakeStates() {\n handshakeQueue.async(flags: .barrier) {\n SecureLogger.log(\"Clearing all handshake states for panic mode\", category: SecureLogger.handshake, level: .warning)\n self.handshakeStates.removeAll()\n self.processedHandshakeMessages.removeAll()\n }\n }\n}"], ["/bitchat/bitchat/Identity/IdentityModels.swift", "//\n// IdentityModels.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # IdentityModels\n///\n/// Defines BitChat's innovative three-layer identity model that balances\n/// privacy, security, and usability in a decentralized mesh network.\n///\n/// ## Overview\n/// BitChat's identity system separates concerns across three distinct layers:\n/// 1. **Ephemeral Identity**: Short-lived, rotatable peer IDs for privacy\n/// 2. **Cryptographic Identity**: Long-term Noise static keys for security\n/// 3. **Social Identity**: User-assigned names and trust relationships\n///\n/// This separation allows users to maintain stable cryptographic identities\n/// while frequently rotating their network identifiers for privacy.\n///\n/// ## Three-Layer Architecture\n///\n/// ### Layer 1: Ephemeral Identity\n/// - Random 8-byte peer IDs that rotate periodically\n/// - Provides network-level privacy and prevents tracking\n/// - Changes don't affect cryptographic relationships\n/// - Includes handshake state tracking\n///\n/// ### Layer 2: Cryptographic Identity\n/// - Based on Noise Protocol static key pairs\n/// - Fingerprint derived from SHA256 of public key\n/// - Enables end-to-end encryption and authentication\n/// - Persists across peer ID rotations\n///\n/// ### Layer 3: Social Identity\n/// - User-assigned names (petnames) for contacts\n/// - Trust levels from unknown to verified\n/// - Favorite/blocked status\n/// - Personal notes and metadata\n///\n/// ## Privacy Design\n/// The model is designed with privacy-first principles:\n/// - No mandatory persistent storage\n/// - Optional identity caching with user consent\n/// - Ephemeral IDs prevent long-term tracking\n/// - Social mappings stored locally only\n///\n/// ## Trust Model\n/// Four levels of trust:\n/// 1. **Unknown**: New or unverified peers\n/// 2. **Casual**: Basic interaction history\n/// 3. **Trusted**: User has explicitly trusted\n/// 4. **Verified**: Cryptographic verification completed\n///\n/// ## Identity Resolution\n/// When a peer rotates their ephemeral ID:\n/// 1. Cryptographic handshake reveals their fingerprint\n/// 2. System looks up social identity by fingerprint\n/// 3. UI seamlessly maintains user relationships\n/// 4. Historical messages remain properly attributed\n///\n/// ## Conflict Resolution\n/// Handles edge cases like:\n/// - Multiple peers claiming same nickname\n/// - Nickname changes and conflicts\n/// - Identity rotation during active chats\n/// - Network partitions and rejoins\n///\n/// ## Usage Example\n/// ```swift\n/// // When peer connects with new ID\n/// let ephemeral = EphemeralIdentity(peerID: \"abc123\", ...)\n/// // After handshake\n/// let crypto = CryptographicIdentity(fingerprint: \"sha256...\", ...)\n/// // User assigns name\n/// let social = SocialIdentity(localPetname: \"Alice\", ...)\n/// ```\n///\n\nimport Foundation\n\n// MARK: - Three-Layer Identity Model\n\n/// Represents the ephemeral layer of identity - short-lived peer IDs that provide network privacy.\n/// These IDs rotate periodically to prevent tracking while maintaining cryptographic relationships.\nstruct EphemeralIdentity {\n let peerID: String // 8 random bytes\n let sessionStart: Date\n var handshakeState: HandshakeState\n}\n\nenum HandshakeState {\n case none\n case initiated\n case inProgress\n case completed(fingerprint: String)\n case failed(reason: String)\n}\n\n/// Represents the cryptographic layer of identity - the stable Noise Protocol static key pair.\n/// This identity persists across ephemeral ID rotations and enables secure communication.\n/// The fingerprint serves as the permanent identifier for a peer's cryptographic identity.\nstruct CryptographicIdentity: Codable {\n let fingerprint: String // SHA256 of public key\n let publicKey: Data // Noise static public key\n let firstSeen: Date\n let lastHandshake: Date?\n}\n\n/// Represents the social layer of identity - user-assigned names and trust relationships.\n/// This layer provides human-friendly identification and relationship management.\n/// All data in this layer is local-only and never transmitted over the network.\nstruct SocialIdentity: Codable {\n let fingerprint: String\n var localPetname: String? // User's name for this peer\n var claimedNickname: String // What peer calls themselves\n var trustLevel: TrustLevel\n var isFavorite: Bool\n var isBlocked: Bool\n var notes: String?\n}\n\nenum TrustLevel: String, Codable {\n case unknown = \"unknown\"\n case casual = \"casual\"\n case trusted = \"trusted\"\n case verified = \"verified\"\n}\n\n// MARK: - Identity Cache\n\n/// Persistent storage for identity mappings and relationships.\n/// Provides efficient lookup between fingerprints, nicknames, and social identities.\n/// Storage is optional and controlled by user privacy settings.\nstruct IdentityCache: Codable {\n // Fingerprint -> Social mapping\n var socialIdentities: [String: SocialIdentity] = [:]\n \n // Nickname -> [Fingerprints] reverse index\n // Multiple fingerprints can claim same nickname\n var nicknameIndex: [String: Set] = [:]\n \n // Verified fingerprints (cryptographic proof)\n var verifiedFingerprints: Set = []\n \n // Last interaction timestamps (privacy: optional)\n var lastInteractions: [String: Date] = [:] \n \n // Schema version for future migrations\n var version: Int = 1\n}\n\n// MARK: - Identity Resolution\n\nenum IdentityHint {\n case unknown\n case likelyKnown(fingerprint: String)\n case ambiguous(candidates: Set)\n case verified(fingerprint: String)\n}\n\n// MARK: - Pending Actions\n\nstruct PendingActions {\n var toggleFavorite: Bool?\n var setTrustLevel: TrustLevel?\n var setPetname: String?\n}\n\n// MARK: - Privacy Settings\n\nstruct PrivacySettings: Codable {\n // Level 1: Maximum privacy (default)\n var persistIdentityCache = false\n var showLastSeen = false\n \n // Level 2: Convenience\n var autoAcceptKnownFingerprints = false\n var rememberNicknameHistory = false\n \n // Level 3: Social\n var shareTrustNetworkHints = false // \"3 mutual contacts trust this person\"\n}\n\n// MARK: - Conflict Resolution\n\n/// Strategies for resolving identity conflicts in the decentralized network.\n/// Handles cases where multiple peers claim the same nickname or when\n/// identity mappings become ambiguous due to network partitions.\nenum ConflictResolution {\n case acceptNew(petname: String) // \"John (2)\"\n case rejectNew\n case blockFingerprint(String)\n case alertUser(message: String)\n}\n\n// MARK: - UI State\n\nstruct PeerUIState {\n let peerID: String\n let nickname: String\n var identityState: IdentityState\n var connectionQuality: ConnectionQuality\n \n enum IdentityState {\n case unknown // Gray - No identity info\n case unverifiedKnown(String) // Blue - Handshake done, matches cache\n case verified(String) // Green - Cryptographically verified\n case conflict(String, String) // Red - Nickname doesn't match fingerprint\n case pending // Yellow - Handshake in progress\n }\n}\n\nenum ConnectionQuality {\n case excellent\n case good\n case poor\n case disconnected\n}\n\n// MARK: - Migration Support\n// Removed LegacyFavorite - no longer needed"], ["/bitchat/bitchat/Utils/SecureLogger.swift", "//\n// SecureLogger.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport os.log\n\n/// Centralized security-aware logging framework\n/// Provides safe logging that filters sensitive data and security events\nclass SecureLogger {\n \n // MARK: - Log Categories\n \n private static let subsystem = \"chat.bitchat\"\n \n static let noise = OSLog(subsystem: subsystem, category: \"noise\")\n static let encryption = OSLog(subsystem: subsystem, category: \"encryption\")\n static let keychain = OSLog(subsystem: subsystem, category: \"keychain\")\n static let session = OSLog(subsystem: subsystem, category: \"session\")\n static let security = OSLog(subsystem: subsystem, category: \"security\")\n static let handshake = OSLog(subsystem: subsystem, category: \"handshake\")\n \n // MARK: - Timestamp Formatter\n \n private static let timestampFormatter: DateFormatter = {\n let formatter = DateFormatter()\n formatter.dateFormat = \"HH:mm:ss.SSS\"\n formatter.timeZone = TimeZone.current\n return formatter\n }()\n \n // MARK: - Cached Regex Patterns\n \n private static let fingerprintPattern = #/[a-fA-F0-9]{64}/#\n private static let base64Pattern = #/[A-Za-z0-9+/]{40,}={0,2}/#\n private static let passwordPattern = #/password[\"\\s:=]+[\"']?[^\"'\\s]+[\"']?/#\n private static let peerIDPattern = #/peerID: ([a-zA-Z0-9]{8})[a-zA-Z0-9]+/#\n \n // MARK: - Sanitization Cache\n \n private static let sanitizationCache: NSCache = {\n let cache = NSCache()\n cache.countLimit = 100 // Keep last 100 sanitized strings\n return cache\n }()\n private static let cacheQueue = DispatchQueue(label: \"chat.bitchat.securelogger.cache\", attributes: .concurrent)\n \n // MARK: - Log Levels\n \n enum LogLevel {\n case debug\n case info\n case warning\n case error\n case fault\n \n var osLogType: OSLogType {\n switch self {\n case .debug: return .debug\n case .info: return .info\n case .warning: return .default\n case .error: return .error\n case .fault: return .fault\n }\n }\n }\n \n // MARK: - Security Event Types\n \n enum SecurityEvent {\n case handshakeStarted(peerID: String)\n case handshakeCompleted(peerID: String)\n case handshakeFailed(peerID: String, error: String)\n case sessionExpired(peerID: String)\n case authenticationFailed(peerID: String)\n \n var message: String {\n switch self {\n case .handshakeStarted(let peerID):\n return \"Handshake started with peer: \\(sanitize(peerID))\"\n case .handshakeCompleted(let peerID):\n return \"Handshake completed with peer: \\(sanitize(peerID))\"\n case .handshakeFailed(let peerID, let error):\n return \"Handshake failed with peer: \\(sanitize(peerID)), error: \\(error)\"\n case .sessionExpired(let peerID):\n return \"Session expired for peer: \\(sanitize(peerID))\"\n case .authenticationFailed(let peerID):\n return \"Authentication failed for peer: \\(sanitize(peerID))\"\n }\n }\n }\n \n // MARK: - Public Logging Methods\n \n /// Log a security event\n static func logSecurityEvent(_ event: SecurityEvent, level: LogLevel = .info, \n file: String = #file, line: Int = #line, function: String = #function) {\n let location = formatLocation(file: file, line: line, function: function)\n let message = \"\\(location) \\(event.message)\"\n \n #if DEBUG\n os_log(\"%{public}@\", log: security, type: level.osLogType, message)\n #else\n // In release, use private logging to prevent sensitive data exposure\n os_log(\"%{private}@\", log: security, type: level.osLogType, message)\n #endif\n }\n \n /// Log general messages with automatic sensitive data filtering\n static func log(_ message: String, category: OSLog = noise, level: LogLevel = .debug,\n file: String = #file, line: Int = #line, function: String = #function) {\n let location = formatLocation(file: file, line: line, function: function)\n let sanitized = sanitize(\"\\(location) \\(message)\")\n \n #if DEBUG\n os_log(\"%{public}@\", log: category, type: level.osLogType, sanitized)\n #else\n // In release builds, only log non-debug messages\n if level != .debug {\n os_log(\"%{private}@\", log: category, type: level.osLogType, sanitized)\n }\n #endif\n }\n \n /// Log errors with context\n static func logError(_ error: Error, context: String, category: OSLog = noise,\n file: String = #file, line: Int = #line, function: String = #function) {\n let location = formatLocation(file: file, line: line, function: function)\n let sanitized = sanitize(context)\n let errorDesc = sanitize(error.localizedDescription)\n \n #if DEBUG\n os_log(\"%{public}@ Error in %{public}@: %{public}@\", log: category, type: .error, location, sanitized, errorDesc)\n #else\n os_log(\"%{private}@ Error in %{private}@: %{private}@\", log: category, type: .error, location, sanitized, errorDesc)\n #endif\n }\n \n // MARK: - Private Helpers\n \n /// Format location information for logging\n private static func formatLocation(file: String, line: Int, function: String) -> String {\n let fileName = (file as NSString).lastPathComponent\n let timestamp = timestampFormatter.string(from: Date())\n return \"[\\(timestamp)] [\\(fileName):\\(line) \\(function)]\"\n }\n \n /// Sanitize strings to remove potentially sensitive data\n private static func sanitize(_ input: String) -> String {\n let key = input as NSString\n \n // Check cache first\n var cachedValue: String?\n cacheQueue.sync {\n cachedValue = sanitizationCache.object(forKey: key) as String?\n }\n \n if let cached = cachedValue {\n return cached\n }\n \n // Perform sanitization\n var sanitized = input\n \n // Remove full fingerprints (keep first 8 chars for debugging)\n sanitized = sanitized.replacing(fingerprintPattern) { match in\n let fingerprint = String(match.output)\n return String(fingerprint.prefix(8)) + \"...\"\n }\n \n // Remove base64 encoded data that might be keys\n sanitized = sanitized.replacing(base64Pattern) { _ in\n \"\"\n }\n \n // Remove potential passwords (assuming they're in quotes or after \"password:\")\n sanitized = sanitized.replacing(passwordPattern) { _ in\n \"password: \"\n }\n \n // Truncate peer IDs to first 8 characters\n sanitized = sanitized.replacing(peerIDPattern) { match in\n \"peerID: \\(match.1)...\"\n }\n \n // Cache the result\n cacheQueue.async(flags: .barrier) {\n sanitizationCache.setObject(sanitized as NSString, forKey: key)\n }\n \n return sanitized\n }\n \n /// Sanitize individual values\n private static func sanitize(_ value: T) -> String {\n let stringValue = String(describing: value)\n return sanitize(stringValue)\n }\n}\n\n// MARK: - Convenience Extensions\n\nextension SecureLogger {\n \n /// Log handshake events\n static func logHandshake(_ phase: String, peerID: String, success: Bool = true,\n file: String = #file, line: Int = #line, function: String = #function) {\n if success {\n log(\"Handshake \\(phase) with peer: \\(peerID)\", category: session, level: .info,\n file: file, line: line, function: function)\n } else {\n log(\"Handshake \\(phase) failed with peer: \\(peerID)\", category: session, level: .warning,\n file: file, line: line, function: function)\n }\n }\n \n /// Log encryption operations\n static func logEncryption(_ operation: String, success: Bool = true,\n file: String = #file, line: Int = #line, function: String = #function) {\n let level: LogLevel = success ? .debug : .error\n log(\"Encryption operation '\\(operation)' \\(success ? \"succeeded\" : \"failed\")\", \n category: encryption, level: level, file: file, line: line, function: function)\n }\n \n /// Log key management operations\n static func logKeyOperation(_ operation: String, keyType: String, success: Bool = true,\n file: String = #file, line: Int = #line, function: String = #function) {\n let level: LogLevel = success ? .info : .error\n log(\"Key operation '\\(operation)' for \\(keyType) \\(success ? \"succeeded\" : \"failed\")\", \n category: keychain, level: level, file: file, line: line, function: function)\n }\n}\n\n// MARK: - Migration Helper\n\n/// Helper to migrate from print statements to SecureLogger\n/// Usage: Replace print(...) with secureLog(...)\nfunc secureLog(_ items: Any..., separator: String = \" \", terminator: String = \"\\n\",\n file: String = #file, line: Int = #line, function: String = #function) {\n #if DEBUG\n let message = items.map { String(describing: $0) }.joined(separator: separator)\n SecureLogger.log(message, level: .debug, file: file, line: line, function: function)\n #endif\n}\n"], ["/bitchat/bitchat/Views/AppInfoView.swift", "import SwiftUI\n\nstruct AppInfoView: View {\n @Environment(\\.dismiss) var dismiss\n @Environment(\\.colorScheme) var colorScheme\n \n private var backgroundColor: Color {\n colorScheme == .dark ? Color.black : Color.white\n }\n \n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n private var secondaryTextColor: Color {\n colorScheme == .dark ? Color.green.opacity(0.8) : Color(red: 0, green: 0.5, blue: 0).opacity(0.8)\n }\n \n // MARK: - Constants\n private enum Strings {\n static let appName = \"bitchat\"\n static let tagline = \"mesh sidegroupchat\"\n \n enum Features {\n static let title = \"FEATURES\"\n static let offlineComm = (\"wifi.slash\", \"offline communication\", \"works without internet using Bluetooth low energy\")\n static let encryption = (\"lock.shield\", \"end-to-end encryption\", \"private messages encrypted with noise protocol\")\n static let extendedRange = (\"antenna.radiowaves.left.and.right\", \"extended range\", \"messages relay through peers, going the distance\")\n static let favorites = (\"star.fill\", \"favorites\", \"get notified when your favorite people join\")\n static let mentions = (\"at\", \"mentions\", \"use @nickname to notify specific people\")\n }\n \n enum Privacy {\n static let title = \"PRIVACY\"\n static let noTracking = (\"eye.slash\", \"no tracking\", \"no servers, accounts, or data collection\")\n static let ephemeral = (\"shuffle\", \"ephemeral identity\", \"new peer ID generated regularly\")\n static let panic = (\"hand.raised.fill\", \"panic mode\", \"triple-tap logo to instantly clear all data\")\n }\n \n enum HowToUse {\n static let title = \"HOW TO USE\"\n static let instructions = [\n \"• set your nickname by tapping it\",\n \"• swipe left for sidebar\",\n \"• tap a peer to start a private chat\",\n \"• use @nickname to mention someone\",\n \"• triple-tap chat to clear\"\n ]\n }\n \n enum Warning {\n static let title = \"WARNING\"\n static let message = \"private message security has not yet been fully audited. do not use for critical situations until this warning disappears.\"\n }\n }\n \n var body: some View {\n #if os(macOS)\n VStack(spacing: 0) {\n // Custom header for macOS\n HStack {\n Spacer()\n Button(\"DONE\") {\n dismiss()\n }\n .buttonStyle(.plain)\n .foregroundColor(textColor)\n .padding()\n }\n .background(backgroundColor.opacity(0.95))\n \n ScrollView {\n infoContent\n }\n .background(backgroundColor)\n }\n .frame(width: 600, height: 700)\n #else\n NavigationView {\n ScrollView {\n infoContent\n }\n .background(backgroundColor)\n .navigationBarTitleDisplayMode(.inline)\n .toolbar {\n ToolbarItem(placement: .navigationBarTrailing) {\n Button(\"DONE\") {\n dismiss()\n }\n .foregroundColor(textColor)\n }\n }\n }\n #endif\n }\n \n @ViewBuilder\n private var infoContent: some View {\n VStack(alignment: .leading, spacing: 24) {\n // Header\n VStack(alignment: .center, spacing: 8) {\n Text(Strings.appName)\n .font(.system(size: 32, weight: .bold, design: .monospaced))\n .foregroundColor(textColor)\n \n Text(Strings.tagline)\n .font(.system(size: 16, design: .monospaced))\n .foregroundColor(secondaryTextColor)\n }\n .frame(maxWidth: .infinity)\n .padding(.vertical)\n \n // Features\n VStack(alignment: .leading, spacing: 16) {\n SectionHeader(Strings.Features.title)\n \n FeatureRow(icon: Strings.Features.offlineComm.0, \n title: Strings.Features.offlineComm.1,\n description: Strings.Features.offlineComm.2)\n \n FeatureRow(icon: Strings.Features.encryption.0,\n title: Strings.Features.encryption.1,\n description: Strings.Features.encryption.2)\n \n FeatureRow(icon: Strings.Features.extendedRange.0,\n title: Strings.Features.extendedRange.1,\n description: Strings.Features.extendedRange.2)\n \n FeatureRow(icon: Strings.Features.favorites.0,\n title: Strings.Features.favorites.1,\n description: Strings.Features.favorites.2)\n \n FeatureRow(icon: Strings.Features.mentions.0,\n title: Strings.Features.mentions.1,\n description: Strings.Features.mentions.2)\n }\n \n // Privacy\n VStack(alignment: .leading, spacing: 16) {\n SectionHeader(Strings.Privacy.title)\n \n FeatureRow(icon: Strings.Privacy.noTracking.0,\n title: Strings.Privacy.noTracking.1,\n description: Strings.Privacy.noTracking.2)\n \n FeatureRow(icon: Strings.Privacy.ephemeral.0,\n title: Strings.Privacy.ephemeral.1,\n description: Strings.Privacy.ephemeral.2)\n \n FeatureRow(icon: Strings.Privacy.panic.0,\n title: Strings.Privacy.panic.1,\n description: Strings.Privacy.panic.2)\n }\n \n // How to Use\n VStack(alignment: .leading, spacing: 16) {\n SectionHeader(Strings.HowToUse.title)\n \n VStack(alignment: .leading, spacing: 8) {\n ForEach(Strings.HowToUse.instructions, id: \\.self) { instruction in\n Text(instruction)\n }\n }\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(textColor)\n }\n \n // Warning\n VStack(alignment: .leading, spacing: 6) {\n SectionHeader(Strings.Warning.title)\n .foregroundColor(Color.red)\n \n Text(Strings.Warning.message)\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(Color.red)\n .fixedSize(horizontal: false, vertical: true)\n }\n .padding(.top, 6)\n .padding(.bottom, 16)\n .padding(.horizontal)\n .background(Color.red.opacity(0.1))\n .cornerRadius(8)\n \n .padding(.top)\n }\n .padding()\n }\n}\n\nstruct SectionHeader: View {\n let title: String\n @Environment(\\.colorScheme) var colorScheme\n \n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n init(_ title: String) {\n self.title = title\n }\n \n var body: some View {\n Text(title)\n .font(.system(size: 16, weight: .bold, design: .monospaced))\n .foregroundColor(textColor)\n .padding(.top, 8)\n }\n}\n\nstruct FeatureRow: View {\n let icon: String\n let title: String\n let description: String\n @Environment(\\.colorScheme) var colorScheme\n \n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n private var secondaryTextColor: Color {\n colorScheme == .dark ? Color.green.opacity(0.8) : Color(red: 0, green: 0.5, blue: 0).opacity(0.8)\n }\n \n var body: some View {\n HStack(alignment: .top, spacing: 12) {\n Image(systemName: icon)\n .font(.system(size: 20))\n .foregroundColor(textColor)\n .frame(width: 30)\n \n VStack(alignment: .leading, spacing: 4) {\n Text(title)\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(textColor)\n \n Text(description)\n .font(.system(size: 12, design: .monospaced))\n .foregroundColor(secondaryTextColor)\n .fixedSize(horizontal: false, vertical: true)\n }\n \n Spacer()\n }\n }\n}\n\n#Preview {\n AppInfoView()\n}\n"], ["/bitchat/bitchatShareExtension/ShareViewController.swift", "//\n// ShareViewController.swift\n// bitchatShareExtension\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport UIKit\nimport Social\nimport UniformTypeIdentifiers\n\nclass ShareViewController: SLComposeServiceViewController {\n \n override func viewDidLoad() {\n super.viewDidLoad()\n // Set placeholder text\n placeholder = \"Share to bitchat...\"\n // Set character limit (optional)\n charactersRemaining = 500\n }\n \n override func isContentValid() -> Bool {\n // Validate that we have text content or attachments\n if let text = contentText, !text.isEmpty {\n return true\n }\n // Check if we have attachments\n if let item = extensionContext?.inputItems.first as? NSExtensionItem,\n let attachments = item.attachments,\n !attachments.isEmpty {\n return true\n }\n return false\n }\n \n override func didSelectPost() {\n guard let extensionItem = extensionContext?.inputItems.first as? NSExtensionItem else {\n self.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)\n return\n }\n \n \n // Get the page title from the compose view or extension item\n let pageTitle = self.contentText ?? extensionItem.attributedContentText?.string ?? extensionItem.attributedTitle?.string\n \n var foundURL: URL? = nil\n let group = DispatchGroup()\n \n // IMPORTANT: Check if the NSExtensionItem itself has a URL\n // Safari often provides the URL as an attributedString with a link\n if let attributedText = extensionItem.attributedContentText {\n let text = attributedText.string\n let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)\n let matches = detector?.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count))\n if let firstMatch = matches?.first, let url = firstMatch.url {\n foundURL = url\n }\n }\n \n // Only check attachments if we haven't found a URL yet\n if foundURL == nil {\n for (_, itemProvider) in (extensionItem.attachments ?? []).enumerated() {\n \n // Try multiple URL type identifiers that Safari might use\n let urlTypes = [\n UTType.url.identifier,\n \"public.url\",\n \"public.file-url\"\n ]\n \n for urlType in urlTypes {\n if itemProvider.hasItemConformingToTypeIdentifier(urlType) {\n group.enter()\n itemProvider.loadItem(forTypeIdentifier: urlType, options: nil) { (item, error) in\n defer { group.leave() }\n \n if let url = item as? URL {\n foundURL = url\n } else if let data = item as? Data,\n let urlString = String(data: data, encoding: .utf8),\n let url = URL(string: urlString) {\n foundURL = url\n } else if let string = item as? String,\n let url = URL(string: string) {\n foundURL = url\n }\n }\n break // Found a URL type, no need to check other types\n }\n }\n \n // Also check for plain text that might be a URL\n if foundURL == nil && itemProvider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) {\n group.enter()\n itemProvider.loadItem(forTypeIdentifier: UTType.plainText.identifier, options: nil) { (item, error) in\n defer { group.leave() }\n \n if let text = item as? String {\n // Check if the text is actually a URL\n if let url = URL(string: text),\n (url.scheme == \"http\" || url.scheme == \"https\") {\n foundURL = url\n }\n }\n }\n }\n }\n } // End of if foundURL == nil\n \n // Process after all checks complete\n group.notify(queue: .main) { [weak self] in\n if let url = foundURL {\n // We have a URL! Create the JSON data\n let urlData: [String: String] = [\n \"url\": url.absoluteString,\n \"title\": pageTitle ?? url.host ?? \"Shared Link\"\n ]\n \n \n if let jsonData = try? JSONSerialization.data(withJSONObject: urlData),\n let jsonString = String(data: jsonData, encoding: .utf8) {\n self?.saveToSharedDefaults(content: jsonString, type: \"url\")\n }\n } else if let title = pageTitle, !title.isEmpty {\n // No URL found, just share the text\n self?.saveToSharedDefaults(content: title, type: \"text\")\n }\n \n self?.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)\n }\n }\n \n override func configurationItems() -> [Any]! {\n // No configuration items needed\n return []\n }\n \n // MARK: - Helper Methods\n \n private func handleSharedText(_ text: String) {\n // Save to shared user defaults to pass to main app\n saveToSharedDefaults(content: text, type: \"text\")\n openMainApp()\n }\n \n private func handleSharedURL(_ url: URL) {\n // Get the page title if available from the extension context\n var pageTitle: String? = nil\n if let item = extensionContext?.inputItems.first as? NSExtensionItem {\n pageTitle = item.attributedContentText?.string ?? item.attributedTitle?.string\n }\n \n // Create a structured format for URL sharing\n let urlData: [String: String] = [\n \"url\": url.absoluteString,\n \"title\": pageTitle ?? url.host ?? \"Shared Link\"\n ]\n \n // Convert to JSON string\n if let jsonData = try? JSONSerialization.data(withJSONObject: urlData),\n let jsonString = String(data: jsonData, encoding: .utf8) {\n saveToSharedDefaults(content: jsonString, type: \"url\")\n } else {\n // Fallback to simple URL\n saveToSharedDefaults(content: url.absoluteString, type: \"url\")\n }\n \n openMainApp()\n }\n \n private func handleSharedImage(_ image: UIImage) {\n // For now, we'll just notify that image sharing isn't supported\n // In the future, we could implement image sharing via the mesh\n saveToSharedDefaults(content: \"Image sharing coming soon!\", type: \"image\")\n openMainApp()\n }\n \n private func saveToSharedDefaults(content: String, type: String) {\n // Use app groups to share data between extension and main app\n guard let userDefaults = UserDefaults(suiteName: \"group.chat.bitchat\") else {\n return\n }\n \n userDefaults.set(content, forKey: \"sharedContent\")\n userDefaults.set(type, forKey: \"sharedContentType\")\n userDefaults.set(Date(), forKey: \"sharedContentDate\")\n userDefaults.synchronize()\n \n \n // Force open the main app\n self.openMainApp()\n }\n \n private func openMainApp() {\n // Share extensions cannot directly open the containing app\n // The app will check for shared content when it becomes active\n // Show success feedback to user\n DispatchQueue.main.async {\n self.textView.text = \"✓ Shared to bitchat\"\n self.textView.isEditable = false\n }\n }\n}"], ["/bitchat/bitchat/Services/KeychainManager.swift", "//\n// KeychainManager.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport Security\nimport os.log\n\nclass KeychainManager {\n static let shared = KeychainManager()\n \n // Use consistent service name for all keychain items\n private let service = \"chat.bitchat\"\n private let appGroup = \"group.chat.bitchat\"\n \n private init() {\n // Clean up legacy keychain items on first run\n cleanupLegacyKeychainItems()\n }\n \n private func cleanupLegacyKeychainItems() {\n // Check if we've already done cleanup\n let cleanupKey = \"bitchat.keychain.cleanup.v2\"\n if UserDefaults.standard.bool(forKey: cleanupKey) {\n return\n }\n \n \n // List of old service names to migrate from\n let legacyServices = [\n \"com.bitchat.passwords\",\n \"com.bitchat.deviceidentity\",\n \"com.bitchat.noise.identity\",\n \"chat.bitchat.passwords\",\n \"bitchat.keychain\"\n ]\n \n var migratedItems = 0\n \n // Try to migrate identity keys\n for oldService in legacyServices {\n // Check for noise identity key\n let query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: oldService,\n kSecAttrAccount as String: \"identity_noiseStaticKey\",\n kSecReturnData as String: true\n ]\n \n var result: AnyObject?\n let status = SecItemCopyMatching(query as CFDictionary, &result)\n \n if status == errSecSuccess, let data = result as? Data {\n // Save to new service\n if saveIdentityKey(data, forKey: \"noiseStaticKey\") {\n migratedItems += 1\n SecureLogger.logKeyOperation(\"migrate\", keyType: \"noiseStaticKey\", success: true)\n }\n // Delete from old service\n let deleteQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: oldService,\n kSecAttrAccount as String: \"identity_noiseStaticKey\"\n ]\n SecItemDelete(deleteQuery as CFDictionary)\n }\n }\n \n // Clean up all other legacy items\n for oldService in legacyServices {\n let deleteQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: oldService\n ]\n \n SecItemDelete(deleteQuery as CFDictionary)\n }\n \n \n // Mark cleanup as done\n UserDefaults.standard.set(true, forKey: cleanupKey)\n }\n \n \n private func isSandboxed() -> Bool {\n #if os(macOS)\n let environment = ProcessInfo.processInfo.environment\n return environment[\"APP_SANDBOX_CONTAINER_ID\"] != nil\n #else\n return false\n #endif\n }\n \n // MARK: - Identity Keys\n \n func saveIdentityKey(_ keyData: Data, forKey key: String) -> Bool {\n let fullKey = \"identity_\\(key)\"\n let result = saveData(keyData, forKey: fullKey)\n SecureLogger.logKeyOperation(\"save\", keyType: key, success: result)\n return result\n }\n \n func getIdentityKey(forKey key: String) -> Data? {\n let fullKey = \"identity_\\(key)\"\n return retrieveData(forKey: fullKey)\n }\n \n func deleteIdentityKey(forKey key: String) -> Bool {\n let result = delete(forKey: \"identity_\\(key)\")\n SecureLogger.logKeyOperation(\"delete\", keyType: key, success: result)\n return result\n }\n \n // MARK: - Generic Operations\n \n private func save(_ value: String, forKey key: String) -> Bool {\n guard let data = value.data(using: .utf8) else { return false }\n return saveData(data, forKey: key)\n }\n \n private func saveData(_ data: Data, forKey key: String) -> Bool {\n // Delete any existing item first to ensure clean state\n _ = delete(forKey: key)\n \n // Build query with all necessary attributes for sandboxed apps\n var query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrAccount as String: key,\n kSecValueData as String: data,\n kSecAttrService as String: service,\n // Important for sandboxed apps: make it accessible when unlocked\n kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlocked\n ]\n \n // Add a label for easier debugging\n query[kSecAttrLabel as String] = \"bitchat-\\(key)\"\n \n // For sandboxed apps, use the app group for sharing between app instances\n if isSandboxed() {\n query[kSecAttrAccessGroup as String] = appGroup\n }\n \n // For sandboxed macOS apps, we need to ensure the item is NOT synchronized\n #if os(macOS)\n query[kSecAttrSynchronizable as String] = false\n #endif\n \n let status = SecItemAdd(query as CFDictionary, nil)\n \n if status == errSecSuccess {\n return true\n } else if status == -34018 {\n SecureLogger.logError(NSError(domain: \"Keychain\", code: -34018), context: \"Missing keychain entitlement\", category: SecureLogger.keychain)\n } else if status != errSecDuplicateItem {\n SecureLogger.logError(NSError(domain: \"Keychain\", code: Int(status)), context: \"Error saving to keychain\", category: SecureLogger.keychain)\n }\n \n return false\n }\n \n private func retrieve(forKey key: String) -> String? {\n guard let data = retrieveData(forKey: key) else { return nil }\n return String(data: data, encoding: .utf8)\n }\n \n private func retrieveData(forKey key: String) -> Data? {\n var query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrAccount as String: key,\n kSecAttrService as String: service,\n kSecReturnData as String: true,\n kSecMatchLimit as String: kSecMatchLimitOne\n ]\n \n // For sandboxed apps, use the app group\n if isSandboxed() {\n query[kSecAttrAccessGroup as String] = appGroup\n }\n \n var result: AnyObject?\n let status = SecItemCopyMatching(query as CFDictionary, &result)\n \n if status == errSecSuccess {\n return result as? Data\n } else if status == -34018 {\n SecureLogger.logError(NSError(domain: \"Keychain\", code: -34018), context: \"Missing keychain entitlement\", category: SecureLogger.keychain)\n }\n \n return nil\n }\n \n private func delete(forKey key: String) -> Bool {\n // Build basic query\n var query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrAccount as String: key,\n kSecAttrService as String: service\n ]\n \n // For sandboxed apps, use the app group\n if isSandboxed() {\n query[kSecAttrAccessGroup as String] = appGroup\n }\n \n let status = SecItemDelete(query as CFDictionary)\n return status == errSecSuccess || status == errSecItemNotFound\n }\n \n // MARK: - Cleanup\n \n func deleteAllPasswords() -> Bool {\n var query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword\n ]\n \n // Add service if not empty\n if !service.isEmpty {\n query[kSecAttrService as String] = service\n }\n \n let status = SecItemDelete(query as CFDictionary)\n return status == errSecSuccess || status == errSecItemNotFound\n }\n \n // Force cleanup to run again (for development/testing)\n func resetCleanupFlag() {\n UserDefaults.standard.removeObject(forKey: \"bitchat.keychain.cleanup.v2\")\n }\n \n \n // Delete ALL keychain data for panic mode\n func deleteAllKeychainData() -> Bool {\n SecureLogger.log(\"Panic mode - deleting all keychain data\", category: SecureLogger.security, level: .warning)\n \n var totalDeleted = 0\n \n // Search without service restriction to catch all items\n let searchQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecMatchLimit as String: kSecMatchLimitAll,\n kSecReturnAttributes as String: true\n ]\n \n var result: AnyObject?\n let searchStatus = SecItemCopyMatching(searchQuery as CFDictionary, &result)\n \n if searchStatus == errSecSuccess, let items = result as? [[String: Any]] {\n for item in items {\n var shouldDelete = false\n let account = item[kSecAttrAccount as String] as? String ?? \"\"\n let service = item[kSecAttrService as String] as? String ?? \"\"\n \n // ONLY delete if service name contains \"bitchat\"\n // This is the safest approach - we only touch items we know are ours\n if service.lowercased().contains(\"bitchat\") {\n shouldDelete = true\n }\n \n if shouldDelete {\n // Build delete query with all available attributes for precise deletion\n var deleteQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword\n ]\n \n if !account.isEmpty {\n deleteQuery[kSecAttrAccount as String] = account\n }\n if !service.isEmpty {\n deleteQuery[kSecAttrService as String] = service\n }\n \n // Add access group if present\n if let accessGroup = item[kSecAttrAccessGroup as String] as? String,\n !accessGroup.isEmpty && accessGroup != \"test\" {\n deleteQuery[kSecAttrAccessGroup as String] = accessGroup\n }\n \n let deleteStatus = SecItemDelete(deleteQuery as CFDictionary)\n if deleteStatus == errSecSuccess {\n totalDeleted += 1\n SecureLogger.log(\"Deleted keychain item: \\(account) from \\(service)\", category: SecureLogger.keychain, level: .info)\n }\n }\n }\n }\n \n // Also try to delete by known service names (in case we missed any)\n let knownServices = [\n \"chat.bitchat\",\n \"com.bitchat.passwords\",\n \"com.bitchat.deviceidentity\", \n \"com.bitchat.noise.identity\",\n \"chat.bitchat.passwords\",\n \"bitchat.keychain\",\n \"bitchat\",\n \"com.bitchat\"\n ]\n \n for serviceName in knownServices {\n let query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: serviceName\n ]\n \n let status = SecItemDelete(query as CFDictionary)\n if status == errSecSuccess {\n totalDeleted += 1\n }\n }\n \n SecureLogger.log(\"Panic mode cleanup completed. Total items deleted: \\(totalDeleted)\", category: SecureLogger.keychain, level: .warning)\n \n return totalDeleted > 0\n }\n \n // MARK: - Debug\n \n func verifyIdentityKeyExists() -> Bool {\n let key = \"identity_noiseStaticKey\"\n return retrieveData(forKey: key) != nil\n }\n \n // Aggressive cleanup for legacy items - can be called manually\n func aggressiveCleanupLegacyItems() -> Int {\n var deletedCount = 0\n \n // List of KNOWN bitchat service names from our development history\n let knownBitchatServices = [\n \"com.bitchat.passwords\",\n \"com.bitchat.deviceidentity\",\n \"com.bitchat.noise.identity\",\n \"chat.bitchat.passwords\",\n \"bitchat.keychain\",\n \"Bitchat\",\n \"BitChat\"\n ]\n \n // First, delete all items from known legacy services\n for legacyService in knownBitchatServices {\n let deleteQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: legacyService\n ]\n \n let status = SecItemDelete(deleteQuery as CFDictionary)\n if status == errSecSuccess {\n deletedCount += 1\n }\n }\n \n // Now search for items that have our specific account patterns with bitchat service names\n let searchQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecMatchLimit as String: kSecMatchLimitAll,\n kSecReturnAttributes as String: true\n ]\n \n var result: AnyObject?\n let status = SecItemCopyMatching(searchQuery as CFDictionary, &result)\n \n if status == errSecSuccess, let items = result as? [[String: Any]] {\n for item in items {\n let account = item[kSecAttrAccount as String] as? String ?? \"\"\n let service = item[kSecAttrService as String] as? String ?? \"\"\n \n // ONLY delete if service name contains \"bitchat\" somewhere\n // This ensures we never touch other apps' keychain items\n var shouldDelete = false\n \n // Check if service contains \"bitchat\" (case insensitive) but NOT our current service\n let serviceLower = service.lowercased()\n if service != self.service && serviceLower.contains(\"bitchat\") {\n shouldDelete = true\n }\n \n if shouldDelete {\n // Build precise delete query\n let deleteQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: service,\n kSecAttrAccount as String: account\n ]\n \n let deleteStatus = SecItemDelete(deleteQuery as CFDictionary)\n if deleteStatus == errSecSuccess {\n deletedCount += 1\n }\n }\n }\n }\n \n return deletedCount\n }\n}"], ["/bitchat/bitchat/Noise/NoiseSecurityConsiderations.swift", "//\n// NoiseSecurityConsiderations.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport CryptoKit\n\n// MARK: - Security Constants\n\nenum NoiseSecurityConstants {\n // Maximum message size to prevent memory exhaustion\n static let maxMessageSize = 65535 // 64KB as per Noise spec\n \n // Maximum handshake message size\n static let maxHandshakeMessageSize = 2048 // 2KB to accommodate XX pattern\n \n // Session timeout - sessions older than this should be renegotiated\n static let sessionTimeout: TimeInterval = 86400 // 24 hours\n \n // Maximum number of messages before rekey (2^64 - 1 is the nonce limit)\n static let maxMessagesPerSession: UInt64 = 1_000_000_000 // 1 billion messages\n \n // Handshake timeout - abandon incomplete handshakes\n static let handshakeTimeout: TimeInterval = 60 // 1 minute\n \n // Maximum concurrent sessions per peer\n static let maxSessionsPerPeer = 3\n \n // Rate limiting\n static let maxHandshakesPerMinute = 10\n static let maxMessagesPerSecond = 100\n \n // Global rate limiting (across all peers)\n static let maxGlobalHandshakesPerMinute = 30\n static let maxGlobalMessagesPerSecond = 500\n}\n\n// MARK: - Security Validations\n\nstruct NoiseSecurityValidator {\n \n /// Validate message size\n static func validateMessageSize(_ data: Data) -> Bool {\n return data.count <= NoiseSecurityConstants.maxMessageSize\n }\n \n /// Validate handshake message size\n static func validateHandshakeMessageSize(_ data: Data) -> Bool {\n return data.count <= NoiseSecurityConstants.maxHandshakeMessageSize\n }\n \n /// Validate peer ID format\n static func validatePeerID(_ peerID: String) -> Bool {\n // Peer ID should be reasonable length and contain valid characters\n let validCharset = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: \"-_\"))\n return peerID.count > 0 && \n peerID.count <= 64 && \n peerID.rangeOfCharacter(from: validCharset.inverted) == nil\n }\n}\n\n// MARK: - Enhanced Noise Session with Security\n\nclass SecureNoiseSession: NoiseSession {\n private(set) var messageCount: UInt64 = 0\n private let sessionStartTime = Date()\n private(set) var lastActivityTime = Date()\n \n override func encrypt(_ plaintext: Data) throws -> Data {\n // Check session age\n if Date().timeIntervalSince(sessionStartTime) > NoiseSecurityConstants.sessionTimeout {\n throw NoiseSecurityError.sessionExpired\n }\n \n // Check message count\n if messageCount >= NoiseSecurityConstants.maxMessagesPerSession {\n throw NoiseSecurityError.sessionExhausted\n }\n \n // Validate message size\n guard NoiseSecurityValidator.validateMessageSize(plaintext) else {\n throw NoiseSecurityError.messageTooLarge\n }\n \n let encrypted = try super.encrypt(plaintext)\n messageCount += 1\n lastActivityTime = Date()\n \n return encrypted\n }\n \n override func decrypt(_ ciphertext: Data) throws -> Data {\n // Check session age\n if Date().timeIntervalSince(sessionStartTime) > NoiseSecurityConstants.sessionTimeout {\n throw NoiseSecurityError.sessionExpired\n }\n \n // Validate message size\n guard NoiseSecurityValidator.validateMessageSize(ciphertext) else {\n throw NoiseSecurityError.messageTooLarge\n }\n \n let decrypted = try super.decrypt(ciphertext)\n lastActivityTime = Date()\n \n return decrypted\n }\n \n func needsRenegotiation() -> Bool {\n // Check if we've used more than 90% of message limit\n let messageThreshold = UInt64(Double(NoiseSecurityConstants.maxMessagesPerSession) * 0.9)\n if messageCount >= messageThreshold {\n return true\n }\n \n // Check if last activity was more than 30 minutes ago\n if Date().timeIntervalSince(lastActivityTime) > NoiseSecurityConstants.sessionTimeout {\n return true\n }\n \n return false\n }\n \n // MARK: - Testing Support\n #if DEBUG\n func setLastActivityTimeForTesting(_ date: Date) {\n lastActivityTime = date\n }\n \n func setMessageCountForTesting(_ count: UInt64) {\n messageCount = count\n }\n #endif\n}\n\n// MARK: - Rate Limiter\n\nclass NoiseRateLimiter {\n private var handshakeTimestamps: [String: [Date]] = [:] // peerID -> timestamps\n private var messageTimestamps: [String: [Date]] = [:] // peerID -> timestamps\n \n // Global rate limiting\n private var globalHandshakeTimestamps: [Date] = []\n private var globalMessageTimestamps: [Date] = []\n \n private let queue = DispatchQueue(label: \"chat.bitchat.noise.ratelimit\", attributes: .concurrent)\n \n func allowHandshake(from peerID: String) -> Bool {\n return queue.sync(flags: .barrier) {\n let now = Date()\n let oneMinuteAgo = now.addingTimeInterval(-60)\n \n // Check global rate limit first\n globalHandshakeTimestamps = globalHandshakeTimestamps.filter { $0 > oneMinuteAgo }\n if globalHandshakeTimestamps.count >= NoiseSecurityConstants.maxGlobalHandshakesPerMinute {\n SecureLogger.log(\"Global handshake rate limit exceeded: \\(globalHandshakeTimestamps.count)/\\(NoiseSecurityConstants.maxGlobalHandshakesPerMinute) per minute\", category: SecureLogger.security, level: .warning)\n return false\n }\n \n // Check per-peer rate limit\n var timestamps = handshakeTimestamps[peerID] ?? []\n timestamps = timestamps.filter { $0 > oneMinuteAgo }\n \n if timestamps.count >= NoiseSecurityConstants.maxHandshakesPerMinute {\n SecureLogger.log(\"Per-peer handshake rate limit exceeded for \\(peerID): \\(timestamps.count)/\\(NoiseSecurityConstants.maxHandshakesPerMinute) per minute\", category: SecureLogger.security, level: .warning)\n return false\n }\n \n // Record new handshake\n timestamps.append(now)\n handshakeTimestamps[peerID] = timestamps\n globalHandshakeTimestamps.append(now)\n return true\n }\n }\n \n func allowMessage(from peerID: String) -> Bool {\n return queue.sync(flags: .barrier) {\n let now = Date()\n let oneSecondAgo = now.addingTimeInterval(-1)\n \n // Check global rate limit first\n globalMessageTimestamps = globalMessageTimestamps.filter { $0 > oneSecondAgo }\n if globalMessageTimestamps.count >= NoiseSecurityConstants.maxGlobalMessagesPerSecond {\n SecureLogger.log(\"Global message rate limit exceeded: \\(globalMessageTimestamps.count)/\\(NoiseSecurityConstants.maxGlobalMessagesPerSecond) per second\", category: SecureLogger.security, level: .warning)\n return false\n }\n \n // Check per-peer rate limit\n var timestamps = messageTimestamps[peerID] ?? []\n timestamps = timestamps.filter { $0 > oneSecondAgo }\n \n if timestamps.count >= NoiseSecurityConstants.maxMessagesPerSecond {\n SecureLogger.log(\"Per-peer message rate limit exceeded for \\(peerID): \\(timestamps.count)/\\(NoiseSecurityConstants.maxMessagesPerSecond) per second\", category: SecureLogger.security, level: .warning)\n return false\n }\n \n // Record new message\n timestamps.append(now)\n messageTimestamps[peerID] = timestamps\n globalMessageTimestamps.append(now)\n return true\n }\n }\n \n func reset(for peerID: String) {\n queue.async(flags: .barrier) {\n self.handshakeTimestamps.removeValue(forKey: peerID)\n self.messageTimestamps.removeValue(forKey: peerID)\n }\n }\n}\n\n// MARK: - Security Errors\n\nenum NoiseSecurityError: Error {\n case sessionExpired\n case sessionExhausted\n case messageTooLarge\n case invalidPeerID\n case rateLimitExceeded\n case handshakeTimeout\n}\n"], ["/bitchat/bitchat/Services/NotificationService.swift", "//\n// NotificationService.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport UserNotifications\n#if os(iOS)\nimport UIKit\n#elseif os(macOS)\nimport AppKit\n#endif\n\nclass NotificationService {\n static let shared = NotificationService()\n \n private init() {}\n \n func requestAuthorization() {\n UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in\n if granted {\n // Permission granted\n } else {\n // Permission denied\n }\n }\n }\n \n func sendLocalNotification(title: String, body: String, identifier: String, userInfo: [String: Any]? = nil) {\n // For now, skip app state check entirely to avoid thread issues\n // The NotificationDelegate will handle foreground presentation\n DispatchQueue.main.async {\n let content = UNMutableNotificationContent()\n content.title = title\n content.body = body\n content.sound = .default\n if let userInfo = userInfo {\n content.userInfo = userInfo\n }\n \n let request = UNNotificationRequest(\n identifier: identifier,\n content: content,\n trigger: nil // Deliver immediately\n )\n \n UNUserNotificationCenter.current().add(request) { _ in\n // Notification added\n }\n }\n }\n \n func sendMentionNotification(from sender: String, message: String) {\n let title = \"@🫵 you were mentioned by \\(sender)\"\n let body = message\n let identifier = \"mention-\\(UUID().uuidString)\"\n \n sendLocalNotification(title: title, body: body, identifier: identifier)\n }\n \n func sendPrivateMessageNotification(from sender: String, message: String, peerID: String) {\n let title = \"🔒 private message from \\(sender)\"\n let body = message\n let identifier = \"private-\\(UUID().uuidString)\"\n let userInfo = [\"peerID\": peerID, \"senderName\": sender]\n \n sendLocalNotification(title: title, body: body, identifier: identifier, userInfo: userInfo)\n }\n \n func sendFavoriteOnlineNotification(nickname: String) {\n // Send directly without checking app state for favorites\n DispatchQueue.main.async {\n let content = UNMutableNotificationContent()\n content.title = \"⭐ \\(nickname) is online!\"\n content.body = \"wanna get in there?\"\n content.sound = .default\n \n let request = UNNotificationRequest(\n identifier: \"favorite-online-\\(UUID().uuidString)\",\n content: content,\n trigger: nil\n )\n \n UNUserNotificationCenter.current().add(request) { _ in\n // Notification added\n }\n }\n }\n \n func sendNetworkAvailableNotification(peerCount: Int) {\n let title = \"👥 bitchatters nearby!\"\n let body = peerCount == 1 ? \"1 person around\" : \"\\(peerCount) people around\"\n let identifier = \"network-available-\\(Date().timeIntervalSince1970)\"\n \n // For network notifications, we want to show them even in foreground\n // No app state check - let the notification delegate handle presentation\n DispatchQueue.main.async {\n let content = UNMutableNotificationContent()\n content.title = title\n content.body = body\n content.sound = .default\n content.interruptionLevel = .timeSensitive // Make it more prominent\n \n let request = UNNotificationRequest(\n identifier: identifier,\n content: content,\n trigger: nil // Deliver immediately\n )\n \n UNUserNotificationCenter.current().add(request) { _ in\n // Notification added\n }\n }\n }\n}\n"], ["/bitchat/bitchat/Utils/BatteryOptimizer.swift", "//\n// BatteryOptimizer.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport Combine\n#if os(iOS)\nimport UIKit\n#elseif os(macOS)\nimport IOKit.ps\n#endif\n\nenum PowerMode {\n case performance // Max performance, battery drain OK\n case balanced // Default balanced mode\n case powerSaver // Aggressive power saving\n case ultraLowPower // Emergency mode\n \n var scanDuration: TimeInterval {\n switch self {\n case .performance: return 3.0\n case .balanced: return 2.0\n case .powerSaver: return 1.0\n case .ultraLowPower: return 0.5\n }\n }\n \n var scanPauseDuration: TimeInterval {\n switch self {\n case .performance: return 2.0\n case .balanced: return 3.0\n case .powerSaver: return 8.0\n case .ultraLowPower: return 20.0\n }\n }\n \n var maxConnections: Int {\n switch self {\n case .performance: return 20\n case .balanced: return 10\n case .powerSaver: return 5\n case .ultraLowPower: return 2\n }\n }\n \n var advertisingInterval: TimeInterval {\n // Note: iOS doesn't let us control this directly, but we can stop/start advertising\n switch self {\n case .performance: return 0.0 // Continuous\n case .balanced: return 5.0 // Advertise every 5 seconds\n case .powerSaver: return 15.0 // Advertise every 15 seconds\n case .ultraLowPower: return 30.0 // Advertise every 30 seconds\n }\n }\n \n var messageAggregationWindow: TimeInterval {\n switch self {\n case .performance: return 0.05 // 50ms\n case .balanced: return 0.1 // 100ms\n case .powerSaver: return 0.3 // 300ms\n case .ultraLowPower: return 0.5 // 500ms\n }\n }\n}\n\nclass BatteryOptimizer {\n static let shared = BatteryOptimizer()\n \n @Published var currentPowerMode: PowerMode = .balanced\n @Published var isInBackground: Bool = false\n @Published var batteryLevel: Float = 1.0\n @Published var isCharging: Bool = false\n \n private var observers: [NSObjectProtocol] = []\n \n private init() {\n setupObservers()\n updateBatteryStatus()\n }\n \n deinit {\n observers.forEach { NotificationCenter.default.removeObserver($0) }\n }\n \n private func setupObservers() {\n #if os(iOS)\n // Monitor app state\n observers.append(\n NotificationCenter.default.addObserver(\n forName: UIApplication.didEnterBackgroundNotification,\n object: nil,\n queue: .main\n ) { [weak self] _ in\n self?.isInBackground = true\n self?.updatePowerMode()\n }\n )\n \n observers.append(\n NotificationCenter.default.addObserver(\n forName: UIApplication.willEnterForegroundNotification,\n object: nil,\n queue: .main\n ) { [weak self] _ in\n self?.isInBackground = false\n self?.updatePowerMode()\n }\n )\n \n // Monitor battery\n UIDevice.current.isBatteryMonitoringEnabled = true\n \n observers.append(\n NotificationCenter.default.addObserver(\n forName: UIDevice.batteryLevelDidChangeNotification,\n object: nil,\n queue: .main\n ) { [weak self] _ in\n self?.updateBatteryStatus()\n }\n )\n \n observers.append(\n NotificationCenter.default.addObserver(\n forName: UIDevice.batteryStateDidChangeNotification,\n object: nil,\n queue: .main\n ) { [weak self] _ in\n self?.updateBatteryStatus()\n }\n )\n #endif\n }\n \n private func updateBatteryStatus() {\n #if os(iOS)\n batteryLevel = UIDevice.current.batteryLevel\n if batteryLevel < 0 {\n batteryLevel = 1.0 // Unknown battery level\n }\n \n isCharging = UIDevice.current.batteryState == .charging || \n UIDevice.current.batteryState == .full\n #elseif os(macOS)\n if let info = getMacOSBatteryInfo() {\n batteryLevel = info.level\n isCharging = info.isCharging\n }\n #endif\n \n updatePowerMode()\n }\n \n #if os(macOS)\n private func getMacOSBatteryInfo() -> (level: Float, isCharging: Bool)? {\n let snapshot = IOPSCopyPowerSourcesInfo().takeRetainedValue()\n let sources = IOPSCopyPowerSourcesList(snapshot).takeRetainedValue() as Array\n \n for source in sources {\n if let description = IOPSGetPowerSourceDescription(snapshot, source).takeUnretainedValue() as? [String: Any] {\n if let currentCapacity = description[kIOPSCurrentCapacityKey] as? Int,\n let maxCapacity = description[kIOPSMaxCapacityKey] as? Int {\n let level = Float(currentCapacity) / Float(maxCapacity)\n let isCharging = description[kIOPSPowerSourceStateKey] as? String == kIOPSACPowerValue\n return (level, isCharging)\n }\n }\n }\n return nil\n }\n #endif\n \n private func updatePowerMode() {\n // Determine optimal power mode based on:\n // 1. Battery level\n // 2. Charging status\n // 3. Background/foreground state\n \n if isCharging {\n // When charging, use performance mode unless battery is critical\n currentPowerMode = batteryLevel < 0.1 ? .balanced : .performance\n } else if isInBackground {\n // In background, always use power saving\n if batteryLevel < 0.2 {\n currentPowerMode = .ultraLowPower\n } else if batteryLevel < 0.5 {\n currentPowerMode = .powerSaver\n } else {\n currentPowerMode = .balanced\n }\n } else {\n // Foreground, not charging\n if batteryLevel < 0.1 {\n currentPowerMode = .ultraLowPower\n } else if batteryLevel < 0.3 {\n currentPowerMode = .powerSaver\n } else if batteryLevel < 0.6 {\n currentPowerMode = .balanced\n } else {\n currentPowerMode = .performance\n }\n }\n }\n \n // Manual power mode override\n func setPowerMode(_ mode: PowerMode) {\n currentPowerMode = mode\n }\n \n // Get current scan parameters\n var scanParameters: (duration: TimeInterval, pause: TimeInterval) {\n return (currentPowerMode.scanDuration, currentPowerMode.scanPauseDuration)\n }\n \n // Should we skip non-essential operations?\n var shouldSkipNonEssential: Bool {\n return currentPowerMode == .ultraLowPower || \n (currentPowerMode == .powerSaver && isInBackground)\n }\n \n // Should we reduce message frequency?\n var shouldThrottleMessages: Bool {\n return currentPowerMode == .powerSaver || currentPowerMode == .ultraLowPower\n }\n}"], ["/bitchat/bitchat/Protocols/BinaryEncodingUtils.swift", "//\n// BinaryEncodingUtils.swift\n// bitchat\n//\n// Binary encoding utilities for efficient protocol messages\n//\n\nimport Foundation\n\n// MARK: - Hex Encoding/Decoding\n\nextension Data {\n func hexEncodedString() -> String {\n if self.isEmpty {\n return \"\"\n }\n return self.map { String(format: \"%02x\", $0) }.joined()\n }\n \n init?(hexString: String) {\n let len = hexString.count / 2\n var data = Data(capacity: len)\n var index = hexString.startIndex\n \n for _ in 0..> 8) & 0xFF))\n self.append(UInt8(value & 0xFF))\n }\n \n mutating func appendUInt32(_ value: UInt32) {\n self.append(UInt8((value >> 24) & 0xFF))\n self.append(UInt8((value >> 16) & 0xFF))\n self.append(UInt8((value >> 8) & 0xFF))\n self.append(UInt8(value & 0xFF))\n }\n \n mutating func appendUInt64(_ value: UInt64) {\n for i in (0..<8).reversed() {\n self.append(UInt8((value >> (i * 8)) & 0xFF))\n }\n }\n \n mutating func appendString(_ string: String, maxLength: Int = 255) {\n guard let data = string.data(using: .utf8) else { return }\n let length = Swift.min(data.count, maxLength)\n \n if maxLength <= 255 {\n self.append(UInt8(length))\n } else {\n self.appendUInt16(UInt16(length))\n }\n \n self.append(data.prefix(length))\n }\n \n mutating func appendData(_ data: Data, maxLength: Int = 65535) {\n let length = Swift.min(data.count, maxLength)\n \n if maxLength <= 255 {\n self.append(UInt8(length))\n } else {\n self.appendUInt16(UInt16(length))\n }\n \n self.append(data.prefix(length))\n }\n \n mutating func appendDate(_ date: Date) {\n let timestamp = UInt64(date.timeIntervalSince1970 * 1000) // milliseconds\n self.appendUInt64(timestamp)\n }\n \n mutating func appendUUID(_ uuid: String) {\n // Convert UUID string to 16 bytes\n var uuidData = Data(count: 16)\n \n let cleanUUID = uuid.replacingOccurrences(of: \"-\", with: \"\")\n var index = cleanUUID.startIndex\n \n for i in 0..<16 {\n guard index < cleanUUID.endIndex else { break }\n let nextIndex = cleanUUID.index(index, offsetBy: 2)\n if let byte = UInt8(String(cleanUUID[index.. UInt8? {\n guard offset >= 0 && offset < self.count else { return nil }\n let value = self[offset]\n offset += 1\n return value\n }\n \n func readUInt16(at offset: inout Int) -> UInt16? {\n guard offset + 2 <= self.count else { return nil }\n let value = UInt16(self[offset]) << 8 | UInt16(self[offset + 1])\n offset += 2\n return value\n }\n \n func readUInt32(at offset: inout Int) -> UInt32? {\n guard offset + 4 <= self.count else { return nil }\n let value = UInt32(self[offset]) << 24 |\n UInt32(self[offset + 1]) << 16 |\n UInt32(self[offset + 2]) << 8 |\n UInt32(self[offset + 3])\n offset += 4\n return value\n }\n \n func readUInt64(at offset: inout Int) -> UInt64? {\n guard offset + 8 <= self.count else { return nil }\n var value: UInt64 = 0\n for i in 0..<8 {\n value = (value << 8) | UInt64(self[offset + i])\n }\n offset += 8\n return value\n }\n \n func readString(at offset: inout Int, maxLength: Int = 255) -> String? {\n let length: Int\n \n if maxLength <= 255 {\n guard let len = readUInt8(at: &offset) else { return nil }\n length = Int(len)\n } else {\n guard let len = readUInt16(at: &offset) else { return nil }\n length = Int(len)\n }\n \n guard offset + length <= self.count else { return nil }\n \n let stringData = self[offset.. Data? {\n let length: Int\n \n if maxLength <= 255 {\n guard let len = readUInt8(at: &offset) else { return nil }\n length = Int(len)\n } else {\n guard let len = readUInt16(at: &offset) else { return nil }\n length = Int(len)\n }\n \n guard offset + length <= self.count else { return nil }\n \n let data = self[offset.. Date? {\n guard let timestamp = readUInt64(at: &offset) else { return nil }\n return Date(timeIntervalSince1970: Double(timestamp) / 1000.0)\n }\n \n func readUUID(at offset: inout Int) -> String? {\n guard offset + 16 <= self.count else { return nil }\n \n let uuidData = self[offset.. Data? {\n guard offset + count <= self.count else { return nil }\n \n let data = self[offset.. Data\n static func fromBinaryData(_ data: Data) -> Self?\n}\n\n// MARK: - Message Type Registry\n\nenum BinaryMessageType: UInt8 {\n case deliveryAck = 0x01\n case readReceipt = 0x02\n case versionHello = 0x07\n case versionAck = 0x08\n case noiseIdentityAnnouncement = 0x09\n case noiseMessage = 0x0A\n}"], ["/bitchat/bitchat/Utils/LRUCache.swift", "//\n// LRUCache.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\n\n/// Thread-safe LRU (Least Recently Used) cache implementation\nfinal class LRUCache {\n private class Node {\n var key: Key\n var value: Value\n var prev: Node?\n var next: Node?\n \n init(key: Key, value: Value) {\n self.key = key\n self.value = value\n }\n }\n \n private let maxSize: Int\n private var cache: [Key: Node] = [:]\n private var head: Node?\n private var tail: Node?\n private let queue = DispatchQueue(label: \"bitchat.lrucache\", attributes: .concurrent)\n \n init(maxSize: Int) {\n self.maxSize = maxSize\n }\n \n func set(_ key: Key, value: Value) {\n queue.sync(flags: .barrier) {\n if let node = cache[key] {\n // Update existing value and move to front\n node.value = value\n moveToFront(node)\n } else {\n // Add new node\n let newNode = Node(key: key, value: value)\n cache[key] = newNode\n addToFront(newNode)\n \n // Remove oldest if over capacity\n if cache.count > maxSize {\n if let tailNode = tail {\n removeNode(tailNode)\n cache.removeValue(forKey: tailNode.key)\n }\n }\n }\n }\n }\n \n func get(_ key: Key) -> Value? {\n return queue.sync(flags: .barrier) {\n guard let node = cache[key] else { return nil }\n moveToFront(node)\n return node.value\n }\n }\n \n func contains(_ key: Key) -> Bool {\n return queue.sync {\n return cache[key] != nil\n }\n }\n \n func remove(_ key: Key) {\n queue.sync(flags: .barrier) {\n if let node = cache[key] {\n removeNode(node)\n cache.removeValue(forKey: key)\n }\n }\n }\n \n func removeAll() {\n queue.sync(flags: .barrier) {\n cache.removeAll()\n head = nil\n tail = nil\n }\n }\n \n var count: Int {\n return queue.sync {\n return cache.count\n }\n }\n \n var keys: [Key] {\n return queue.sync {\n return Array(cache.keys)\n }\n }\n \n // MARK: - Private Helpers\n \n private func addToFront(_ node: Node) {\n node.next = head\n node.prev = nil\n \n if let head = head {\n head.prev = node\n }\n \n head = node\n \n if tail == nil {\n tail = node\n }\n }\n \n private func removeNode(_ node: Node) {\n if let prev = node.prev {\n prev.next = node.next\n } else {\n head = node.next\n }\n \n if let next = node.next {\n next.prev = node.prev\n } else {\n tail = node.prev\n }\n \n node.prev = nil\n node.next = nil\n }\n \n private func moveToFront(_ node: Node) {\n guard node !== head else { return }\n removeNode(node)\n addToFront(node)\n }\n}\n\n// MARK: - Bounded Set\n\n/// Thread-safe set with maximum size using LRU eviction\nfinal class BoundedSet {\n private let cache: LRUCache\n \n init(maxSize: Int) {\n self.cache = LRUCache(maxSize: maxSize)\n }\n \n func insert(_ element: Element) {\n cache.set(element, value: true)\n }\n \n func contains(_ element: Element) -> Bool {\n return cache.get(element) != nil\n }\n \n func remove(_ element: Element) {\n cache.remove(element)\n }\n \n func removeAll() {\n cache.removeAll()\n }\n \n var count: Int {\n return cache.count\n }\n}"], ["/bitchat/bitchat/Utils/OptimizedBloomFilter.swift", "//\n// OptimizedBloomFilter.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport CryptoKit\n\n/// Optimized Bloom filter using bit-packed storage and better hash functions\nstruct OptimizedBloomFilter {\n private var bitArray: [UInt64]\n private let bitCount: Int\n private let hashCount: Int\n \n // Statistics\n private(set) var insertCount: Int = 0\n \n init(expectedItems: Int = 1000, falsePositiveRate: Double = 0.01) {\n // Calculate optimal bit count and hash count\n let m = Double(expectedItems) * abs(log(falsePositiveRate)) / (log(2) * log(2))\n self.bitCount = Int(max(64, m.rounded()))\n \n let k = Double(bitCount) / Double(expectedItems) * log(2)\n self.hashCount = Int(max(1, min(10, k.rounded())))\n \n // Initialize bit array (64 bits per UInt64)\n let arraySize = (bitCount + 63) / 64\n self.bitArray = Array(repeating: 0, count: arraySize)\n }\n \n mutating func insert(_ item: String) {\n let hashes = generateHashes(item)\n \n for i in 0.. Bool {\n let hashes = generateHashes(item)\n \n for i in 0.. [Int] {\n guard let data = item.data(using: .utf8) else {\n return Array(repeating: 0, count: hashCount)\n }\n \n // Use SHA256 for high-quality hash values\n let hash = SHA256.hash(data: data)\n let hashBytes = Array(hash)\n \n var hashes = [Int]()\n \n // Extract multiple hash values from the SHA256 output\n for i in 0.. 0 else { return 0 }\n \n // Count set bits\n var setBits = 0\n for value in bitArray {\n setBits += value.nonzeroBitCount\n }\n \n // Calculate probability: (1 - e^(-kn/m))^k\n let ratio = Double(hashCount * insertCount) / Double(bitCount)\n return pow(1 - exp(-ratio), Double(hashCount))\n }\n \n // Get memory usage in bytes\n var memorySizeBytes: Int {\n return bitArray.count * 8\n }\n}\n\n// Extension for adaptive Bloom filter that adjusts based on network size\nextension OptimizedBloomFilter {\n static func adaptive(for networkSize: Int) -> OptimizedBloomFilter {\n // Adjust parameters based on network size\n let expectedItems: Int\n let falsePositiveRate: Double\n \n switch networkSize {\n case 0..<50:\n expectedItems = 500\n falsePositiveRate = 0.01\n case 50..<200:\n expectedItems = 2000\n falsePositiveRate = 0.02\n case 200..<500:\n expectedItems = 5000\n falsePositiveRate = 0.03\n default:\n expectedItems = 10000\n falsePositiveRate = 0.05\n }\n \n return OptimizedBloomFilter(expectedItems: expectedItems, falsePositiveRate: falsePositiveRate)\n }\n}"], ["/bitchat/bitchat/Utils/CompressionUtil.swift", "//\n// CompressionUtil.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport Compression\n\nstruct CompressionUtil {\n // Compression threshold - don't compress if data is smaller than this\n static let compressionThreshold = 100 // bytes\n \n // Compress data using LZ4 algorithm (fast compression/decompression)\n static func compress(_ data: Data) -> Data? {\n // Skip compression for small data\n guard data.count >= compressionThreshold else { return nil }\n \n let maxCompressedSize = data.count + (data.count / 255) + 16\n let destinationBuffer = UnsafeMutablePointer.allocate(capacity: maxCompressedSize)\n defer { destinationBuffer.deallocate() }\n \n let compressedSize = data.withUnsafeBytes { sourceBuffer in\n guard let sourcePtr = sourceBuffer.bindMemory(to: UInt8.self).baseAddress else { return 0 }\n return compression_encode_buffer(\n destinationBuffer, data.count,\n sourcePtr, data.count,\n nil, COMPRESSION_LZ4\n )\n }\n \n guard compressedSize > 0 && compressedSize < data.count else { return nil }\n \n return Data(bytes: destinationBuffer, count: compressedSize)\n }\n \n // Decompress LZ4 compressed data\n static func decompress(_ compressedData: Data, originalSize: Int) -> Data? {\n let destinationBuffer = UnsafeMutablePointer.allocate(capacity: originalSize)\n defer { destinationBuffer.deallocate() }\n \n let decompressedSize = compressedData.withUnsafeBytes { sourceBuffer in\n guard let sourcePtr = sourceBuffer.bindMemory(to: UInt8.self).baseAddress else { return 0 }\n return compression_decode_buffer(\n destinationBuffer, originalSize,\n sourcePtr, compressedData.count,\n nil, COMPRESSION_LZ4\n )\n }\n \n guard decompressedSize > 0 else { return nil }\n \n return Data(bytes: destinationBuffer, count: decompressedSize)\n }\n \n // Helper to check if compression is worth it\n static func shouldCompress(_ data: Data) -> Bool {\n // Don't compress if:\n // 1. Data is too small\n // 2. Data appears to be already compressed (high entropy)\n guard data.count >= compressionThreshold else { return false }\n \n // Simple entropy check - count unique bytes\n var byteFrequency = [UInt8: Int]()\n for byte in data {\n byteFrequency[byte, default: 0] += 1\n }\n \n // If we have very high byte diversity, data is likely already compressed\n let uniqueByteRatio = Double(byteFrequency.count) / Double(min(data.count, 256))\n return uniqueByteRatio < 0.9 // Compress if less than 90% unique bytes\n }\n}"]], "task_instance_info": {"created_time": "2025-08-21 03:19:36", "created_task_model": "DeepSeek-R1", "function_skeleton": "private func flushMessageBatch ( ) { }", "code_description": "This code segment functions to: Consolidate batched message data into the primary storage structures while enforcing chronological ordering and capacity limits, then propagate interface updates through the observable object's change notifications."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\nprivate func flushMessageBatch() {\n // Process public messages first\n if !pendingMessages.isEmpty {\n messages.append(contentsOf: pendingMessages)\n trimMessagesIfNeeded()\n pendingMessages.removeAll()\n }\n \n // Process private messages\n for (peerID, messages) in pendingPrivateMessages {\n if privateChats[peerID] == nil {\n privateChats[peerID] = []\n }\n privateChats[peerID]?.append(contentsOf: messages)\n trimPrivateChatMessagesIfNeeded(for: peerID)\n }\n pendingPrivateMessages.removeAll()\n \n // Force UI update on main thread\n DispatchQueue.main.async { [weak self] in\n self?.objectWillChange.send()\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 03-19-55"}, "editdistance_info": {"edit_distance": 31.4554, "calculate_time": "2025-08-21 03:19:55", "true_code_clean": "private func flushMessageBatch() {\n DispatchQueue.main.async { [weak self] in\n guard let self = self else { return }\n if !self.pendingMessages.isEmpty {\n let messagesToAdd = self.pendingMessages\n self.pendingMessages.removeAll()\n self.messages.append(contentsOf: messagesToAdd)\n self.messages.sort { $0.timestamp < $1.timestamp }\n self.trimMessagesIfNeeded()\n }\n if !self.pendingPrivateMessages.isEmpty {\n let privateMessageBatches = self.pendingPrivateMessages\n self.pendingPrivateMessages.removeAll()\n for (peerID, messagesToAdd) in privateMessageBatches {\n if self.privateChats[peerID] == nil {\n self.privateChats[peerID] = []\n }\n self.privateChats[peerID]?.append(contentsOf: messagesToAdd)\n self.privateChats[peerID]?.sort { $0.timestamp < $1.timestamp }\n self.trimPrivateChatMessagesIfNeeded(for: peerID)\n }\n }\n self.objectWillChange.send()\n }\n }", "predict_code_clean": "private func flushMessageBatch() {\n if !pendingMessages.isEmpty {\n messages.append(contentsOf: pendingMessages)\n trimMessagesIfNeeded()\n pendingMessages.removeAll()\n }\n for (peerID, messages) in pendingPrivateMessages {\n if privateChats[peerID] == nil {\n privateChats[peerID] = []\n }\n privateChats[peerID]?.append(contentsOf: messages)\n trimPrivateChatMessagesIfNeeded(for: peerID)\n }\n pendingPrivateMessages.removeAll()\n DispatchQueue.main.async { [weak self] in\n self?.objectWillChange.send()\n }\n}"}} +{"repo_name": "bitchat", "file_name": "/bitchat/bitchat/Views/FingerprintView.swift", "inference_info": {"prefix_code": "//\n// FingerprintView.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport SwiftUI\n\nstruct FingerprintView: View {\n @ObservedObject var viewModel: ChatViewModel\n let peerID: String\n @Environment(\\.dismiss) var dismiss\n @Environment(\\.colorScheme) var colorScheme\n \n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n private var backgroundColor: Color {\n colorScheme == .dark ? Color.black : Color.white\n }\n \n var body: some View {\n VStack(spacing: 20) {\n // Header\n HStack {\n Text(\"SECURITY VERIFICATION\")\n .font(.system(size: 16, weight: .bold, design: .monospaced))\n .foregroundColor(textColor)\n \n Spacer()\n \n Button(\"DONE\") {\n dismiss()\n }\n .foregroundColor(textColor)\n }\n .padding()\n \n VStack(alignment: .leading, spacing: 16) {\n // Peer info\n let peerNickname = viewModel.meshService.getPeerNicknames()[peerID] ?? \"Unknown\"\n let encryptionStatus = viewModel.getEncryptionStatus(for: peerID)\n \n HStack {\n if let icon = encryptionStatus.icon {\n Image(systemName: icon)\n .font(.system(size: 20))\n .foregroundColor(encryptionStatus == .noiseVerified ? Color.green : textColor)\n }\n \n VStack(alignment: .leading, spacing: 4) {\n Text(peerNickname)\n .font(.system(size: 18, weight: .semibold, design: .monospaced))\n .foregroundColor(textColor)\n \n Text(encryptionStatus.description)\n .font(.system(size: 12, design: .monospaced))\n .foregroundColor(textColor.opacity(0.7))\n }\n \n Spacer()\n }\n .padding()\n .background(Color.gray.opacity(0.1))\n .cornerRadius(8)\n \n // Their fingerprint\n VStack(alignment: .leading, spacing: 8) {\n Text(\"THEIR FINGERPRINT:\")\n .font(.system(size: 12, weight: .bold, design: .monospaced))\n .foregroundColor(textColor.opacity(0.7))\n \n if let fingerprint = viewModel.getFingerprint(for: peerID) {\n Text(formatFingerprint(fingerprint))\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(textColor)\n .multilineTextAlignment(.leading)\n .lineLimit(nil)\n .fixedSize(horizontal: false, vertical: true)\n .padding()\n .frame(maxWidth: .infinity)\n .background(Color.gray.opacity(0.1))\n .cornerRadius(8)\n .contextMenu {\n Button(\"Copy\") {\n #if os(iOS)\n UIPasteboard.general.string = fingerprint\n #else\n NSPasteboard.general.clearContents()\n NSPasteboard.general.setString(fingerprint, forType: .string)\n #endif\n }\n }\n } else {\n Text(\"not available - handshake in progress\")\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(Color.orange)\n .padding()\n }\n }\n \n // My fingerprint\n VStack(alignment: .leading, spacing: 8) {\n Text(\"YOUR FINGERPRINT:\")\n .font(.system(size: 12, weight: .bold, design: .monospaced))\n .foregroundColor(textColor.opacity(0.7))\n \n let myFingerprint = viewModel.getMyFingerprint()\n Text(formatFingerprint(myFingerprint))\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(textColor)\n .multilineTextAlignment(.leading)\n .lineLimit(nil)\n .fixedSize(horizontal: false, vertical: true)\n .padding()\n .frame(maxWidth: .infinity)\n .background(Color.gray.opacity(0.1))\n .cornerRadius(8)\n .contextMenu {\n Button(\"Copy\") {\n #if os(iOS)\n UIPasteboard.general.string = myFingerprint\n #else\n NSPasteboard.general.clearContents()\n NSPasteboard.general.setString(myFingerprint, forType: .string)\n #endif\n }\n }\n }\n \n // Verification status\n if encryptionStatus == .noiseSecured || encryptionStatus == .noiseVerified {\n let isVerified = encryptionStatus == .noiseVerified\n \n VStack(spacing: 12) {\n Text(isVerified ? \"✓ VERIFIED\" : \"⚠️ NOT VERIFIED\")\n .font(.system(size: 14, weight: .bold, design: .monospaced))\n .foregroundColor(isVerified ? Color.green : Color.orange)\n .frame(maxWidth: .infinity)\n \n Text(isVerified ? \n \"you have verified this person's identity.\" :\n \"compare these fingerprints with \\(peerNickname) using a secure channel.\")\n .font(.system(size: 12, design: .monospaced))\n .foregroundColor(textColor.opacity(0.7))\n .multilineTextAlignment(.center)\n .lineLimit(nil)\n .fixedSize(horizontal: false, vertical: true)\n .frame(maxWidth: .infinity)\n \n if !isVerified {\n Button(action: {\n viewModel.verifyFingerprint(for: peerID)\n dismiss()\n }) {\n Text(\"MARK AS VERIFIED\")\n .font(.system(size: 14, weight: .bold, design: .monospaced))\n .foregroundColor(.white)\n .padding(.horizontal, 20)\n .padding(.vertical, 10)\n .background(Color.green)\n .cornerRadius(8)\n }\n .buttonStyle(PlainButtonStyle())\n }\n }\n .padding(.top)\n .frame(maxWidth: .infinity)\n }\n }\n .padding()\n .frame(maxWidth: 500) // Constrain max width for better readability\n \n Spacer()\n }\n .padding()\n .frame(maxWidth: .infinity, maxHeight: .infinity)\n .background(backgroundColor)\n .presentationDetents([.large])\n .presentationDragIndicator(.visible)\n }\n \n ", "suffix_code": "\n}\n", "middle_code": "private func formatFingerprint(_ fingerprint: String) -> String {\n let uppercased = fingerprint.uppercased()\n var formatted = \"\"\n for (index, char) in uppercased.enumerated() {\n if index > 0 && index % 4 == 0 {\n if index % 16 == 0 {\n formatted += \"\\n\"\n } else {\n formatted += \" \"\n }\n }\n formatted += String(char)\n }\n return formatted\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/bitchat/bitchat/Views/ContentView.swift", "//\n// ContentView.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport SwiftUI\n\n// MARK: - Supporting Types\n\n// Pre-computed peer data for performance\nstruct PeerDisplayData: Identifiable {\n let id: String\n let displayName: String\n let rssi: Int?\n let isFavorite: Bool\n let isMe: Bool\n let hasUnreadMessages: Bool\n let encryptionStatus: EncryptionStatus\n}\n\n// MARK: - Lazy Link Preview\n\n// Lazy loading wrapper for link previews\nstruct LazyLinkPreviewView: View {\n let url: URL\n let title: String?\n @State private var isVisible = false\n \n var body: some View {\n GeometryReader { geometry in\n if isVisible {\n LinkPreviewView(url: url, title: title)\n } else {\n // Placeholder while not visible\n RoundedRectangle(cornerRadius: 10)\n .fill(Color.gray.opacity(0.1))\n .frame(height: 80)\n .onAppear {\n // Only load when view appears on screen\n isVisible = true\n }\n }\n }\n .frame(height: 80)\n }\n}\n\n// MARK: - Main Content View\n\nstruct ContentView: View {\n // MARK: - Properties\n \n @EnvironmentObject var viewModel: ChatViewModel\n @State private var messageText = \"\"\n @State private var textFieldSelection: NSRange? = nil\n @FocusState private var isTextFieldFocused: Bool\n @Environment(\\.colorScheme) var colorScheme\n @State private var showPeerList = false\n @State private var showSidebar = false\n @State private var sidebarDragOffset: CGFloat = 0\n @State private var showAppInfo = false\n @State private var showCommandSuggestions = false\n @State private var commandSuggestions: [String] = []\n @State private var backSwipeOffset: CGFloat = 0\n @State private var showPrivateChat = false\n @State private var showMessageActions = false\n @State private var selectedMessageSender: String?\n @State private var selectedMessageSenderID: String?\n @FocusState private var isNicknameFieldFocused: Bool\n @State private var lastScrollTime: Date = .distantPast\n @State private var scrollThrottleTimer: Timer?\n @State private var autocompleteDebounceTimer: Timer?\n \n // MARK: - Computed Properties\n \n private var backgroundColor: Color {\n colorScheme == .dark ? Color.black : Color.white\n }\n \n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n private var secondaryTextColor: Color {\n colorScheme == .dark ? Color.green.opacity(0.8) : Color(red: 0, green: 0.5, blue: 0).opacity(0.8)\n }\n \n // MARK: - Body\n \n var body: some View {\n GeometryReader { geometry in\n ZStack {\n // Base layer - Main public chat (always visible)\n mainChatView\n \n // Private chat slide-over\n if viewModel.selectedPrivateChatPeer != nil {\n privateChatView\n .frame(width: geometry.size.width)\n .background(backgroundColor)\n .transition(.asymmetric(\n insertion: .move(edge: .trailing),\n removal: .move(edge: .trailing)\n ))\n .offset(x: showPrivateChat ? -1 : max(0, geometry.size.width))\n .offset(x: backSwipeOffset.isNaN ? 0 : backSwipeOffset)\n .gesture(\n DragGesture()\n .onChanged { value in\n if value.translation.width > 0 && !value.translation.width.isNaN {\n let maxWidth = max(0, geometry.size.width)\n backSwipeOffset = min(value.translation.width, maxWidth.isNaN ? 0 : maxWidth)\n }\n }\n .onEnded { value in\n let translation = value.translation.width.isNaN ? 0 : value.translation.width\n let velocity = value.velocity.width.isNaN ? 0 : value.velocity.width\n if translation > 50 || (translation > 30 && velocity > 300) {\n withAnimation(.easeOut(duration: 0.2)) {\n showPrivateChat = false\n backSwipeOffset = 0\n viewModel.endPrivateChat()\n }\n } else {\n withAnimation(.easeOut(duration: 0.15)) {\n backSwipeOffset = 0\n }\n }\n }\n )\n }\n \n // Sidebar overlay\n HStack(spacing: 0) {\n // Tap to dismiss area\n Color.clear\n .contentShape(Rectangle())\n .onTapGesture {\n withAnimation(.easeInOut(duration: 0.2)) {\n showSidebar = false\n sidebarDragOffset = 0\n }\n }\n \n // Only render sidebar content when it's visible or animating\n if showSidebar || sidebarDragOffset != 0 {\n sidebarView\n #if os(macOS)\n .frame(width: min(300, max(0, geometry.size.width.isNaN ? 300 : geometry.size.width) * 0.4))\n #else\n .frame(width: max(0, geometry.size.width.isNaN ? 300 : geometry.size.width) * 0.7)\n #endif\n .transition(.move(edge: .trailing))\n } else {\n // Empty placeholder when hidden\n Color.clear\n #if os(macOS)\n .frame(width: min(300, max(0, geometry.size.width.isNaN ? 300 : geometry.size.width) * 0.4))\n #else\n .frame(width: max(0, geometry.size.width.isNaN ? 300 : geometry.size.width) * 0.7)\n #endif\n }\n }\n .offset(x: {\n let dragOffset = sidebarDragOffset.isNaN ? 0 : sidebarDragOffset\n let width = geometry.size.width.isNaN ? 0 : max(0, geometry.size.width)\n return showSidebar ? -dragOffset : width - dragOffset\n }())\n .animation(.easeInOut(duration: 0.25), value: showSidebar)\n }\n }\n #if os(macOS)\n .frame(minWidth: 600, minHeight: 400)\n #endif\n .onChange(of: viewModel.selectedPrivateChatPeer) { newValue in\n withAnimation(.easeInOut(duration: 0.2)) {\n showPrivateChat = newValue != nil\n }\n }\n .sheet(isPresented: $showAppInfo) {\n AppInfoView()\n }\n .sheet(isPresented: Binding(\n get: { viewModel.showingFingerprintFor != nil },\n set: { _ in viewModel.showingFingerprintFor = nil }\n )) {\n if let peerID = viewModel.showingFingerprintFor {\n FingerprintView(viewModel: viewModel, peerID: peerID)\n }\n }\n .confirmationDialog(\n selectedMessageSender.map { \"@\\($0)\" } ?? \"Actions\",\n isPresented: $showMessageActions,\n titleVisibility: .visible\n ) {\n Button(\"private message\") {\n if let peerID = selectedMessageSenderID {\n viewModel.startPrivateChat(with: peerID)\n withAnimation(.easeInOut(duration: 0.2)) {\n showSidebar = false\n sidebarDragOffset = 0\n }\n }\n }\n \n Button(\"hug\") {\n if let sender = selectedMessageSender {\n viewModel.sendMessage(\"/hug @\\(sender)\")\n }\n }\n \n Button(\"slap\") {\n if let sender = selectedMessageSender {\n viewModel.sendMessage(\"/slap @\\(sender)\")\n }\n }\n \n Button(\"BLOCK\", role: .destructive) {\n if let sender = selectedMessageSender {\n viewModel.sendMessage(\"/block \\(sender)\")\n }\n }\n \n Button(\"cancel\", role: .cancel) {}\n }\n .onDisappear {\n // Clean up timers\n scrollThrottleTimer?.invalidate()\n autocompleteDebounceTimer?.invalidate()\n }\n }\n \n // MARK: - Message List View\n \n private func messagesView(privatePeer: String?) -> some View {\n ScrollViewReader { proxy in\n ScrollView {\n VStack(alignment: .leading, spacing: 0) {\n // Extract messages based on context (private or public chat)\n let messages: [BitchatMessage] = {\n if let privatePeer = privatePeer {\n let msgs = viewModel.getPrivateChatMessages(for: privatePeer)\n return msgs\n } else {\n return viewModel.messages\n }\n }()\n \n // Implement windowing - show last 100 messages for performance\n let windowedMessages = messages.suffix(100)\n \n ForEach(windowedMessages, id: \\.id) { message in\n VStack(alignment: .leading, spacing: 0) {\n // Check if current user is mentioned\n let _ = message.mentions?.contains(viewModel.nickname) ?? false\n \n if message.sender == \"system\" {\n // System messages\n Text(viewModel.formatMessageAsText(message, colorScheme: colorScheme))\n .textSelection(.enabled)\n .fixedSize(horizontal: false, vertical: true)\n .frame(maxWidth: .infinity, alignment: .leading)\n } else {\n // Regular messages with natural text wrapping\n VStack(alignment: .leading, spacing: 0) {\n HStack(alignment: .top, spacing: 0) {\n // Single text view for natural wrapping\n Text(viewModel.formatMessageAsText(message, colorScheme: colorScheme))\n .textSelection(.enabled)\n .fixedSize(horizontal: false, vertical: true)\n .frame(maxWidth: .infinity, alignment: .leading)\n \n // Delivery status indicator for private messages\n if message.isPrivate && message.sender == viewModel.nickname,\n let status = message.deliveryStatus {\n DeliveryStatusView(status: status, colorScheme: colorScheme)\n .padding(.leading, 4)\n }\n }\n \n // Check for plain URLs\n let urls = message.content.extractURLs()\n if !urls.isEmpty {\n ForEach(urls.prefix(3).indices, id: \\.self) { index in\n let urlInfo = urls[index]\n LazyLinkPreviewView(url: urlInfo.url, title: nil)\n .padding(.top, 3)\n .padding(.horizontal, 1)\n .id(\"\\(message.id)-\\(urlInfo.url.absoluteString)\")\n }\n }\n }\n }\n }\n .id(message.id)\n .contentShape(Rectangle())\n .onTapGesture {\n // Only show actions for messages from other users (not system or self)\n if message.sender != \"system\" && message.sender != viewModel.nickname {\n selectedMessageSender = message.sender\n selectedMessageSenderID = message.senderPeerID\n showMessageActions = true\n }\n }\n .padding(.horizontal, 12)\n .padding(.vertical, 2)\n }\n }\n .padding(.vertical, 4)\n }\n .background(backgroundColor)\n .onTapGesture(count: 3) {\n // Triple-tap to clear current chat\n viewModel.sendMessage(\"/clear\")\n }\n .onChange(of: viewModel.messages.count) { _ in\n if privatePeer == nil && !viewModel.messages.isEmpty {\n // Throttle scroll animations to prevent excessive UI updates\n let now = Date()\n if now.timeIntervalSince(lastScrollTime) > 0.5 {\n // Immediate scroll if enough time has passed\n lastScrollTime = now\n proxy.scrollTo(viewModel.messages.suffix(100).last?.id, anchor: .bottom)\n } else {\n // Schedule a delayed scroll\n scrollThrottleTimer?.invalidate()\n scrollThrottleTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in\n lastScrollTime = Date()\n proxy.scrollTo(viewModel.messages.suffix(100).last?.id, anchor: .bottom)\n }\n }\n }\n }\n .onChange(of: viewModel.privateChats) { _ in\n if let peerID = privatePeer,\n let messages = viewModel.privateChats[peerID],\n !messages.isEmpty {\n // Same throttling for private chats\n let now = Date()\n if now.timeIntervalSince(lastScrollTime) > 0.5 {\n lastScrollTime = now\n proxy.scrollTo(messages.suffix(100).last?.id, anchor: .bottom)\n } else {\n scrollThrottleTimer?.invalidate()\n scrollThrottleTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in\n lastScrollTime = Date()\n proxy.scrollTo(messages.suffix(100).last?.id, anchor: .bottom)\n }\n }\n }\n }\n .onAppear {\n // Also check when view appears\n if let peerID = privatePeer {\n // Try multiple times to ensure read receipts are sent\n viewModel.markPrivateMessagesAsRead(from: peerID)\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {\n viewModel.markPrivateMessagesAsRead(from: peerID)\n }\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {\n viewModel.markPrivateMessagesAsRead(from: peerID)\n }\n }\n }\n }\n }\n \n // MARK: - Input View\n \n private var inputView: some View {\n VStack(spacing: 0) {\n // @mentions autocomplete\n if viewModel.showAutocomplete && !viewModel.autocompleteSuggestions.isEmpty {\n VStack(alignment: .leading, spacing: 0) {\n ForEach(viewModel.autocompleteSuggestions, id: \\.self) { suggestion in\n Button(action: {\n _ = viewModel.completeNickname(suggestion, in: &messageText)\n }) {\n HStack {\n Text(\"@\\(suggestion)\")\n .font(.system(size: 11, design: .monospaced))\n .foregroundColor(textColor)\n .fontWeight(.medium)\n Spacer()\n }\n .padding(.horizontal, 12)\n .padding(.vertical, 3)\n .frame(maxWidth: .infinity, alignment: .leading)\n }\n .buttonStyle(.plain)\n .background(Color.gray.opacity(0.1))\n }\n }\n .background(backgroundColor)\n .overlay(\n RoundedRectangle(cornerRadius: 4)\n .stroke(secondaryTextColor.opacity(0.3), lineWidth: 1)\n )\n .padding(.horizontal, 12)\n }\n \n // Command suggestions\n if showCommandSuggestions && !commandSuggestions.isEmpty {\n VStack(alignment: .leading, spacing: 0) {\n // Define commands with aliases and syntax\n let commandInfo: [(commands: [String], syntax: String?, description: String)] = [\n ([\"/block\"], \"[nickname]\", \"block or list blocked peers\"),\n ([\"/clear\"], nil, \"clear chat messages\"),\n ([\"/hug\"], \"\", \"send someone a warm hug\"),\n ([\"/m\", \"/msg\"], \" [message]\", \"send private message\"),\n ([\"/slap\"], \"\", \"slap someone with a trout\"),\n ([\"/unblock\"], \"\", \"unblock a peer\"),\n ([\"/w\"], nil, \"see who's online\")\n ]\n \n // Build the display\n let allCommands = commandInfo\n \n // Show matching commands\n ForEach(commandSuggestions, id: \\.self) { command in\n // Find the command info for this suggestion\n if let info = allCommands.first(where: { $0.commands.contains(command) }) {\n Button(action: {\n // Replace current text with selected command\n messageText = command + \" \"\n showCommandSuggestions = false\n commandSuggestions = []\n }) {\n HStack {\n // Show all aliases together\n Text(info.commands.joined(separator: \", \"))\n .font(.system(size: 11, design: .monospaced))\n .foregroundColor(textColor)\n .fontWeight(.medium)\n \n // Show syntax if any\n if let syntax = info.syntax {\n Text(syntax)\n .font(.system(size: 10, design: .monospaced))\n .foregroundColor(secondaryTextColor.opacity(0.8))\n }\n \n Spacer()\n \n // Show description\n Text(info.description)\n .font(.system(size: 10, design: .monospaced))\n .foregroundColor(secondaryTextColor)\n }\n .padding(.horizontal, 12)\n .padding(.vertical, 3)\n .frame(maxWidth: .infinity, alignment: .leading)\n }\n .buttonStyle(.plain)\n .background(Color.gray.opacity(0.1))\n }\n }\n }\n .background(backgroundColor)\n .overlay(\n RoundedRectangle(cornerRadius: 4)\n .stroke(secondaryTextColor.opacity(0.3), lineWidth: 1)\n )\n .padding(.horizontal, 12)\n }\n \n HStack(alignment: .center, spacing: 4) {\n TextField(\"type a message...\", text: $messageText)\n .textFieldStyle(.plain)\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(textColor)\n .focused($isTextFieldFocused)\n .padding(.leading, 12)\n .autocorrectionDisabled(true)\n #if os(iOS)\n .textInputAutocapitalization(.never)\n #endif\n .onChange(of: messageText) { newValue in\n // Cancel previous debounce timer\n autocompleteDebounceTimer?.invalidate()\n \n // Debounce autocomplete updates to reduce calls during rapid typing\n autocompleteDebounceTimer = Timer.scheduledTimer(withTimeInterval: 0.15, repeats: false) { _ in\n // Get cursor position (approximate - end of text for now)\n let cursorPosition = newValue.count\n viewModel.updateAutocomplete(for: newValue, cursorPosition: cursorPosition)\n }\n \n // Check for command autocomplete (instant, no debounce needed)\n if newValue.hasPrefix(\"/\") && newValue.count >= 1 {\n // Build context-aware command list\n let commandDescriptions = [\n (\"/block\", \"block or list blocked peers\"),\n (\"/clear\", \"clear chat messages\"),\n (\"/hug\", \"send someone a warm hug\"),\n (\"/m\", \"send private message\"),\n (\"/slap\", \"slap someone with a trout\"),\n (\"/unblock\", \"unblock a peer\"),\n (\"/w\", \"see who's online\")\n ]\n \n let input = newValue.lowercased()\n \n // Map of aliases to primary commands\n let aliases: [String: String] = [\n \"/join\": \"/j\",\n \"/msg\": \"/m\"\n ]\n \n // Filter commands, but convert aliases to primary\n commandSuggestions = commandDescriptions\n .filter { $0.0.starts(with: input) }\n .map { $0.0 }\n \n // Also check if input matches an alias\n for (alias, primary) in aliases {\n if alias.starts(with: input) && !commandSuggestions.contains(primary) {\n if commandDescriptions.contains(where: { $0.0 == primary }) {\n commandSuggestions.append(primary)\n }\n }\n }\n \n // Remove duplicates and sort\n commandSuggestions = Array(Set(commandSuggestions)).sorted()\n showCommandSuggestions = !commandSuggestions.isEmpty\n } else {\n showCommandSuggestions = false\n commandSuggestions = []\n }\n }\n .onSubmit {\n sendMessage()\n }\n \n Button(action: sendMessage) {\n Image(systemName: \"arrow.up.circle.fill\")\n .font(.system(size: 20))\n .foregroundColor(messageText.isEmpty ? Color.gray :\n viewModel.selectedPrivateChatPeer != nil\n ? Color.orange : textColor)\n }\n .buttonStyle(.plain)\n .padding(.trailing, 12)\n .accessibilityLabel(\"Send message\")\n .accessibilityHint(messageText.isEmpty ? \"Enter a message to send\" : \"Double tap to send\")\n }\n .padding(.vertical, 8)\n .background(backgroundColor.opacity(0.95))\n }\n .onAppear {\n // Delay keyboard focus to avoid iOS constraint warnings\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {\n isTextFieldFocused = true\n }\n }\n }\n \n // MARK: - Actions\n \n private func sendMessage() {\n viewModel.sendMessage(messageText)\n messageText = \"\"\n }\n \n // MARK: - Sidebar View\n \n private var sidebarView: some View {\n HStack(spacing: 0) {\n // Grey vertical bar for visual continuity\n Rectangle()\n .fill(Color.gray.opacity(0.3))\n .frame(width: 1)\n \n VStack(alignment: .leading, spacing: 0) {\n // Header - match main toolbar height\n HStack {\n Text(\"NETWORK\")\n .font(.system(size: 16, weight: .bold, design: .monospaced))\n .foregroundColor(textColor)\n Spacer()\n }\n .frame(height: 44) // Match header height\n .padding(.horizontal, 12)\n .background(backgroundColor.opacity(0.95))\n \n Divider()\n \n // Rooms and People list\n ScrollView {\n VStack(alignment: .leading, spacing: 12) {\n // People section\n VStack(alignment: .leading, spacing: 8) {\n // Show appropriate header based on context\n if !viewModel.connectedPeers.isEmpty {\n HStack(spacing: 4) {\n Image(systemName: \"person.2.fill\")\n .font(.system(size: 10))\n .accessibilityHidden(true)\n Text(\"PEOPLE\")\n .font(.system(size: 11, weight: .bold, design: .monospaced))\n }\n .foregroundColor(secondaryTextColor)\n .padding(.horizontal, 12)\n }\n \n if viewModel.connectedPeers.isEmpty {\n Text(\"nobody around...\")\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(secondaryTextColor)\n .padding(.horizontal)\n } else {\n // Extract peer data for display\n let peerNicknames = viewModel.meshService.getPeerNicknames()\n let peerRSSI = viewModel.meshService.getPeerRSSI()\n let myPeerID = viewModel.meshService.myPeerID\n \n // Show all connected peers\n let peersToShow: [String] = viewModel.connectedPeers\n let _ = print(\"ContentView: Showing \\(peersToShow.count) peers: \\(peersToShow.joined(separator: \", \"))\")\n \n // Pre-compute peer data outside ForEach to reduce overhead\n let peerData = peersToShow.map { peerID in\n let rssiValue = peerRSSI[peerID]?.intValue\n if rssiValue == nil {\n print(\"ContentView: No RSSI for peer \\(peerID) in dictionary with \\(peerRSSI.count) entries\")\n print(\"ContentView: peerRSSI keys: \\(peerRSSI.keys.joined(separator: \", \"))\")\n } else {\n print(\"ContentView: RSSI for peer \\(peerID) is \\(rssiValue!)\")\n }\n return PeerDisplayData(\n id: peerID,\n displayName: peerID == myPeerID ? viewModel.nickname : (peerNicknames[peerID] ?? \"anon\\(peerID.prefix(4))\"),\n rssi: rssiValue,\n isFavorite: viewModel.isFavorite(peerID: peerID),\n isMe: peerID == myPeerID,\n hasUnreadMessages: viewModel.unreadPrivateMessages.contains(peerID),\n encryptionStatus: viewModel.getEncryptionStatus(for: peerID)\n )\n }.sorted { (peer1: PeerDisplayData, peer2: PeerDisplayData) in\n // Sort: favorites first, then alphabetically by nickname\n if peer1.isFavorite != peer2.isFavorite {\n return peer1.isFavorite\n }\n return peer1.displayName < peer2.displayName\n }\n \n ForEach(peerData) { peer in\n HStack(spacing: 8) {\n // Signal strength indicator or unread message icon\n if peer.isMe {\n Image(systemName: \"person.fill\")\n .font(.system(size: 10))\n .foregroundColor(textColor)\n .accessibilityLabel(\"You\")\n } else if peer.hasUnreadMessages {\n Image(systemName: \"envelope.fill\")\n .font(.system(size: 12))\n .foregroundColor(Color.orange)\n .accessibilityLabel(\"Unread message from \\(peer.displayName)\")\n } else if let rssi = peer.rssi {\n Image(systemName: \"circle.fill\")\n .font(.system(size: 8))\n .foregroundColor(viewModel.getRSSIColor(rssi: rssi, colorScheme: colorScheme))\n .accessibilityLabel(\"Signal strength: \\(rssi > -60 ? \"excellent\" : rssi > -70 ? \"good\" : rssi > -80 ? \"fair\" : \"poor\")\")\n } else {\n // No RSSI data available\n Image(systemName: \"circle\")\n .font(.system(size: 8))\n .foregroundColor(Color.secondary.opacity(0.5))\n .accessibilityLabel(\"Signal strength: unknown\")\n }\n \n // Peer name\n if peer.isMe {\n HStack {\n Text(peer.displayName + \" (you)\")\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(textColor)\n \n Spacer()\n }\n } else {\n Text(peer.displayName)\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(peerNicknames[peer.id] != nil ? textColor : secondaryTextColor)\n \n // Encryption status icon (after peer name)\n if let icon = peer.encryptionStatus.icon {\n Image(systemName: icon)\n .font(.system(size: 10))\n .foregroundColor(peer.encryptionStatus == .noiseVerified ? Color.green : \n peer.encryptionStatus == .noiseSecured ? textColor :\n peer.encryptionStatus == .noiseHandshaking ? Color.orange :\n Color.red)\n .accessibilityLabel(\"Encryption: \\(peer.encryptionStatus == .noiseVerified ? \"verified\" : peer.encryptionStatus == .noiseSecured ? \"secured\" : peer.encryptionStatus == .noiseHandshaking ? \"establishing\" : \"none\")\")\n }\n \n Spacer()\n \n // Favorite star\n Button(action: {\n viewModel.toggleFavorite(peerID: peer.id)\n }) {\n Image(systemName: peer.isFavorite ? \"star.fill\" : \"star\")\n .font(.system(size: 12))\n .foregroundColor(peer.isFavorite ? Color.yellow : secondaryTextColor)\n }\n .buttonStyle(.plain)\n .accessibilityLabel(peer.isFavorite ? \"Remove \\(peer.displayName) from favorites\" : \"Add \\(peer.displayName) to favorites\")\n }\n }\n .padding(.horizontal)\n .padding(.vertical, 8)\n .contentShape(Rectangle())\n .onTapGesture {\n if !peer.isMe && peerNicknames[peer.id] != nil {\n viewModel.startPrivateChat(with: peer.id)\n withAnimation(.easeInOut(duration: 0.2)) {\n showSidebar = false\n sidebarDragOffset = 0\n }\n }\n }\n .onTapGesture(count: 2) {\n if !peer.isMe {\n // Show fingerprint on double tap\n viewModel.showFingerprint(for: peer.id)\n }\n }\n }\n }\n }\n }\n .padding(.vertical, 8)\n }\n \n Spacer()\n }\n .background(backgroundColor)\n }\n }\n \n // MARK: - View Components\n \n private var mainChatView: some View {\n VStack(spacing: 0) {\n mainHeaderView\n Divider()\n messagesView(privatePeer: nil)\n Divider()\n inputView\n }\n .background(backgroundColor)\n .foregroundColor(textColor)\n .gesture(\n DragGesture()\n .onChanged { value in\n let translation = value.translation.width.isNaN ? 0 : value.translation.width\n if !showSidebar && translation < 0 {\n sidebarDragOffset = max(translation, -300)\n } else if showSidebar && translation > 0 {\n sidebarDragOffset = min(-300 + translation, 0)\n }\n }\n .onEnded { value in\n let translation = value.translation.width.isNaN ? 0 : value.translation.width\n let velocity = value.velocity.width.isNaN ? 0 : value.velocity.width\n withAnimation(.easeOut(duration: 0.2)) {\n if !showSidebar {\n if translation < -100 || (translation < -50 && velocity < -500) {\n showSidebar = true\n sidebarDragOffset = 0\n } else {\n sidebarDragOffset = 0\n }\n } else {\n if translation > 100 || (translation > 50 && velocity > 500) {\n showSidebar = false\n sidebarDragOffset = 0\n } else {\n sidebarDragOffset = 0\n }\n }\n }\n }\n )\n }\n \n private var privateChatView: some View {\n HStack(spacing: 0) {\n // Vertical separator bar\n Rectangle()\n .fill(Color.gray.opacity(0.3))\n .frame(width: 1)\n \n VStack(spacing: 0) {\n privateHeaderView\n Divider()\n messagesView(privatePeer: viewModel.selectedPrivateChatPeer)\n Divider()\n inputView\n }\n .background(backgroundColor)\n .foregroundColor(textColor)\n }\n }\n \n \n private var mainHeaderView: some View {\n HStack(spacing: 0) {\n Text(\"bitchat/\")\n .font(.system(size: 18, weight: .medium, design: .monospaced))\n .foregroundColor(textColor)\n .onTapGesture(count: 3) {\n // PANIC: Triple-tap to clear all data\n viewModel.panicClearAllData()\n }\n .onTapGesture(count: 1) {\n // Single tap for app info\n showAppInfo = true\n }\n \n HStack(spacing: 0) {\n Text(\"@\")\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(secondaryTextColor)\n \n TextField(\"nickname\", text: $viewModel.nickname)\n .textFieldStyle(.plain)\n .font(.system(size: 14, design: .monospaced))\n .frame(maxWidth: 100)\n .foregroundColor(textColor)\n .focused($isNicknameFieldFocused)\n .autocorrectionDisabled(true)\n #if os(iOS)\n .textInputAutocapitalization(.never)\n #endif\n .onChange(of: isNicknameFieldFocused) { isFocused in\n if !isFocused {\n // Only validate when losing focus\n viewModel.validateAndSaveNickname()\n }\n }\n .onSubmit {\n viewModel.validateAndSaveNickname()\n }\n }\n \n Spacer()\n \n // People counter with unread indicator\n HStack(spacing: 4) {\n if !viewModel.unreadPrivateMessages.isEmpty {\n Image(systemName: \"envelope.fill\")\n .font(.system(size: 12))\n .foregroundColor(Color.orange)\n .accessibilityLabel(\"Unread private messages\")\n }\n \n let otherPeersCount = viewModel.connectedPeers.filter { $0 != viewModel.meshService.myPeerID }.count\n \n HStack(spacing: 4) {\n // People icon with count\n Image(systemName: \"person.2.fill\")\n .font(.system(size: 11))\n .accessibilityLabel(\"\\(otherPeersCount) connected \\(otherPeersCount == 1 ? \"person\" : \"people\")\")\n Text(\"\\(otherPeersCount)\")\n .font(.system(size: 12, design: .monospaced))\n .accessibilityHidden(true)\n }\n .foregroundColor(viewModel.isConnected ? textColor : Color.red)\n }\n .onTapGesture {\n withAnimation(.easeInOut(duration: 0.2)) {\n showSidebar.toggle()\n sidebarDragOffset = 0\n }\n }\n }\n .frame(height: 44)\n .padding(.horizontal, 12)\n .background(backgroundColor.opacity(0.95))\n }\n \n private var privateHeaderView: some View {\n Group {\n if let privatePeerID = viewModel.selectedPrivateChatPeer,\n let privatePeerNick = viewModel.meshService.getPeerNicknames()[privatePeerID] {\n HStack {\n Button(action: {\n withAnimation(.easeInOut(duration: 0.2)) {\n showPrivateChat = false\n viewModel.endPrivateChat()\n }\n }) {\n HStack(spacing: 4) {\n Image(systemName: \"chevron.left\")\n .font(.system(size: 12))\n Text(\"back\")\n .font(.system(size: 14, design: .monospaced))\n }\n .foregroundColor(textColor)\n }\n .buttonStyle(.plain)\n .accessibilityLabel(\"Back to main chat\")\n \n Spacer()\n \n Button(action: {\n viewModel.showFingerprint(for: privatePeerID)\n }) {\n HStack(spacing: 6) {\n Text(\"\\(privatePeerNick)\")\n .font(.system(size: 16, weight: .medium, design: .monospaced))\n .foregroundColor(Color.orange)\n // Dynamic encryption status icon\n let encryptionStatus = viewModel.getEncryptionStatus(for: privatePeerID)\n if let icon = encryptionStatus.icon {\n Image(systemName: icon)\n .font(.system(size: 14))\n .foregroundColor(encryptionStatus == .noiseVerified ? Color.green : \n encryptionStatus == .noiseSecured ? Color.orange :\n Color.red)\n .accessibilityLabel(\"Encryption status: \\(encryptionStatus == .noiseVerified ? \"verified\" : encryptionStatus == .noiseSecured ? \"secured\" : \"not encrypted\")\")\n }\n }\n .frame(maxWidth: .infinity)\n .accessibilityLabel(\"Private chat with \\(privatePeerNick)\")\n .accessibilityHint(\"Tap to view encryption fingerprint\")\n }\n .buttonStyle(.plain)\n \n Spacer()\n \n // Favorite button\n Button(action: {\n viewModel.toggleFavorite(peerID: privatePeerID)\n }) {\n Image(systemName: viewModel.isFavorite(peerID: privatePeerID) ? \"star.fill\" : \"star\")\n .font(.system(size: 16))\n .foregroundColor(viewModel.isFavorite(peerID: privatePeerID) ? Color.yellow : textColor)\n }\n .buttonStyle(.plain)\n .accessibilityLabel(viewModel.isFavorite(peerID: privatePeerID) ? \"Remove from favorites\" : \"Add to favorites\")\n .accessibilityHint(\"Double tap to toggle favorite status\")\n }\n .frame(height: 44)\n .padding(.horizontal, 12)\n .background(backgroundColor.opacity(0.95))\n } else {\n EmptyView()\n }\n }\n }\n \n}\n\n// MARK: - Helper Views\n\n// Helper view for rendering message content with clickable hashtags\nstruct MessageContentView: View {\n let message: BitchatMessage\n let viewModel: ChatViewModel\n let colorScheme: ColorScheme\n let isMentioned: Bool\n \n var body: some View {\n let content = message.content\n let hashtagPattern = \"#([a-zA-Z0-9_]+)\"\n let mentionPattern = \"@([a-zA-Z0-9_]+)\"\n \n let hashtagRegex = try? NSRegularExpression(pattern: hashtagPattern, options: [])\n let mentionRegex = try? NSRegularExpression(pattern: mentionPattern, options: [])\n \n let hashtagMatches = hashtagRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n let mentionMatches = mentionRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n \n // Combine all matches and sort by location\n var allMatches: [(range: NSRange, type: String)] = []\n for match in hashtagMatches {\n allMatches.append((match.range(at: 0), \"hashtag\"))\n }\n for match in mentionMatches {\n allMatches.append((match.range(at: 0), \"mention\"))\n }\n allMatches.sort { $0.range.location < $1.range.location }\n \n // Build the text as a concatenated Text view for natural wrapping\n let segments = buildTextSegments()\n var result = Text(\"\")\n \n for segment in segments {\n if segment.type == \"hashtag\" {\n // Note: We can't have clickable links in concatenated Text, so hashtags won't be clickable\n result = result + Text(segment.text)\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(Color.blue)\n .underline()\n } else if segment.type == \"mention\" {\n result = result + Text(segment.text)\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(Color.orange)\n } else {\n result = result + Text(segment.text)\n .font(.system(size: 14, design: .monospaced))\n .fontWeight(isMentioned ? .bold : .regular)\n }\n }\n \n return result\n .textSelection(.enabled)\n }\n \n // MARK: - Helper Methods\n \n private func buildTextSegments() -> [(text: String, type: String)] {\n var segments: [(text: String, type: String)] = []\n let content = message.content\n var lastEnd = content.startIndex\n \n let hashtagPattern = \"#([a-zA-Z0-9_]+)\"\n let mentionPattern = \"@([a-zA-Z0-9_]+)\"\n \n let hashtagRegex = try? NSRegularExpression(pattern: hashtagPattern, options: [])\n let mentionRegex = try? NSRegularExpression(pattern: mentionPattern, options: [])\n \n let hashtagMatches = hashtagRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n let mentionMatches = mentionRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n \n // Combine all matches and sort by location\n var allMatches: [(range: NSRange, type: String)] = []\n for match in hashtagMatches {\n allMatches.append((match.range(at: 0), \"hashtag\"))\n }\n for match in mentionMatches {\n allMatches.append((match.range(at: 0), \"mention\"))\n }\n allMatches.sort { $0.range.location < $1.range.location }\n \n for (matchRange, matchType) in allMatches {\n if let range = Range(matchRange, in: content) {\n // Add text before the match\n if lastEnd < range.lowerBound {\n let beforeText = String(content[lastEnd..\n//\n\nimport SwiftUI\n#if os(iOS)\nimport LinkPresentation\nimport UIKit\n#endif\n\n// MARK: - Link Metadata Cache\n\n/// Cache for link metadata to prevent repeated network requests\nprivate class LinkMetadataCache {\n static let shared = LinkMetadataCache()\n \n #if os(iOS)\n private let cache = NSCache()\n private let imageCache = NSCache()\n #endif\n private let queue = DispatchQueue(label: \"chat.bitchat.linkmetadata.cache\", attributes: .concurrent)\n \n private init() {\n #if os(iOS)\n cache.countLimit = 100 // Keep metadata for up to 100 URLs\n imageCache.countLimit = 50 // Keep images for up to 50 URLs\n imageCache.totalCostLimit = 50 * 1024 * 1024 // 50MB limit for images\n #endif\n }\n \n #if os(iOS)\n class CachedMetadata {\n let metadata: LPLinkMetadata?\n let title: String?\n let host: String?\n let error: Error?\n let timestamp: Date\n \n init(metadata: LPLinkMetadata? = nil, title: String? = nil, host: String? = nil, error: Error? = nil) {\n self.metadata = metadata\n self.title = title\n self.host = host\n self.error = error\n self.timestamp = Date()\n }\n }\n \n func getCachedMetadata(for url: URL) -> (metadata: LPLinkMetadata?, title: String?, host: String?, image: UIImage?)? {\n return queue.sync {\n guard let cached = cache.object(forKey: url as NSURL) else { return nil }\n \n // Check if cache is older than 24 hours\n if Date().timeIntervalSince(cached.timestamp) > 86400 {\n cache.removeObject(forKey: url as NSURL)\n imageCache.removeObject(forKey: url as NSURL)\n return nil\n }\n \n let image = imageCache.object(forKey: url as NSURL)\n return (cached.metadata, cached.title, cached.host, image)\n }\n }\n \n func cacheMetadata(_ metadata: LPLinkMetadata?, title: String?, host: String?, image: UIImage?, for url: URL) {\n queue.async(flags: .barrier) {\n let cached = CachedMetadata(metadata: metadata, title: title, host: host)\n self.cache.setObject(cached, forKey: url as NSURL)\n \n if let image = image {\n let cost = Int(image.size.width * image.size.height * 4) // Approximate memory usage\n self.imageCache.setObject(image, forKey: url as NSURL, cost: cost)\n }\n }\n }\n \n func cacheError(_ error: Error, for url: URL) {\n queue.async(flags: .barrier) {\n let cached = CachedMetadata(error: error)\n self.cache.setObject(cached, forKey: url as NSURL)\n }\n }\n #endif\n \n func clearCache() {\n queue.async(flags: .barrier) {\n #if os(iOS)\n self.cache.removeAllObjects()\n self.imageCache.removeAllObjects()\n #endif\n }\n }\n}\n\n// MARK: - Link Preview View\n\nstruct LinkPreviewView: View {\n let url: URL\n let title: String?\n @Environment(\\.colorScheme) var colorScheme\n #if os(iOS)\n @State private var metadata: LPLinkMetadata?\n @State private var cachedTitle: String?\n @State private var cachedHost: String?\n @State private var isLoading = false\n #endif\n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n private var backgroundColor: Color {\n colorScheme == .dark ? Color.black : Color.white\n }\n \n private var borderColor: Color {\n textColor.opacity(0.3)\n }\n \n var body: some View {\n // Always use our custom compact view for consistent appearance\n compactLinkView\n .onAppear {\n loadFromCacheOrFetch()\n }\n }\n \n #if os(iOS)\n @State private var previewImage: UIImage? = nil\n #endif\n \n private var compactLinkView: some View {\n Button(action: {\n #if os(iOS)\n UIApplication.shared.open(url)\n #else\n NSWorkspace.shared.open(url)\n #endif\n }) {\n HStack(spacing: 12) {\n // Preview image or icon\n Group {\n #if os(iOS)\n if let image = previewImage {\n Image(uiImage: image)\n .resizable()\n .aspectRatio(contentMode: .fill)\n .frame(width: 60, height: 60)\n .clipped()\n .cornerRadius(8)\n } else {\n // Favicon or default icon\n RoundedRectangle(cornerRadius: 8)\n .fill(Color.blue.opacity(0.1))\n .frame(width: 60, height: 60)\n .overlay(\n Image(systemName: \"link\")\n .font(.system(size: 24))\n .foregroundColor(Color.blue)\n )\n }\n #else\n RoundedRectangle(cornerRadius: 8)\n .fill(Color.blue.opacity(0.1))\n .frame(width: 60, height: 60)\n .overlay(\n Image(systemName: \"link\")\n .font(.system(size: 24))\n .foregroundColor(Color.blue)\n )\n #endif\n }\n \n VStack(alignment: .leading, spacing: 4) {\n // Title\n #if os(iOS)\n Text(cachedTitle ?? metadata?.title ?? title ?? url.host ?? \"Link\")\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(textColor)\n .lineLimit(2)\n .multilineTextAlignment(.leading)\n #else\n Text(title ?? url.host ?? \"Link\")\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(textColor)\n .lineLimit(2)\n .multilineTextAlignment(.leading)\n #endif\n \n // Host\n #if os(iOS)\n Text(cachedHost ?? url.host ?? url.absoluteString)\n .font(.system(size: 11, design: .monospaced))\n .foregroundColor(textColor.opacity(0.6))\n .lineLimit(1)\n #else\n Text(url.host ?? url.absoluteString)\n .font(.system(size: 11, design: .monospaced))\n .foregroundColor(textColor.opacity(0.6))\n .lineLimit(1)\n #endif\n }\n \n Spacer()\n }\n .padding(10)\n .frame(maxWidth: .infinity, alignment: .leading)\n .background(\n RoundedRectangle(cornerRadius: 10)\n .fill(colorScheme == .dark ? Color.gray.opacity(0.15) : Color.gray.opacity(0.08))\n )\n .overlay(\n RoundedRectangle(cornerRadius: 10)\n .stroke(borderColor, lineWidth: 1)\n )\n }\n .buttonStyle(.plain)\n }\n \n private var simpleLinkView: some View {\n Button(action: {\n #if os(iOS)\n UIApplication.shared.open(url)\n #else\n NSWorkspace.shared.open(url)\n #endif\n }) {\n HStack(spacing: 12) {\n // Link icon\n Image(systemName: \"link.circle.fill\")\n .font(.system(size: 32))\n .foregroundColor(Color.blue.opacity(0.8))\n .frame(width: 40, height: 40)\n \n VStack(alignment: .leading, spacing: 4) {\n // Title\n Text(title ?? url.host ?? \"Link\")\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(textColor)\n .lineLimit(2)\n .multilineTextAlignment(.leading)\n \n // URL\n Text(url.absoluteString)\n .font(.system(size: 11, design: .monospaced))\n .foregroundColor(Color.blue)\n .lineLimit(1)\n .truncationMode(.middle)\n }\n \n Spacer()\n \n // Arrow indicator\n Image(systemName: \"chevron.right\")\n .font(.system(size: 14))\n .foregroundColor(textColor.opacity(0.5))\n }\n .padding(12)\n .frame(maxWidth: .infinity, alignment: .leading)\n .background(\n RoundedRectangle(cornerRadius: 10)\n .fill(colorScheme == .dark ? Color.gray.opacity(0.15) : Color.gray.opacity(0.08))\n )\n .overlay(\n RoundedRectangle(cornerRadius: 10)\n .stroke(borderColor, lineWidth: 1)\n )\n }\n .buttonStyle(.plain)\n }\n \n private func loadFromCacheOrFetch() {\n #if os(iOS)\n // Check if we already have data in state\n guard metadata == nil && !isLoading else { \n return \n }\n \n // Check cache first\n if let cached = LinkMetadataCache.shared.getCachedMetadata(for: url) {\n // print(\"🔗 LinkPreviewView: Using CACHED metadata for: \\(url.absoluteString)\")\n self.metadata = cached.metadata\n self.cachedTitle = cached.title ?? cached.metadata?.title\n self.cachedHost = cached.host ?? url.host\n self.previewImage = cached.image\n return\n }\n \n // Not in cache, fetch it\n // print(\"🔗 LinkPreviewView: FETCHING metadata for: \\(url.absoluteString)\")\n isLoading = true\n \n let provider = LPMetadataProvider()\n provider.startFetchingMetadata(for: url) { fetchedMetadata, error in\n DispatchQueue.main.async {\n self.isLoading = false\n \n if let error = error {\n // Check if it's an ATS error for subresources (non-critical)\n let errorString = error.localizedDescription.lowercased()\n let isATSError = errorString.contains(\"app transport security\") || \n errorString.contains(\"secure connection\")\n \n if !isATSError {\n // Only log non-ATS errors\n // print(\"🔗 LinkPreviewView: Error fetching metadata: \\(error)\")\n }\n \n // Still try to show basic preview with URL info\n self.cachedTitle = self.title ?? self.url.host\n self.cachedHost = self.url.host\n \n // Cache even failed attempts to avoid repeated fetches\n LinkMetadataCache.shared.cacheMetadata(\n nil,\n title: self.cachedTitle,\n host: self.cachedHost,\n image: nil,\n for: self.url\n )\n return\n }\n \n if let fetchedMetadata = fetchedMetadata {\n // Use the fetched metadata, or create new with our title\n if let title = self.title, !title.isEmpty {\n fetchedMetadata.title = title\n }\n self.metadata = fetchedMetadata\n self.cachedTitle = fetchedMetadata.title ?? self.title\n self.cachedHost = self.url.host\n \n // Try to extract image\n if let imageProvider = fetchedMetadata.imageProvider {\n imageProvider.loadObject(ofClass: UIImage.self) { image, error in\n DispatchQueue.main.async {\n if let image = image as? UIImage {\n self.previewImage = image\n // Cache everything including the image\n LinkMetadataCache.shared.cacheMetadata(\n fetchedMetadata,\n title: self.cachedTitle,\n host: self.cachedHost,\n image: image,\n for: self.url\n )\n } else {\n // Cache without image\n LinkMetadataCache.shared.cacheMetadata(\n fetchedMetadata,\n title: self.cachedTitle,\n host: self.cachedHost,\n image: nil,\n for: self.url\n )\n }\n }\n }\n } else {\n // No image, cache what we have\n LinkMetadataCache.shared.cacheMetadata(\n fetchedMetadata,\n title: self.cachedTitle,\n host: self.cachedHost,\n image: nil,\n for: self.url\n )\n }\n }\n }\n }\n #endif\n }\n}\n\n#if os(iOS)\n// UIViewRepresentable wrapper for LPLinkView\nstruct LinkPreview: UIViewRepresentable {\n let metadata: LPLinkMetadata\n \n func makeUIView(context: Context) -> UIView {\n let containerView = UIView()\n containerView.backgroundColor = .clear\n \n let linkView = LPLinkView(metadata: metadata)\n linkView.isUserInteractionEnabled = false // We handle taps at the SwiftUI level\n linkView.translatesAutoresizingMaskIntoConstraints = false\n \n containerView.addSubview(linkView)\n NSLayoutConstraint.activate([\n linkView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),\n linkView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),\n linkView.topAnchor.constraint(equalTo: containerView.topAnchor),\n linkView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)\n ])\n \n return containerView\n }\n \n func updateUIView(_ uiView: UIView, context: Context) {\n // Update if needed\n }\n}\n#endif\n\n// Helper to extract URLs from text\nextension String {\n func extractURLs() -> [(url: URL, range: Range)] {\n var urls: [(URL, Range)] = []\n \n // Check for plain URLs\n let types: NSTextCheckingResult.CheckingType = .link\n if let detector = try? NSDataDetector(types: types.rawValue) {\n let matches = detector.matches(in: self, range: NSRange(location: 0, length: self.utf16.count))\n for match in matches {\n if let range = Range(match.range, in: self),\n let url = match.url {\n urls.append((url, range))\n }\n }\n }\n \n return urls\n }\n}\n\n#Preview {\n VStack {\n LinkPreviewView(url: URL(string: \"https://example.com\")!, title: \"Example Website\")\n .padding()\n }\n}\n"], ["/bitchat/bitchat/Views/AppInfoView.swift", "import SwiftUI\n\nstruct AppInfoView: View {\n @Environment(\\.dismiss) var dismiss\n @Environment(\\.colorScheme) var colorScheme\n \n private var backgroundColor: Color {\n colorScheme == .dark ? Color.black : Color.white\n }\n \n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n private var secondaryTextColor: Color {\n colorScheme == .dark ? Color.green.opacity(0.8) : Color(red: 0, green: 0.5, blue: 0).opacity(0.8)\n }\n \n // MARK: - Constants\n private enum Strings {\n static let appName = \"bitchat\"\n static let tagline = \"mesh sidegroupchat\"\n \n enum Features {\n static let title = \"FEATURES\"\n static let offlineComm = (\"wifi.slash\", \"offline communication\", \"works without internet using Bluetooth low energy\")\n static let encryption = (\"lock.shield\", \"end-to-end encryption\", \"private messages encrypted with noise protocol\")\n static let extendedRange = (\"antenna.radiowaves.left.and.right\", \"extended range\", \"messages relay through peers, going the distance\")\n static let favorites = (\"star.fill\", \"favorites\", \"get notified when your favorite people join\")\n static let mentions = (\"at\", \"mentions\", \"use @nickname to notify specific people\")\n }\n \n enum Privacy {\n static let title = \"PRIVACY\"\n static let noTracking = (\"eye.slash\", \"no tracking\", \"no servers, accounts, or data collection\")\n static let ephemeral = (\"shuffle\", \"ephemeral identity\", \"new peer ID generated regularly\")\n static let panic = (\"hand.raised.fill\", \"panic mode\", \"triple-tap logo to instantly clear all data\")\n }\n \n enum HowToUse {\n static let title = \"HOW TO USE\"\n static let instructions = [\n \"• set your nickname by tapping it\",\n \"• swipe left for sidebar\",\n \"• tap a peer to start a private chat\",\n \"• use @nickname to mention someone\",\n \"• triple-tap chat to clear\"\n ]\n }\n \n enum Warning {\n static let title = \"WARNING\"\n static let message = \"private message security has not yet been fully audited. do not use for critical situations until this warning disappears.\"\n }\n }\n \n var body: some View {\n #if os(macOS)\n VStack(spacing: 0) {\n // Custom header for macOS\n HStack {\n Spacer()\n Button(\"DONE\") {\n dismiss()\n }\n .buttonStyle(.plain)\n .foregroundColor(textColor)\n .padding()\n }\n .background(backgroundColor.opacity(0.95))\n \n ScrollView {\n infoContent\n }\n .background(backgroundColor)\n }\n .frame(width: 600, height: 700)\n #else\n NavigationView {\n ScrollView {\n infoContent\n }\n .background(backgroundColor)\n .navigationBarTitleDisplayMode(.inline)\n .toolbar {\n ToolbarItem(placement: .navigationBarTrailing) {\n Button(\"DONE\") {\n dismiss()\n }\n .foregroundColor(textColor)\n }\n }\n }\n #endif\n }\n \n @ViewBuilder\n private var infoContent: some View {\n VStack(alignment: .leading, spacing: 24) {\n // Header\n VStack(alignment: .center, spacing: 8) {\n Text(Strings.appName)\n .font(.system(size: 32, weight: .bold, design: .monospaced))\n .foregroundColor(textColor)\n \n Text(Strings.tagline)\n .font(.system(size: 16, design: .monospaced))\n .foregroundColor(secondaryTextColor)\n }\n .frame(maxWidth: .infinity)\n .padding(.vertical)\n \n // Features\n VStack(alignment: .leading, spacing: 16) {\n SectionHeader(Strings.Features.title)\n \n FeatureRow(icon: Strings.Features.offlineComm.0, \n title: Strings.Features.offlineComm.1,\n description: Strings.Features.offlineComm.2)\n \n FeatureRow(icon: Strings.Features.encryption.0,\n title: Strings.Features.encryption.1,\n description: Strings.Features.encryption.2)\n \n FeatureRow(icon: Strings.Features.extendedRange.0,\n title: Strings.Features.extendedRange.1,\n description: Strings.Features.extendedRange.2)\n \n FeatureRow(icon: Strings.Features.favorites.0,\n title: Strings.Features.favorites.1,\n description: Strings.Features.favorites.2)\n \n FeatureRow(icon: Strings.Features.mentions.0,\n title: Strings.Features.mentions.1,\n description: Strings.Features.mentions.2)\n }\n \n // Privacy\n VStack(alignment: .leading, spacing: 16) {\n SectionHeader(Strings.Privacy.title)\n \n FeatureRow(icon: Strings.Privacy.noTracking.0,\n title: Strings.Privacy.noTracking.1,\n description: Strings.Privacy.noTracking.2)\n \n FeatureRow(icon: Strings.Privacy.ephemeral.0,\n title: Strings.Privacy.ephemeral.1,\n description: Strings.Privacy.ephemeral.2)\n \n FeatureRow(icon: Strings.Privacy.panic.0,\n title: Strings.Privacy.panic.1,\n description: Strings.Privacy.panic.2)\n }\n \n // How to Use\n VStack(alignment: .leading, spacing: 16) {\n SectionHeader(Strings.HowToUse.title)\n \n VStack(alignment: .leading, spacing: 8) {\n ForEach(Strings.HowToUse.instructions, id: \\.self) { instruction in\n Text(instruction)\n }\n }\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(textColor)\n }\n \n // Warning\n VStack(alignment: .leading, spacing: 6) {\n SectionHeader(Strings.Warning.title)\n .foregroundColor(Color.red)\n \n Text(Strings.Warning.message)\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(Color.red)\n .fixedSize(horizontal: false, vertical: true)\n }\n .padding(.top, 6)\n .padding(.bottom, 16)\n .padding(.horizontal)\n .background(Color.red.opacity(0.1))\n .cornerRadius(8)\n \n .padding(.top)\n }\n .padding()\n }\n}\n\nstruct SectionHeader: View {\n let title: String\n @Environment(\\.colorScheme) var colorScheme\n \n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n init(_ title: String) {\n self.title = title\n }\n \n var body: some View {\n Text(title)\n .font(.system(size: 16, weight: .bold, design: .monospaced))\n .foregroundColor(textColor)\n .padding(.top, 8)\n }\n}\n\nstruct FeatureRow: View {\n let icon: String\n let title: String\n let description: String\n @Environment(\\.colorScheme) var colorScheme\n \n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n private var secondaryTextColor: Color {\n colorScheme == .dark ? Color.green.opacity(0.8) : Color(red: 0, green: 0.5, blue: 0).opacity(0.8)\n }\n \n var body: some View {\n HStack(alignment: .top, spacing: 12) {\n Image(systemName: icon)\n .font(.system(size: 20))\n .foregroundColor(textColor)\n .frame(width: 30)\n \n VStack(alignment: .leading, spacing: 4) {\n Text(title)\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(textColor)\n \n Text(description)\n .font(.system(size: 12, design: .monospaced))\n .foregroundColor(secondaryTextColor)\n .fixedSize(horizontal: false, vertical: true)\n }\n \n Spacer()\n }\n }\n}\n\n#Preview {\n AppInfoView()\n}\n"], ["/bitchat/bitchat/ViewModels/ChatViewModel.swift", "//\n// ChatViewModel.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # ChatViewModel\n///\n/// The central business logic and state management component for BitChat.\n/// Coordinates between the UI layer and the networking/encryption services.\n///\n/// ## Overview\n/// ChatViewModel implements the MVVM pattern, serving as the binding layer between\n/// SwiftUI views and the underlying BitChat services. It manages:\n/// - Message state and delivery\n/// - Peer connections and presence\n/// - Private chat sessions\n/// - Command processing\n/// - UI state like autocomplete and notifications\n///\n/// ## Architecture\n/// The ViewModel acts as:\n/// - **BitchatDelegate**: Receives messages and events from BluetoothMeshService\n/// - **State Manager**: Maintains all UI-relevant state with @Published properties\n/// - **Command Processor**: Handles IRC-style commands (/msg, /who, etc.)\n/// - **Message Router**: Directs messages to appropriate chats (public/private)\n///\n/// ## Key Features\n///\n/// ### Message Management\n/// - Batches incoming messages for performance (100ms window)\n/// - Maintains separate public and private message queues\n/// - Limits message history to prevent memory issues (1337 messages)\n/// - Tracks delivery and read receipts\n///\n/// ### Privacy Features\n/// - Ephemeral by design - no persistent message storage\n/// - Supports verified fingerprints for secure communication\n/// - Blocks messages from blocked users\n/// - Emergency wipe capability (triple-tap)\n///\n/// ### User Experience\n/// - Smart autocomplete for mentions and commands\n/// - Unread message indicators\n/// - Connection status tracking\n/// - Favorite peers management\n///\n/// ## Command System\n/// Supports IRC-style commands:\n/// - `/nick `: Change nickname\n/// - `/msg `: Send private message\n/// - `/who`: List connected peers\n/// - `/slap `: Fun interaction\n/// - `/clear`: Clear message history\n/// - `/help`: Show available commands\n///\n/// ## Performance Optimizations\n/// - Message batching reduces UI updates\n/// - Caches expensive computations (RSSI colors, encryption status)\n/// - Debounces autocomplete suggestions\n/// - Efficient peer list management\n///\n/// ## Thread Safety\n/// - All @Published properties trigger UI updates on main thread\n/// - Background operations use proper queue management\n/// - Atomic operations for critical state updates\n///\n/// ## Usage Example\n/// ```swift\n/// let viewModel = ChatViewModel()\n/// viewModel.nickname = \"Alice\"\n/// viewModel.startServices()\n/// viewModel.sendMessage(\"Hello, mesh network!\")\n/// ```\n///\n\nimport Foundation\nimport SwiftUI\nimport Combine\nimport CryptoKit\nimport CommonCrypto\n#if os(iOS)\nimport UIKit\n#endif\n\n/// Manages the application state and business logic for BitChat.\n/// Acts as the primary coordinator between UI components and backend services,\n/// implementing the BitchatDelegate protocol to handle network events.\nclass ChatViewModel: ObservableObject {\n // MARK: - Published Properties\n \n @Published var messages: [BitchatMessage] = []\n private let maxMessages = 1337 // Maximum messages before oldest are removed\n @Published var connectedPeers: [String] = []\n \n // MARK: - Message Batching Properties\n \n // Message batching for performance\n private var pendingMessages: [BitchatMessage] = []\n private var pendingPrivateMessages: [String: [BitchatMessage]] = [:] // peerID -> messages\n private var messageBatchTimer: Timer?\n private let messageBatchInterval: TimeInterval = 0.1 // 100ms batching window\n @Published var nickname: String = \"\" {\n didSet {\n // Trim whitespace whenever nickname is set\n let trimmed = nickname.trimmingCharacters(in: .whitespacesAndNewlines)\n if trimmed != nickname {\n nickname = trimmed\n }\n }\n }\n @Published var isConnected = false\n @Published var privateChats: [String: [BitchatMessage]] = [:] // peerID -> messages\n @Published var selectedPrivateChatPeer: String? = nil\n private var selectedPrivateChatFingerprint: String? = nil // Track by fingerprint for persistence across reconnections\n @Published var unreadPrivateMessages: Set = []\n @Published var autocompleteSuggestions: [String] = []\n @Published var showAutocomplete: Bool = false\n @Published var autocompleteRange: NSRange? = nil\n @Published var selectedAutocompleteIndex: Int = 0\n \n // MARK: - Autocomplete Properties\n \n // Autocomplete optimization\n private let mentionRegex = try? NSRegularExpression(pattern: \"@([a-zA-Z0-9_]*)$\", options: [])\n private var cachedNicknames: [String] = []\n private var lastNicknameUpdate: Date = .distantPast\n \n // Temporary property to fix compilation\n @Published var showPasswordPrompt = false\n \n // MARK: - Services and Storage\n \n var meshService = BluetoothMeshService()\n private let userDefaults = UserDefaults.standard\n private let nicknameKey = \"bitchat.nickname\"\n \n // MARK: - Caches\n \n // Caches for expensive computations\n private var rssiColorCache: [String: Color] = [:] // key: \"\\(rssi)_\\(isDark)\"\n private var encryptionStatusCache: [String: EncryptionStatus] = [:] // key: peerID\n \n // MARK: - Social Features\n \n @Published var favoritePeers: Set = [] // Now stores public key fingerprints instead of peer IDs\n private var peerIDToPublicKeyFingerprint: [String: String] = [:] // Maps ephemeral peer IDs to persistent fingerprints\n private var blockedUsers: Set = [] // Stores public key fingerprints of blocked users\n \n // MARK: - Encryption and Security\n \n // Noise Protocol encryption status\n @Published var peerEncryptionStatus: [String: EncryptionStatus] = [:] // peerID -> encryption status\n @Published var verifiedFingerprints: Set = [] // Set of verified fingerprints\n @Published var showingFingerprintFor: String? = nil // Currently showing fingerprint sheet for peer\n \n // Messages are naturally ephemeral - no persistent storage\n \n // MARK: - Message Delivery Tracking\n \n // Delivery tracking\n private var deliveryTrackerCancellable: AnyCancellable?\n \n // Track sent read receipts to avoid duplicates\n private var sentReadReceipts: Set = [] // messageID set\n \n // MARK: - Initialization\n \n init() {\n loadNickname()\n loadFavorites()\n loadBlockedUsers()\n loadVerifiedFingerprints()\n meshService.delegate = self\n \n // Log startup info\n \n // Log fingerprint after a delay to ensure encryption service is ready\n DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in\n if let self = self {\n _ = self.getMyFingerprint()\n }\n }\n \n // Start mesh service immediately\n meshService.startServices()\n \n // Set up message retry service\n MessageRetryService.shared.meshService = meshService\n \n // Set up Noise encryption callbacks\n setupNoiseCallbacks()\n \n // Request notification permission\n NotificationService.shared.requestAuthorization()\n \n // Subscribe to delivery status updates\n deliveryTrackerCancellable = DeliveryTracker.shared.deliveryStatusUpdated\n .receive(on: DispatchQueue.main)\n .sink { [weak self] (messageID, status) in\n self?.updateMessageDeliveryStatus(messageID, status: status)\n }\n \n // Listen for retry notifications\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(handleRetryMessage),\n name: Notification.Name(\"bitchat.retryMessage\"),\n object: nil\n )\n \n // When app becomes active, send read receipts for visible messages\n #if os(macOS)\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appDidBecomeActive),\n name: NSApplication.didBecomeActiveNotification,\n object: nil\n )\n \n // Add app lifecycle observers to save data\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillResignActive),\n name: NSApplication.willResignActiveNotification,\n object: nil\n )\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillTerminate),\n name: NSApplication.willTerminateNotification,\n object: nil\n )\n #else\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appDidBecomeActive),\n name: UIApplication.didBecomeActiveNotification,\n object: nil\n )\n \n // Add screenshot detection for iOS\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(userDidTakeScreenshot),\n name: UIApplication.userDidTakeScreenshotNotification,\n object: nil\n )\n \n // Add app lifecycle observers to save data\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillResignActive),\n name: UIApplication.willResignActiveNotification,\n object: nil\n )\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillTerminate),\n name: UIApplication.willTerminateNotification,\n object: nil\n )\n #endif\n }\n \n // MARK: - Deinitialization\n \n deinit {\n // Clean up timer\n messageBatchTimer?.invalidate()\n \n // Force immediate save\n userDefaults.synchronize()\n }\n \n // MARK: - Nickname Management\n \n private func loadNickname() {\n if let savedNickname = userDefaults.string(forKey: nicknameKey) {\n // Trim whitespace when loading\n nickname = savedNickname.trimmingCharacters(in: .whitespacesAndNewlines)\n } else {\n nickname = \"anon\\(Int.random(in: 1000...9999))\"\n saveNickname()\n }\n }\n \n func saveNickname() {\n userDefaults.set(nickname, forKey: nicknameKey)\n userDefaults.synchronize() // Force immediate save\n \n // Send announce with new nickname to all peers\n meshService.sendBroadcastAnnounce()\n }\n \n func validateAndSaveNickname() {\n // Trim whitespace from nickname\n let trimmed = nickname.trimmingCharacters(in: .whitespacesAndNewlines)\n \n // Check if nickname is empty after trimming\n if trimmed.isEmpty {\n nickname = \"anon\\(Int.random(in: 1000...9999))\"\n } else {\n nickname = trimmed\n }\n saveNickname()\n }\n \n // MARK: - Favorites Management\n \n private func loadFavorites() {\n // Load favorites from secure storage\n favoritePeers = SecureIdentityStateManager.shared.getFavorites()\n }\n \n private func saveFavorites() {\n // Favorites are now saved automatically in SecureIdentityStateManager\n // This method is kept for compatibility\n }\n \n // MARK: - Blocked Users Management\n \n private func loadBlockedUsers() {\n // Load blocked users from secure storage\n let allIdentities = SecureIdentityStateManager.shared.getAllSocialIdentities()\n blockedUsers = Set(allIdentities.filter { $0.isBlocked }.map { $0.fingerprint })\n }\n \n private func saveBlockedUsers() {\n // Blocked users are now saved automatically in SecureIdentityStateManager\n // This method is kept for compatibility\n }\n \n \n func toggleFavorite(peerID: String) {\n // First try to get fingerprint from mesh service (supports peer ID rotation)\n var fingerprint: String? = meshService.getFingerprint(for: peerID)\n \n // Fallback to local mapping if not found in mesh service\n if fingerprint == nil {\n fingerprint = peerIDToPublicKeyFingerprint[peerID]\n }\n \n guard let fp = fingerprint else {\n return\n }\n \n let isFavorite = SecureIdentityStateManager.shared.isFavorite(fingerprint: fp)\n SecureIdentityStateManager.shared.setFavorite(fp, isFavorite: !isFavorite)\n \n // Update local set for UI\n if isFavorite {\n favoritePeers.remove(fp)\n } else {\n favoritePeers.insert(fp)\n }\n }\n \n func isFavorite(peerID: String) -> Bool {\n // First try to get fingerprint from mesh service (supports peer ID rotation)\n var fingerprint: String? = meshService.getFingerprint(for: peerID)\n \n // Fallback to local mapping if not found in mesh service\n if fingerprint == nil {\n fingerprint = peerIDToPublicKeyFingerprint[peerID]\n }\n \n guard let fp = fingerprint else {\n return false\n }\n \n return SecureIdentityStateManager.shared.isFavorite(fingerprint: fp)\n }\n \n // MARK: - Public Key and Identity Management\n \n // Called when we receive a peer's public key\n func registerPeerPublicKey(peerID: String, publicKeyData: Data) {\n // Create a fingerprint from the public key (full SHA256, not truncated)\n let fingerprintStr = SHA256.hash(data: publicKeyData)\n .compactMap { String(format: \"%02x\", $0) }\n .joined()\n \n // Only register if not already registered\n if peerIDToPublicKeyFingerprint[peerID] != fingerprintStr {\n peerIDToPublicKeyFingerprint[peerID] = fingerprintStr\n }\n \n // Update identity state manager with handshake completion\n SecureIdentityStateManager.shared.updateHandshakeState(peerID: peerID, state: .completed(fingerprint: fingerprintStr))\n \n // Update encryption status now that we have the fingerprint\n updateEncryptionStatus(for: peerID)\n \n // Check if we have a claimed nickname for this peer\n let peerNicknames = meshService.getPeerNicknames()\n if let nickname = peerNicknames[peerID], nickname != \"Unknown\" && nickname != \"anon\\(peerID.prefix(4))\" {\n // Update or create social identity with the claimed nickname\n if var identity = SecureIdentityStateManager.shared.getSocialIdentity(for: fingerprintStr) {\n identity.claimedNickname = nickname\n SecureIdentityStateManager.shared.updateSocialIdentity(identity)\n } else {\n let newIdentity = SocialIdentity(\n fingerprint: fingerprintStr,\n localPetname: nil,\n claimedNickname: nickname,\n trustLevel: .casual,\n isFavorite: false,\n isBlocked: false,\n notes: nil\n )\n SecureIdentityStateManager.shared.updateSocialIdentity(newIdentity)\n }\n }\n \n // Check if this peer is the one we're in a private chat with\n updatePrivateChatPeerIfNeeded()\n }\n \n private func isPeerBlocked(_ peerID: String) -> Bool {\n // Check if we have the public key fingerprint for this peer\n if let fingerprint = peerIDToPublicKeyFingerprint[peerID] {\n return SecureIdentityStateManager.shared.isBlocked(fingerprint: fingerprint)\n }\n \n // Try to get fingerprint from mesh service\n if let fingerprint = meshService.getPeerFingerprint(peerID) {\n return SecureIdentityStateManager.shared.isBlocked(fingerprint: fingerprint)\n }\n \n return false\n }\n \n // Helper method to find current peer ID for a fingerprint\n private func getCurrentPeerIDForFingerprint(_ fingerprint: String) -> String? {\n // Search through all connected peers to find the one with matching fingerprint\n for peerID in connectedPeers {\n if let mappedFingerprint = peerIDToPublicKeyFingerprint[peerID],\n mappedFingerprint == fingerprint {\n return peerID\n }\n }\n return nil\n }\n \n // Helper method to update selectedPrivateChatPeer if fingerprint matches\n private func updatePrivateChatPeerIfNeeded() {\n guard let chatFingerprint = selectedPrivateChatFingerprint else { return }\n \n // Find current peer ID for the fingerprint\n if let currentPeerID = getCurrentPeerIDForFingerprint(chatFingerprint) {\n // Update the selected peer if it's different\n if let oldPeerID = selectedPrivateChatPeer, oldPeerID != currentPeerID {\n // Migrate messages from old peer ID to new peer ID\n if let oldMessages = privateChats[oldPeerID] {\n if privateChats[currentPeerID] == nil {\n privateChats[currentPeerID] = []\n }\n privateChats[currentPeerID]?.append(contentsOf: oldMessages)\n trimPrivateChatMessagesIfNeeded(for: currentPeerID)\n privateChats.removeValue(forKey: oldPeerID)\n }\n \n // Migrate unread status\n if unreadPrivateMessages.contains(oldPeerID) {\n unreadPrivateMessages.remove(oldPeerID)\n unreadPrivateMessages.insert(currentPeerID)\n }\n \n selectedPrivateChatPeer = currentPeerID\n } else if selectedPrivateChatPeer == nil {\n // Just set the peer ID if we don't have one\n selectedPrivateChatPeer = currentPeerID\n }\n \n // Clear unread messages for the current peer ID\n unreadPrivateMessages.remove(currentPeerID)\n }\n }\n \n // MARK: - Message Sending\n \n /// Sends a message through the BitChat network.\n /// - Parameter content: The message content to send\n /// - Note: Automatically handles command processing if content starts with '/'\n /// Routes to private chat if one is selected, otherwise broadcasts\n func sendMessage(_ content: String) {\n guard !content.isEmpty else { return }\n \n // Check for commands\n if content.hasPrefix(\"/\") {\n handleCommand(content)\n return\n }\n \n if selectedPrivateChatPeer != nil {\n // Update peer ID in case it changed due to reconnection\n updatePrivateChatPeerIfNeeded()\n \n if let selectedPeer = selectedPrivateChatPeer {\n // Send as private message\n sendPrivateMessage(content, to: selectedPeer)\n } else {\n }\n } else {\n // Parse mentions from the content\n let mentions = parseMentions(from: content)\n \n // Add message to local display\n let message = BitchatMessage(\n sender: nickname,\n content: content,\n timestamp: Date(),\n isRelay: false,\n originalSender: nil,\n isPrivate: false,\n recipientNickname: nil,\n senderPeerID: meshService.myPeerID,\n mentions: mentions.isEmpty ? nil : mentions\n )\n \n // Add to main messages immediately for user feedback\n messages.append(message)\n trimMessagesIfNeeded()\n \n // Force immediate UI update for user's own messages\n objectWillChange.send()\n \n // Send via mesh with mentions\n meshService.sendMessage(content, mentions: mentions)\n }\n }\n \n /// Sends an encrypted private message to a specific peer.\n /// - Parameters:\n /// - content: The message content to encrypt and send\n /// - peerID: The recipient's peer ID\n /// - Note: Automatically establishes Noise encryption if not already active\n func sendPrivateMessage(_ content: String, to peerID: String) {\n guard !content.isEmpty else { return }\n guard let recipientNickname = meshService.getPeerNicknames()[peerID] else { \n return \n }\n \n // Check if the recipient is blocked\n if isPeerBlocked(peerID) {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot send message to \\(recipientNickname): user is blocked.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n return\n }\n \n // IMPORTANT: When sending a message, it means we're viewing this chat\n // Send read receipts for any delivered messages from this peer\n markPrivateMessagesAsRead(from: peerID)\n \n // Create the message locally\n let message = BitchatMessage(\n sender: nickname,\n content: content,\n timestamp: Date(),\n isRelay: false,\n originalSender: nil,\n isPrivate: true,\n recipientNickname: recipientNickname,\n senderPeerID: meshService.myPeerID,\n deliveryStatus: .sending\n )\n \n // Add to our private chat history\n if privateChats[peerID] == nil {\n privateChats[peerID] = []\n }\n privateChats[peerID]?.append(message)\n trimPrivateChatMessagesIfNeeded(for: peerID)\n \n // Track the message for delivery confirmation\n let isFavorite = isFavorite(peerID: peerID)\n DeliveryTracker.shared.trackMessage(message, recipientID: peerID, recipientNickname: recipientNickname, isFavorite: isFavorite)\n \n // Immediate UI update for user's own messages\n objectWillChange.send()\n \n // Send via mesh with the same message ID\n meshService.sendPrivateMessage(content, to: peerID, recipientNickname: recipientNickname, messageID: message.id)\n }\n \n // MARK: - Private Chat Management\n \n /// Initiates a private chat session with a peer.\n /// - Parameter peerID: The peer's ID to start chatting with\n /// - Note: Switches the UI to private chat mode and loads message history\n func startPrivateChat(with peerID: String) {\n let peerNickname = meshService.getPeerNicknames()[peerID] ?? \"unknown\"\n \n // Check if the peer is blocked\n if isPeerBlocked(peerID) {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot start chat with \\(peerNickname): user is blocked.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n return\n }\n \n // Trigger handshake if we don't have a session yet\n let sessionState = meshService.getNoiseSessionState(for: peerID)\n switch sessionState {\n case .none, .failed:\n // Initiate handshake when opening PM\n meshService.triggerHandshake(with: peerID)\n default:\n break\n }\n \n selectedPrivateChatPeer = peerID\n // Also track by fingerprint for persistence across reconnections\n selectedPrivateChatFingerprint = peerIDToPublicKeyFingerprint[peerID]\n unreadPrivateMessages.remove(peerID)\n \n // Check if we need to migrate messages from an old peer ID\n // This happens when peer IDs change between sessions\n if privateChats[peerID] == nil || privateChats[peerID]?.isEmpty == true {\n \n // Look for messages from this nickname under other peer IDs\n var migratedMessages: [BitchatMessage] = []\n var oldPeerIDsToRemove: [String] = []\n \n for (oldPeerID, messages) in privateChats {\n if oldPeerID != peerID {\n // Check if any messages in this chat are from the peer's nickname\n // Check if this chat contains messages with this peer\n let messagesWithPeer = messages.filter { msg in\n // Message is FROM the peer to us\n (msg.sender == peerNickname && msg.sender != nickname) ||\n // OR message is FROM us TO the peer\n (msg.sender == nickname && (msg.recipientNickname == peerNickname || \n // Also check if this was a private message in a chat that only has us and one other person\n (msg.isPrivate && messages.allSatisfy { m in \n m.sender == nickname || m.sender == peerNickname \n })))\n }\n \n if !messagesWithPeer.isEmpty {\n \n // Check if ALL messages in this chat are between us and this peer\n let allMessagesAreWithPeer = messages.allSatisfy { msg in\n (msg.sender == peerNickname || msg.sender == nickname) &&\n (msg.recipientNickname == nil || msg.recipientNickname == peerNickname || msg.recipientNickname == nickname)\n }\n \n if allMessagesAreWithPeer {\n // This entire chat history belongs to this peer, migrate it all\n migratedMessages.append(contentsOf: messages)\n oldPeerIDsToRemove.append(oldPeerID)\n }\n }\n }\n }\n \n // Remove old peer ID entries that were fully migrated\n for oldPeerID in oldPeerIDsToRemove {\n privateChats.removeValue(forKey: oldPeerID)\n unreadPrivateMessages.remove(oldPeerID)\n }\n \n // Initialize chat history with migrated messages if any\n if !migratedMessages.isEmpty {\n privateChats[peerID] = migratedMessages.sorted { $0.timestamp < $1.timestamp }\n trimPrivateChatMessagesIfNeeded(for: peerID)\n } else {\n privateChats[peerID] = []\n }\n }\n \n _ = privateChats[peerID] ?? []\n \n // Send read receipts for unread messages from this peer\n // Add a small delay to ensure UI has updated\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [weak self] in\n self?.markPrivateMessagesAsRead(from: peerID)\n }\n \n // Also try immediately in case messages are already there\n markPrivateMessagesAsRead(from: peerID)\n }\n \n func endPrivateChat() {\n selectedPrivateChatPeer = nil\n selectedPrivateChatFingerprint = nil\n }\n \n // MARK: - Message Retry Handling\n \n @objc private func handleRetryMessage(_ notification: Notification) {\n guard let messageID = notification.userInfo?[\"messageID\"] as? String else { return }\n \n // Find the message to retry\n if let message = messages.first(where: { $0.id == messageID }) {\n SecureLogger.log(\"Retrying message \\(messageID) to \\(message.recipientNickname ?? \"unknown\")\", \n category: SecureLogger.session, level: .info)\n \n // Resend the message through mesh service\n if message.isPrivate,\n let peerID = getPeerIDForNickname(message.recipientNickname ?? \"\") {\n // Update status to sending\n updateMessageDeliveryStatus(messageID, status: .sending)\n \n // Resend via mesh service\n meshService.sendMessage(message.content, \n mentions: message.mentions ?? [], \n to: peerID,\n messageID: messageID,\n timestamp: message.timestamp)\n }\n }\n }\n \n // MARK: - App Lifecycle\n \n @objc private func appDidBecomeActive() {\n // When app becomes active, send read receipts for visible private chat\n if let peerID = selectedPrivateChatPeer {\n // Try immediately\n self.markPrivateMessagesAsRead(from: peerID)\n // And again with a delay\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {\n self.markPrivateMessagesAsRead(from: peerID)\n }\n }\n }\n \n @objc private func userDidTakeScreenshot() {\n // Send screenshot notification based on current context\n let screenshotMessage = \"* \\(nickname) took a screenshot *\"\n \n if let peerID = selectedPrivateChatPeer {\n // In private chat - send to the other person\n if let peerNickname = meshService.getPeerNicknames()[peerID] {\n // Only send screenshot notification if we have an established session\n // This prevents triggering handshake requests for screenshot notifications\n let sessionState = meshService.getNoiseSessionState(for: peerID)\n switch sessionState {\n case .established:\n // Send the message directly without going through sendPrivateMessage to avoid local echo\n meshService.sendPrivateMessage(screenshotMessage, to: peerID, recipientNickname: peerNickname)\n default:\n // Don't send screenshot notification if no session exists\n SecureLogger.log(\"Skipping screenshot notification to \\(peerID) - no established session\", category: SecureLogger.security, level: .debug)\n }\n }\n \n // Show local notification immediately as system message\n let localNotification = BitchatMessage(\n sender: \"system\",\n content: \"you took a screenshot\",\n timestamp: Date(),\n isRelay: false,\n originalSender: nil,\n isPrivate: true,\n recipientNickname: meshService.getPeerNicknames()[peerID],\n senderPeerID: meshService.myPeerID\n )\n if privateChats[peerID] == nil {\n privateChats[peerID] = []\n }\n privateChats[peerID]?.append(localNotification)\n trimPrivateChatMessagesIfNeeded(for: peerID)\n \n } else {\n // In public chat - send to everyone\n meshService.sendMessage(screenshotMessage, mentions: [])\n \n // Show local notification immediately as system message\n let localNotification = BitchatMessage(\n sender: \"system\",\n content: \"you took a screenshot\",\n timestamp: Date(),\n isRelay: false\n )\n // System messages can be batched\n addMessageToBatch(localNotification)\n }\n }\n \n @objc private func appWillResignActive() {\n // Flush any pending messages when app goes to background\n flushMessageBatchImmediately()\n \n userDefaults.synchronize()\n }\n \n @objc func applicationWillTerminate() {\n // Flush any pending messages immediately\n flushMessageBatchImmediately()\n \n // Force save any pending identity changes (verifications, favorites, etc)\n SecureIdentityStateManager.shared.forceSave()\n \n // Verify identity key is still there\n _ = KeychainManager.shared.verifyIdentityKeyExists()\n \n userDefaults.synchronize()\n \n // Verify identity key after save\n _ = KeychainManager.shared.verifyIdentityKeyExists()\n }\n \n @objc private func appWillTerminate() {\n // Flush any pending messages immediately\n flushMessageBatchImmediately()\n \n userDefaults.synchronize()\n }\n \n func markPrivateMessagesAsRead(from peerID: String) {\n // Get the nickname for this peer\n let peerNickname = meshService.getPeerNicknames()[peerID] ?? \"\"\n \n // First ensure we have the latest messages (in case of migration)\n if let messages = privateChats[peerID], !messages.isEmpty {\n } else {\n \n // Look through ALL private chats to find messages from this nickname\n for (_, chatMessages) in privateChats {\n let relevantMessages = chatMessages.filter { msg in\n msg.sender == peerNickname && msg.sender != nickname\n }\n if !relevantMessages.isEmpty {\n }\n }\n }\n \n guard let messages = privateChats[peerID], !messages.isEmpty else { \n return \n }\n \n \n // Find messages from the peer that haven't been read yet\n var readReceiptsSent = 0\n for (_, message) in messages.enumerated() {\n // Only send read receipts for messages from the other peer (not our own)\n // Check multiple conditions to ensure we catch all messages from the peer\n let isOurMessage = message.sender == nickname\n let isFromPeerByNickname = !peerNickname.isEmpty && message.sender == peerNickname\n let isFromPeerByID = message.senderPeerID == peerID\n let isPrivateToUs = message.isPrivate && message.recipientNickname == nickname\n \n // This is a message FROM the peer if it's not from us AND (matches nickname OR peer ID OR is private to us)\n let isFromPeer = !isOurMessage && (isFromPeerByNickname || isFromPeerByID || isPrivateToUs)\n \n if message.id == message.id { // Always true, for debugging\n }\n \n if isFromPeer {\n if let status = message.deliveryStatus {\n switch status {\n case .sent, .delivered:\n // Create and send read receipt for sent or delivered messages\n // Check if we've already sent a receipt for this message\n if !sentReadReceipts.contains(message.id) {\n // Send to the CURRENT peer ID, not the old senderPeerID which may have changed\n let receipt = ReadReceipt(\n originalMessageID: message.id,\n readerID: meshService.myPeerID,\n readerNickname: nickname\n )\n meshService.sendReadReceipt(receipt, to: peerID)\n sentReadReceipts.insert(message.id)\n readReceiptsSent += 1\n } else {\n }\n case .read:\n // Already read, no need to send another receipt\n break\n default:\n // Message not yet delivered, can't mark as read\n break\n }\n } else {\n // No delivery status - this might be an older message\n // Send read receipt anyway for backwards compatibility\n if !sentReadReceipts.contains(message.id) {\n let receipt = ReadReceipt(\n originalMessageID: message.id,\n readerID: meshService.myPeerID,\n readerNickname: nickname\n )\n meshService.sendReadReceipt(receipt, to: peerID)\n sentReadReceipts.insert(message.id)\n readReceiptsSent += 1\n } else {\n }\n }\n } else {\n }\n }\n \n }\n \n func getPrivateChatMessages(for peerID: String) -> [BitchatMessage] {\n let messages = privateChats[peerID] ?? []\n if !messages.isEmpty {\n }\n return messages\n }\n \n func getPeerIDForNickname(_ nickname: String) -> String? {\n let nicknames = meshService.getPeerNicknames()\n return nicknames.first(where: { $0.value == nickname })?.key\n }\n \n \n // MARK: - Emergency Functions\n \n // PANIC: Emergency data clearing for activist safety\n func panicClearAllData() {\n // Flush any pending messages immediately before clearing\n flushMessageBatchImmediately()\n \n // Clear all messages\n messages.removeAll()\n privateChats.removeAll()\n unreadPrivateMessages.removeAll()\n \n // First run aggressive cleanup to get rid of all legacy items\n _ = KeychainManager.shared.aggressiveCleanupLegacyItems()\n \n // Then delete all current keychain data\n _ = KeychainManager.shared.deleteAllKeychainData()\n \n // Clear UserDefaults identity fallbacks\n userDefaults.removeObject(forKey: \"bitchat.noiseIdentityKey\")\n userDefaults.removeObject(forKey: \"bitchat.messageRetentionKey\")\n \n // Clear verified fingerprints\n verifiedFingerprints.removeAll()\n // Verified fingerprints are cleared when identity data is cleared below\n \n // Clear message retry queue\n MessageRetryService.shared.clearRetryQueue()\n \n \n // Reset nickname to anonymous\n nickname = \"anon\\(Int.random(in: 1000...9999))\"\n saveNickname()\n \n // Clear favorites\n favoritePeers.removeAll()\n peerIDToPublicKeyFingerprint.removeAll()\n \n // Clear identity data from secure storage\n SecureIdentityStateManager.shared.clearAllIdentityData()\n \n // Clear autocomplete state\n autocompleteSuggestions.removeAll()\n showAutocomplete = false\n autocompleteRange = nil\n selectedAutocompleteIndex = 0\n \n // Clear selected private chat\n selectedPrivateChatPeer = nil\n selectedPrivateChatFingerprint = nil\n \n // Clear read receipt tracking\n sentReadReceipts.removeAll()\n \n // Clear all caches\n invalidateEncryptionCache()\n invalidateRSSIColorCache()\n \n // Disconnect from all peers and clear persistent identity\n // This will force creation of a new identity (new fingerprint) on next launch\n meshService.emergencyDisconnectAll()\n \n // Force immediate UserDefaults synchronization\n userDefaults.synchronize()\n \n // Force UI update\n objectWillChange.send()\n \n }\n \n \n \n // MARK: - Formatting Helpers\n \n func formatTimestamp(_ date: Date) -> String {\n let formatter = DateFormatter()\n formatter.dateFormat = \"HH:mm:ss\"\n return formatter.string(from: date)\n }\n \n func getRSSIColor(rssi: Int, colorScheme: ColorScheme) -> Color {\n let isDark = colorScheme == .dark\n let cacheKey = \"\\(rssi)_\\(isDark)\"\n \n // Check cache first\n if let cachedColor = rssiColorCache[cacheKey] {\n return cachedColor\n }\n \n // RSSI typically ranges from -30 (excellent) to -90 (poor)\n // We'll map this to colors from green (strong) to red (weak)\n \n let color: Color\n if rssi >= -50 {\n // Excellent signal: bright green\n color = isDark ? Color(red: 0.0, green: 1.0, blue: 0.0) : Color(red: 0.0, green: 0.7, blue: 0.0)\n } else if rssi >= -60 {\n // Good signal: green-yellow\n color = isDark ? Color(red: 0.5, green: 1.0, blue: 0.0) : Color(red: 0.3, green: 0.7, blue: 0.0)\n } else if rssi >= -70 {\n // Fair signal: yellow\n color = isDark ? Color(red: 1.0, green: 1.0, blue: 0.0) : Color(red: 0.7, green: 0.7, blue: 0.0)\n } else if rssi >= -80 {\n // Weak signal: orange\n color = isDark ? Color(red: 1.0, green: 0.6, blue: 0.0) : Color(red: 0.8, green: 0.4, blue: 0.0)\n } else {\n // Poor signal: red\n color = isDark ? Color(red: 1.0, green: 0.2, blue: 0.2) : Color(red: 0.8, green: 0.0, blue: 0.0)\n }\n \n // Cache the result\n rssiColorCache[cacheKey] = color\n return color\n }\n \n // MARK: - Autocomplete\n \n func updateAutocomplete(for text: String, cursorPosition: Int) {\n // Quick early exit for empty text\n guard cursorPosition > 0 else {\n if showAutocomplete {\n showAutocomplete = false\n autocompleteSuggestions = []\n autocompleteRange = nil\n }\n return\n }\n \n // Find @ symbol before cursor\n let beforeCursor = String(text.prefix(cursorPosition))\n \n // Use cached regex\n guard let regex = mentionRegex,\n let match = regex.firstMatch(in: beforeCursor, options: [], range: NSRange(location: 0, length: beforeCursor.count)) else {\n if showAutocomplete {\n showAutocomplete = false\n autocompleteSuggestions = []\n autocompleteRange = nil\n }\n return\n }\n \n // Extract the partial nickname\n let partialRange = match.range(at: 1)\n guard let range = Range(partialRange, in: beforeCursor) else {\n if showAutocomplete {\n showAutocomplete = false\n autocompleteSuggestions = []\n autocompleteRange = nil\n }\n return\n }\n \n let partial = String(beforeCursor[range]).lowercased()\n \n // Update cached nicknames only if peer list changed (check every 1 second max)\n let now = Date()\n if now.timeIntervalSince(lastNicknameUpdate) > 1.0 || cachedNicknames.isEmpty {\n let peerNicknames = meshService.getPeerNicknames()\n cachedNicknames = Array(peerNicknames.values).sorted()\n lastNicknameUpdate = now\n }\n \n // Filter suggestions using cached nicknames\n let suggestions = cachedNicknames.filter { nick in\n nick.lowercased().hasPrefix(partial)\n }\n \n // Batch UI updates\n if !suggestions.isEmpty {\n // Only update if suggestions changed\n if autocompleteSuggestions != suggestions {\n autocompleteSuggestions = suggestions\n }\n if !showAutocomplete {\n showAutocomplete = true\n }\n if autocompleteRange != match.range(at: 0) {\n autocompleteRange = match.range(at: 0)\n }\n selectedAutocompleteIndex = 0\n } else {\n if showAutocomplete {\n showAutocomplete = false\n autocompleteSuggestions = []\n autocompleteRange = nil\n selectedAutocompleteIndex = 0\n }\n }\n }\n \n func completeNickname(_ nickname: String, in text: inout String) -> Int {\n guard let range = autocompleteRange else { return text.count }\n \n // Replace the @partial with @nickname\n let nsText = text as NSString\n let newText = nsText.replacingCharacters(in: range, with: \"@\\(nickname) \")\n text = newText\n \n // Hide autocomplete\n showAutocomplete = false\n autocompleteSuggestions = []\n autocompleteRange = nil\n selectedAutocompleteIndex = 0\n \n // Return new cursor position (after the space)\n return range.location + nickname.count + 2\n }\n \n // MARK: - Message Formatting\n \n func getSenderColor(for message: BitchatMessage, colorScheme: ColorScheme) -> Color {\n let isDark = colorScheme == .dark\n let primaryColor = isDark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n \n // Always use the same color for all senders - no RSSI-based coloring\n return primaryColor\n }\n \n \n func formatMessageContent(_ message: BitchatMessage, colorScheme: ColorScheme) -> AttributedString {\n let isDark = colorScheme == .dark\n let contentText = message.content\n var processedContent = AttributedString()\n \n // Regular expressions for mentions and hashtags\n let mentionPattern = \"@([a-zA-Z0-9_]+)\"\n let hashtagPattern = \"#([a-zA-Z0-9_]+)\"\n \n let mentionRegex = try? NSRegularExpression(pattern: mentionPattern, options: [])\n let hashtagRegex = try? NSRegularExpression(pattern: hashtagPattern, options: [])\n \n let mentionMatches = mentionRegex?.matches(in: contentText, options: [], range: NSRange(location: 0, length: contentText.count)) ?? []\n let hashtagMatches = hashtagRegex?.matches(in: contentText, options: [], range: NSRange(location: 0, length: contentText.count)) ?? []\n \n // Combine and sort all matches\n var allMatches: [(range: NSRange, type: String)] = []\n for match in mentionMatches {\n allMatches.append((match.range(at: 0), \"mention\"))\n }\n for match in hashtagMatches {\n allMatches.append((match.range(at: 0), \"hashtag\"))\n }\n allMatches.sort { $0.range.location < $1.range.location }\n \n var lastEndIndex = contentText.startIndex\n \n for (matchRange, matchType) in allMatches {\n // Add text before the match\n if let range = Range(matchRange, in: contentText) {\n let beforeText = String(contentText[lastEndIndex.. AttributedString {\n // Check cache first\n let isDark = colorScheme == .dark\n if let cachedText = message.getCachedFormattedText(isDark: isDark) {\n return cachedText\n }\n \n // Not cached, format the message\n var result = AttributedString()\n \n let primaryColor = isDark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n let secondaryColor = primaryColor.opacity(0.7)\n \n // Timestamp\n let timestamp = AttributedString(\"[\\(formatTimestamp(message.timestamp))] \")\n var timestampStyle = AttributeContainer()\n timestampStyle.foregroundColor = message.sender == \"system\" ? Color.gray : secondaryColor\n timestampStyle.font = .system(size: 12, design: .monospaced)\n result.append(timestamp.mergingAttributes(timestampStyle))\n \n if message.sender != \"system\" {\n // Sender\n let sender = AttributedString(\"<@\\(message.sender)> \")\n var senderStyle = AttributeContainer()\n \n // Use consistent color for all senders\n senderStyle.foregroundColor = primaryColor\n // Bold the user's own nickname\n let fontWeight: Font.Weight = message.sender == nickname ? .bold : .medium\n senderStyle.font = .system(size: 14, weight: fontWeight, design: .monospaced)\n result.append(sender.mergingAttributes(senderStyle))\n \n // Process content with hashtags and mentions\n let content = message.content\n \n let hashtagPattern = \"#([a-zA-Z0-9_]+)\"\n let mentionPattern = \"@([a-zA-Z0-9_]+)\"\n \n let hashtagRegex = try? NSRegularExpression(pattern: hashtagPattern, options: [])\n let mentionRegex = try? NSRegularExpression(pattern: mentionPattern, options: [])\n \n // Use NSDataDetector for URL detection\n let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)\n \n let hashtagMatches = hashtagRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n let mentionMatches = mentionRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n let urlMatches = detector?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n \n // Combine and sort matches\n var allMatches: [(range: NSRange, type: String)] = []\n for match in hashtagMatches {\n allMatches.append((match.range(at: 0), \"hashtag\"))\n }\n for match in mentionMatches {\n allMatches.append((match.range(at: 0), \"mention\"))\n }\n for match in urlMatches {\n allMatches.append((match.range, \"url\"))\n }\n allMatches.sort { $0.range.location < $1.range.location }\n \n // Build content with styling\n var lastEnd = content.startIndex\n let isMentioned = message.mentions?.contains(nickname) ?? false\n \n for (range, type) in allMatches {\n // Add text before match\n if let nsRange = Range(range, in: content) {\n let beforeText = String(content[lastEnd.. AttributedString {\n var result = AttributedString()\n \n let isDark = colorScheme == .dark\n let primaryColor = isDark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n let secondaryColor = primaryColor.opacity(0.7)\n \n let timestamp = AttributedString(\"[\\(formatTimestamp(message.timestamp))] \")\n var timestampStyle = AttributeContainer()\n timestampStyle.foregroundColor = message.sender == \"system\" ? Color.gray : secondaryColor\n timestampStyle.font = .system(size: 12, design: .monospaced)\n result.append(timestamp.mergingAttributes(timestampStyle))\n \n if message.sender == \"system\" {\n let content = AttributedString(\"* \\(message.content) *\")\n var contentStyle = AttributeContainer()\n contentStyle.foregroundColor = Color.gray\n contentStyle.font = .system(size: 12, design: .monospaced).italic()\n result.append(content.mergingAttributes(contentStyle))\n } else {\n let sender = AttributedString(\"<\\(message.sender)> \")\n var senderStyle = AttributeContainer()\n \n // Use consistent color for all senders\n senderStyle.foregroundColor = primaryColor\n // Bold the user's own nickname\n let fontWeight: Font.Weight = message.sender == nickname ? .bold : .medium\n senderStyle.font = .system(size: 12, weight: fontWeight, design: .monospaced)\n result.append(sender.mergingAttributes(senderStyle))\n \n \n // Process content to highlight mentions\n let contentText = message.content\n var processedContent = AttributedString()\n \n // Regular expression to find @mentions\n let pattern = \"@([a-zA-Z0-9_]+)\"\n let regex = try? NSRegularExpression(pattern: pattern, options: [])\n let matches = regex?.matches(in: contentText, options: [], range: NSRange(location: 0, length: contentText.count)) ?? []\n \n var lastEndIndex = contentText.startIndex\n \n for match in matches {\n // Add text before the mention\n if let range = Range(match.range(at: 0), in: contentText) {\n let beforeText = String(contentText[lastEndIndex.. EncryptionStatus {\n // Check cache first\n if let cachedStatus = encryptionStatusCache[peerID] {\n return cachedStatus\n }\n \n // This must be a pure function - no state mutations allowed\n // to avoid SwiftUI update loops\n \n let sessionState = meshService.getNoiseSessionState(for: peerID)\n let storedStatus = peerEncryptionStatus[peerID]\n \n let status: EncryptionStatus\n \n // Determine status based on session state\n switch sessionState {\n case .established:\n // We have encryption, now check if it's verified\n if let fingerprint = getFingerprint(for: peerID) {\n if verifiedFingerprints.contains(fingerprint) {\n status = .noiseVerified\n } else {\n status = .noiseSecured\n }\n } else {\n // We have a session but no fingerprint yet - still secured\n status = .noiseSecured\n }\n case .handshaking, .handshakeQueued:\n // Currently establishing encryption\n status = .noiseHandshaking\n case .none:\n // No handshake attempted\n status = .noHandshake\n case .failed:\n // Handshake failed - show broken lock\n status = .none\n }\n \n // Cache the result\n encryptionStatusCache[peerID] = status\n \n // Only log occasionally to avoid spam\n if Int.random(in: 0..<100) == 0 {\n SecureLogger.log(\"getEncryptionStatus for \\(peerID): sessionState=\\(sessionState), stored=\\(String(describing: storedStatus)), final=\\(status)\", category: SecureLogger.security, level: .debug)\n }\n \n return status\n }\n \n // Clear caches when data changes\n private func invalidateEncryptionCache(for peerID: String? = nil) {\n if let peerID = peerID {\n encryptionStatusCache.removeValue(forKey: peerID)\n } else {\n encryptionStatusCache.removeAll()\n }\n }\n \n private func invalidateRSSIColorCache() {\n rssiColorCache.removeAll()\n }\n \n // MARK: - Message Batching\n \n private func trimMessagesIfNeeded() {\n if messages.count > maxMessages {\n let removeCount = messages.count - maxMessages\n messages.removeFirst(removeCount)\n }\n }\n \n private func trimPrivateChatMessagesIfNeeded(for peerID: String) {\n if let count = privateChats[peerID]?.count, count > maxMessages {\n let removeCount = count - maxMessages\n privateChats[peerID]?.removeFirst(removeCount)\n }\n }\n \n private func addMessageToBatch(_ message: BitchatMessage) {\n pendingMessages.append(message)\n scheduleBatchFlush()\n }\n \n private func addPrivateMessageToBatch(_ message: BitchatMessage, for peerID: String) {\n if pendingPrivateMessages[peerID] == nil {\n pendingPrivateMessages[peerID] = []\n }\n pendingPrivateMessages[peerID]?.append(message)\n scheduleBatchFlush()\n }\n \n private func scheduleBatchFlush() {\n // Cancel existing timer\n messageBatchTimer?.invalidate()\n \n // Schedule new flush\n messageBatchTimer = Timer.scheduledTimer(withTimeInterval: messageBatchInterval, repeats: false) { [weak self] _ in\n self?.flushMessageBatch()\n }\n }\n \n private func flushMessageBatch() {\n DispatchQueue.main.async { [weak self] in\n guard let self = self else { return }\n \n // Process pending public messages\n if !self.pendingMessages.isEmpty {\n let messagesToAdd = self.pendingMessages\n self.pendingMessages.removeAll()\n \n // Add all messages at once\n self.messages.append(contentsOf: messagesToAdd)\n \n // Sort once after batch addition\n self.messages.sort { $0.timestamp < $1.timestamp }\n \n // Trim once if needed\n self.trimMessagesIfNeeded()\n }\n \n // Process pending private messages\n if !self.pendingPrivateMessages.isEmpty {\n let privateMessageBatches = self.pendingPrivateMessages\n self.pendingPrivateMessages.removeAll()\n \n for (peerID, messagesToAdd) in privateMessageBatches {\n if self.privateChats[peerID] == nil {\n self.privateChats[peerID] = []\n }\n \n // Add all messages for this peer at once\n self.privateChats[peerID]?.append(contentsOf: messagesToAdd)\n \n // Sort once after batch addition\n self.privateChats[peerID]?.sort { $0.timestamp < $1.timestamp }\n \n // Trim once if needed\n self.trimPrivateChatMessagesIfNeeded(for: peerID)\n }\n }\n \n // Single UI update for all changes\n self.objectWillChange.send()\n }\n }\n \n // Force immediate flush for high-priority messages\n private func flushMessageBatchImmediately() {\n messageBatchTimer?.invalidate()\n flushMessageBatch()\n }\n \n // Update encryption status in appropriate places, not during view updates\n private func updateEncryptionStatus(for peerID: String) {\n let noiseService = meshService.getNoiseService()\n \n if noiseService.hasEstablishedSession(with: peerID) {\n if let fingerprint = getFingerprint(for: peerID) {\n if verifiedFingerprints.contains(fingerprint) {\n peerEncryptionStatus[peerID] = .noiseVerified\n } else {\n peerEncryptionStatus[peerID] = .noiseSecured\n }\n } else {\n // Session established but no fingerprint yet\n peerEncryptionStatus[peerID] = .noiseSecured\n }\n } else if noiseService.hasSession(with: peerID) {\n peerEncryptionStatus[peerID] = .noiseHandshaking\n } else {\n peerEncryptionStatus[peerID] = Optional.none\n }\n \n // Invalidate cache when encryption status changes\n invalidateEncryptionCache(for: peerID)\n \n // Trigger UI update\n DispatchQueue.main.async { [weak self] in\n self?.objectWillChange.send()\n }\n }\n \n // MARK: - Fingerprint Management\n \n func showFingerprint(for peerID: String) {\n showingFingerprintFor = peerID\n }\n \n func getFingerprint(for peerID: String) -> String? {\n // Remove debug logging to prevent console spam during view updates\n \n // First try to get fingerprint from mesh service's peer ID rotation mapping\n if let fingerprint = meshService.getFingerprint(for: peerID) {\n return fingerprint\n }\n \n // Fallback to noise service (direct Noise session fingerprint)\n if let fingerprint = meshService.getNoiseService().getPeerFingerprint(peerID) {\n return fingerprint\n }\n \n // Last resort: check local mapping\n if let fingerprint = peerIDToPublicKeyFingerprint[peerID] {\n return fingerprint\n }\n \n return nil\n }\n \n // Helper to resolve nickname for a peer ID through various sources\n func resolveNickname(for peerID: String) -> String {\n // Guard against empty or very short peer IDs\n guard !peerID.isEmpty else {\n return \"unknown\"\n }\n \n // Check if this might already be a nickname (not a hex peer ID)\n // Peer IDs are hex strings, so they only contain 0-9 and a-f\n let isHexID = peerID.allSatisfy { $0.isHexDigit }\n if !isHexID {\n // If it's already a nickname, just return it\n return peerID\n }\n \n // First try direct peer nicknames from mesh service\n let peerNicknames = meshService.getPeerNicknames()\n if let nickname = peerNicknames[peerID] {\n return nickname\n }\n \n // Try to resolve through fingerprint and social identity\n if let fingerprint = getFingerprint(for: peerID) {\n if let identity = SecureIdentityStateManager.shared.getSocialIdentity(for: fingerprint) {\n // Prefer local petname if set\n if let petname = identity.localPetname {\n return petname\n }\n // Otherwise use their claimed nickname\n return identity.claimedNickname\n }\n }\n \n // Fallback to anonymous with shortened peer ID\n // Ensure we have at least 4 characters for the prefix\n let prefixLength = min(4, peerID.count)\n let prefix = String(peerID.prefix(prefixLength))\n \n // Avoid \"anonanon\" by checking if ID already starts with \"anon\"\n if prefix.starts(with: \"anon\") {\n return \"peer\\(prefix)\"\n }\n return \"anon\\(prefix)\"\n }\n \n func getMyFingerprint() -> String {\n let fingerprint = meshService.getNoiseService().getIdentityFingerprint()\n return fingerprint\n }\n \n func verifyFingerprint(for peerID: String) {\n guard let fingerprint = getFingerprint(for: peerID) else { return }\n \n // Update secure storage with verified status\n SecureIdentityStateManager.shared.setVerified(fingerprint: fingerprint, verified: true)\n \n // Update local set for UI\n verifiedFingerprints.insert(fingerprint)\n \n // Update encryption status after verification\n updateEncryptionStatus(for: peerID)\n }\n \n func loadVerifiedFingerprints() {\n // Load verified fingerprints directly from secure storage\n verifiedFingerprints = SecureIdentityStateManager.shared.getVerifiedFingerprints()\n }\n \n private func setupNoiseCallbacks() {\n let noiseService = meshService.getNoiseService()\n \n // Set up authentication callback\n noiseService.onPeerAuthenticated = { [weak self] peerID, fingerprint in\n DispatchQueue.main.async {\n guard let self = self else { return }\n \n SecureLogger.log(\"ChatViewModel: Peer authenticated - \\(peerID), fingerprint: \\(fingerprint)\", category: SecureLogger.security, level: .info)\n \n // Update encryption status\n if self.verifiedFingerprints.contains(fingerprint) {\n self.peerEncryptionStatus[peerID] = .noiseVerified\n SecureLogger.log(\"ChatViewModel: Setting encryption status to noiseVerified for \\(peerID)\", category: SecureLogger.security, level: .info)\n } else {\n self.peerEncryptionStatus[peerID] = .noiseSecured\n SecureLogger.log(\"ChatViewModel: Setting encryption status to noiseSecured for \\(peerID)\", category: SecureLogger.security, level: .info)\n }\n \n // Invalidate cache when encryption status changes\n self.invalidateEncryptionCache(for: peerID)\n \n // Force UI update\n self.objectWillChange.send()\n }\n }\n \n // Set up handshake required callback\n noiseService.onHandshakeRequired = { [weak self] peerID in\n DispatchQueue.main.async {\n guard let self = self else { return }\n self.peerEncryptionStatus[peerID] = .noiseHandshaking\n \n // Invalidate cache when encryption status changes\n self.invalidateEncryptionCache(for: peerID)\n \n // Force UI update\n self.objectWillChange.send()\n }\n }\n }\n}\n\n// MARK: - BitchatDelegate\n\nextension ChatViewModel: BitchatDelegate {\n \n // MARK: - Command Handling\n \n /// Processes IRC-style commands starting with '/'.\n /// - Parameter command: The full command string including the leading slash\n /// - Note: Supports commands like /nick, /msg, /who, /slap, /clear, /help\n private func handleCommand(_ command: String) {\n let parts = command.split(separator: \" \")\n guard let cmd = parts.first else { return }\n \n switch cmd {\n case \"/m\", \"/msg\":\n if parts.count > 1 {\n let targetName = String(parts[1])\n // Remove @ if present\n let nickname = targetName.hasPrefix(\"@\") ? String(targetName.dropFirst()) : targetName\n \n // Find peer ID for this nickname\n if let peerID = getPeerIDForNickname(nickname) {\n startPrivateChat(with: peerID)\n \n // If there's a message after the nickname, send it\n if parts.count > 2 {\n let messageContent = parts[2...].joined(separator: \" \")\n sendPrivateMessage(messageContent, to: peerID)\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"started private chat with \\(nickname)\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"user '\\(nickname)' not found. they may be offline or using a different nickname.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"usage: /m @nickname [message] or /m nickname [message]\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n case \"/w\":\n let peerNicknames = meshService.getPeerNicknames()\n if connectedPeers.isEmpty {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"no one else is online right now.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n } else {\n let onlineList = connectedPeers.compactMap { peerID in\n peerNicknames[peerID]\n }.sorted().joined(separator: \", \")\n \n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"online users: \\(onlineList)\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n case \"/clear\":\n // Clear messages based on current context\n if let peerID = selectedPrivateChatPeer {\n // Clear private chat\n privateChats[peerID]?.removeAll()\n } else {\n // Clear main messages\n messages.removeAll()\n }\n case \"/hug\":\n if parts.count > 1 {\n let targetName = String(parts[1])\n // Remove @ if present\n let nickname = targetName.hasPrefix(\"@\") ? String(targetName.dropFirst()) : targetName\n \n // Check if target exists in connected peers\n if let targetPeerID = getPeerIDForNickname(nickname) {\n // Create hug message\n let hugMessage = BitchatMessage(\n sender: \"system\",\n content: \"🫂 \\(self.nickname) hugs \\(nickname)\",\n timestamp: Date(),\n isRelay: false,\n isPrivate: false,\n recipientNickname: nickname,\n senderPeerID: meshService.myPeerID\n )\n \n // Send as a regular message but it will be displayed as system message due to content\n let hugContent = \"* 🫂 \\(self.nickname) hugs \\(nickname) *\"\n if selectedPrivateChatPeer != nil {\n // In private chat, send as private message\n if let peerNickname = meshService.getPeerNicknames()[targetPeerID] {\n meshService.sendPrivateMessage(\"* 🫂 \\(self.nickname) hugs you *\", to: targetPeerID, recipientNickname: peerNickname)\n }\n } else {\n // In public chat\n meshService.sendMessage(hugContent)\n messages.append(hugMessage)\n }\n } else {\n let errorMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot hug \\(nickname): user not found.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(errorMessage)\n }\n } else {\n let usageMessage = BitchatMessage(\n sender: \"system\",\n content: \"usage: /hug \",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(usageMessage)\n }\n \n case \"/slap\":\n if parts.count > 1 {\n let targetName = String(parts[1])\n // Remove @ if present\n let nickname = targetName.hasPrefix(\"@\") ? String(targetName.dropFirst()) : targetName\n \n // Check if target exists in connected peers\n if let targetPeerID = getPeerIDForNickname(nickname) {\n // Create slap message\n let slapMessage = BitchatMessage(\n sender: \"system\",\n content: \"🐟 \\(self.nickname) slaps \\(nickname) around a bit with a large trout\",\n timestamp: Date(),\n isRelay: false,\n isPrivate: false,\n recipientNickname: nickname,\n senderPeerID: meshService.myPeerID\n )\n \n // Send as a regular message but it will be displayed as system message due to content\n let slapContent = \"* 🐟 \\(self.nickname) slaps \\(nickname) around a bit with a large trout *\"\n if selectedPrivateChatPeer != nil {\n // In private chat, send as private message\n if let peerNickname = meshService.getPeerNicknames()[targetPeerID] {\n meshService.sendPrivateMessage(\"* 🐟 \\(self.nickname) slaps you around a bit with a large trout *\", to: targetPeerID, recipientNickname: peerNickname)\n }\n } else {\n // In public chat\n meshService.sendMessage(slapContent)\n messages.append(slapMessage)\n }\n } else {\n let errorMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot slap \\(nickname): user not found.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(errorMessage)\n }\n } else {\n let usageMessage = BitchatMessage(\n sender: \"system\",\n content: \"usage: /slap \",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(usageMessage)\n }\n \n case \"/block\":\n if parts.count > 1 {\n let targetName = String(parts[1])\n // Remove @ if present\n let nickname = targetName.hasPrefix(\"@\") ? String(targetName.dropFirst()) : targetName\n \n // Find peer ID for this nickname\n if let peerID = getPeerIDForNickname(nickname) {\n // Get fingerprint for persistent blocking\n if let fingerprintStr = meshService.getPeerFingerprint(peerID) {\n \n if SecureIdentityStateManager.shared.isBlocked(fingerprint: fingerprintStr) {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"\\(nickname) is already blocked.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n } else {\n // Update or create social identity with blocked status\n if var identity = SecureIdentityStateManager.shared.getSocialIdentity(for: fingerprintStr) {\n identity.isBlocked = true\n identity.isFavorite = false // Remove from favorites if blocked\n SecureIdentityStateManager.shared.updateSocialIdentity(identity)\n } else {\n let blockedIdentity = SocialIdentity(\n fingerprint: fingerprintStr,\n localPetname: nil,\n claimedNickname: nickname,\n trustLevel: .unknown,\n isFavorite: false,\n isBlocked: true,\n notes: nil\n )\n SecureIdentityStateManager.shared.updateSocialIdentity(blockedIdentity)\n }\n \n // Update local sets for UI\n blockedUsers.insert(fingerprintStr)\n favoritePeers.remove(fingerprintStr)\n \n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"blocked \\(nickname). you will no longer receive messages from them.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot block \\(nickname): unable to verify identity.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot block \\(nickname): user not found.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n // List blocked users\n if blockedUsers.isEmpty {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"no blocked peers.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n } else {\n // Find nicknames for blocked users\n var blockedNicknames: [String] = []\n for (peerID, _) in meshService.getPeerNicknames() {\n if let fingerprintStr = meshService.getPeerFingerprint(peerID) {\n if blockedUsers.contains(fingerprintStr) {\n if let nickname = meshService.getPeerNicknames()[peerID] {\n blockedNicknames.append(nickname)\n }\n }\n }\n }\n \n let blockedList = blockedNicknames.isEmpty ? \"blocked peers (not currently online)\" : blockedNicknames.sorted().joined(separator: \", \")\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"blocked peers: \\(blockedList)\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n }\n \n case \"/unblock\":\n if parts.count > 1 {\n let targetName = String(parts[1])\n // Remove @ if present\n let nickname = targetName.hasPrefix(\"@\") ? String(targetName.dropFirst()) : targetName\n \n // Find peer ID for this nickname\n if let peerID = getPeerIDForNickname(nickname) {\n // Get fingerprint\n if let fingerprintStr = meshService.getPeerFingerprint(peerID) {\n \n if SecureIdentityStateManager.shared.isBlocked(fingerprint: fingerprintStr) {\n // Update social identity to unblock\n SecureIdentityStateManager.shared.setBlocked(fingerprintStr, isBlocked: false)\n \n // Update local set for UI\n blockedUsers.remove(fingerprintStr)\n \n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"unblocked \\(nickname).\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"\\(nickname) is not blocked.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot unblock \\(nickname): unable to verify identity.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot unblock \\(nickname): user not found.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"usage: /unblock \",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n \n default:\n // Unknown command\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"unknown command: \\(cmd).\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n }\n \n // MARK: - Message Reception\n \n func handleHandshakeRequest(from peerID: String, nickname: String, pendingCount: UInt8) {\n // Create a notification message\n let notificationMessage = BitchatMessage(\n sender: \"system\",\n content: \"📨 \\(nickname) wants to send you \\(pendingCount) message\\(pendingCount == 1 ? \"\" : \"s\"). Open the conversation to receive.\",\n timestamp: Date(),\n isRelay: false,\n originalSender: nil,\n isPrivate: false,\n recipientNickname: nil,\n senderPeerID: \"system\",\n mentions: nil\n )\n \n // Add to messages\n messages.append(notificationMessage)\n trimMessagesIfNeeded()\n \n // Show system notification\n if let fingerprint = getFingerprint(for: peerID) {\n let isFavorite = favoritePeers.contains(fingerprint)\n if isFavorite {\n // Send favorite notification\n NotificationService.shared.sendPrivateMessageNotification(\n from: nickname,\n message: \"\\(pendingCount) message\\(pendingCount == 1 ? \"\" : \"s\") pending\",\n peerID: peerID\n )\n } else {\n // Send regular notification\n NotificationService.shared.sendMentionNotification(\n from: nickname,\n message: \"\\(pendingCount) message\\(pendingCount == 1 ? \"\" : \"s\") pending. Open conversation to receive.\"\n )\n }\n }\n }\n \n func didReceiveMessage(_ message: BitchatMessage) {\n \n \n // Check if sender is blocked (for both private and public messages)\n if let senderPeerID = message.senderPeerID {\n if isPeerBlocked(senderPeerID) {\n // Silently ignore messages from blocked users\n return\n }\n } else if let peerID = getPeerIDForNickname(message.sender) {\n if isPeerBlocked(peerID) {\n // Silently ignore messages from blocked users\n return\n }\n }\n \n if message.isPrivate {\n // Handle private message\n \n // Use the senderPeerID from the message if available\n let senderPeerID = message.senderPeerID ?? getPeerIDForNickname(message.sender)\n \n if let peerID = senderPeerID {\n // Message from someone else\n \n // First check if we need to migrate existing messages from this sender\n let senderNickname = message.sender\n if privateChats[peerID] == nil || privateChats[peerID]?.isEmpty == true {\n // Check if we have messages from this nickname under a different peer ID\n var migratedMessages: [BitchatMessage] = []\n var oldPeerIDsToRemove: [String] = []\n \n for (oldPeerID, messages) in privateChats {\n if oldPeerID != peerID {\n // Check if this chat contains messages with this sender\n let isRelevantChat = messages.contains { msg in\n (msg.sender == senderNickname && msg.sender != nickname) ||\n (msg.sender == nickname && msg.recipientNickname == senderNickname)\n }\n \n if isRelevantChat {\n migratedMessages.append(contentsOf: messages)\n oldPeerIDsToRemove.append(oldPeerID)\n }\n }\n }\n \n // Remove old peer ID entries\n for oldPeerID in oldPeerIDsToRemove {\n privateChats.removeValue(forKey: oldPeerID)\n unreadPrivateMessages.remove(oldPeerID)\n }\n \n // Initialize with migrated messages\n privateChats[peerID] = migratedMessages\n trimPrivateChatMessagesIfNeeded(for: peerID)\n }\n \n if privateChats[peerID] == nil {\n privateChats[peerID] = []\n }\n \n // Fix delivery status for incoming messages\n var messageToStore = message\n if message.sender != nickname {\n // This is an incoming message - it should NOT have \"sending\" status\n if messageToStore.deliveryStatus == nil || messageToStore.deliveryStatus == .sending {\n // Mark it as delivered since we received it\n messageToStore.deliveryStatus = .delivered(to: nickname, at: Date())\n }\n }\n \n // Check if this is an action that should be converted to system message\n let isActionMessage = messageToStore.content.hasPrefix(\"* \") && messageToStore.content.hasSuffix(\" *\") &&\n (messageToStore.content.contains(\"🫂\") || messageToStore.content.contains(\"🐟\") || \n messageToStore.content.contains(\"took a screenshot\"))\n \n if isActionMessage {\n // Convert to system message\n messageToStore = BitchatMessage(\n id: messageToStore.id,\n sender: \"system\",\n content: String(messageToStore.content.dropFirst(2).dropLast(2)), // Remove * * wrapper\n timestamp: messageToStore.timestamp,\n isRelay: messageToStore.isRelay,\n originalSender: messageToStore.originalSender,\n isPrivate: messageToStore.isPrivate,\n recipientNickname: messageToStore.recipientNickname,\n senderPeerID: messageToStore.senderPeerID,\n mentions: messageToStore.mentions,\n deliveryStatus: messageToStore.deliveryStatus\n )\n }\n \n // Use batching for private messages\n addPrivateMessageToBatch(messageToStore, for: peerID)\n \n // Debug logging\n \n // Check if we're in a private chat with this peer's fingerprint\n // This handles reconnections with new peer IDs\n if let chatFingerprint = selectedPrivateChatFingerprint,\n let senderFingerprint = peerIDToPublicKeyFingerprint[peerID],\n chatFingerprint == senderFingerprint && selectedPrivateChatPeer != peerID {\n // Update our private chat peer to the new ID\n selectedPrivateChatPeer = peerID\n }\n \n // Mark as unread if not currently viewing this chat\n if selectedPrivateChatPeer != peerID {\n unreadPrivateMessages.insert(peerID)\n \n } else {\n // We're viewing this chat, make sure unread is cleared\n unreadPrivateMessages.remove(peerID)\n \n // Send read receipt immediately since we're viewing the chat\n // Send to the current peer ID since peer IDs change between sessions\n if !sentReadReceipts.contains(message.id) {\n let receipt = ReadReceipt(\n originalMessageID: message.id,\n readerID: meshService.myPeerID,\n readerNickname: nickname\n )\n meshService.sendReadReceipt(receipt, to: peerID)\n sentReadReceipts.insert(message.id)\n }\n \n // Also check if there are other unread messages from this peer\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in\n self?.markPrivateMessagesAsRead(from: peerID)\n }\n }\n } else if message.sender == nickname {\n // Our own message that was echoed back - ignore it since we already added it locally\n }\n } else {\n // Regular public message (main chat)\n \n // Check if this is an action that should be converted to system message\n let isActionMessage = message.content.hasPrefix(\"* \") && message.content.hasSuffix(\" *\") &&\n (message.content.contains(\"🫂\") || message.content.contains(\"🐟\") || \n message.content.contains(\"took a screenshot\"))\n \n let finalMessage: BitchatMessage\n if isActionMessage {\n // Convert to system message\n finalMessage = BitchatMessage(\n sender: \"system\",\n content: String(message.content.dropFirst(2).dropLast(2)), // Remove * * wrapper\n timestamp: message.timestamp,\n isRelay: message.isRelay,\n originalSender: message.originalSender,\n isPrivate: false,\n recipientNickname: message.recipientNickname,\n senderPeerID: message.senderPeerID,\n mentions: message.mentions\n )\n } else {\n finalMessage = message\n }\n \n // Check if this is our own message being echoed back\n if finalMessage.sender != nickname && finalMessage.sender != \"system\" {\n // Skip empty or whitespace-only messages\n if !finalMessage.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {\n addMessageToBatch(finalMessage)\n }\n } else if finalMessage.sender != \"system\" {\n // Our own message - check if we already have it (by ID and content)\n let messageExists = messages.contains { existingMsg in\n // Check by ID first\n if existingMsg.id == finalMessage.id {\n return true\n }\n // Check by content and sender with time window (within 1 second)\n if existingMsg.content == finalMessage.content && \n existingMsg.sender == finalMessage.sender {\n let timeDiff = abs(existingMsg.timestamp.timeIntervalSince(finalMessage.timestamp))\n return timeDiff < 1.0\n }\n return false\n }\n if !messageExists {\n // This is a message we sent from another device or it's missing locally\n // Skip empty or whitespace-only messages\n if !finalMessage.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {\n addMessageToBatch(finalMessage)\n }\n }\n } else {\n // System message - check for empty content before adding\n if !finalMessage.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {\n addMessageToBatch(finalMessage)\n }\n }\n }\n \n // Check if we're mentioned\n let isMentioned = message.mentions?.contains(nickname) ?? false\n \n // Send notifications for mentions and private messages when app is in background\n if isMentioned && message.sender != nickname {\n NotificationService.shared.sendMentionNotification(from: message.sender, message: message.content)\n } else if message.isPrivate && message.sender != nickname {\n // Only send notification if the private chat is not currently open\n if selectedPrivateChatPeer != message.senderPeerID {\n NotificationService.shared.sendPrivateMessageNotification(from: message.sender, message: message.content, peerID: message.senderPeerID ?? \"\")\n }\n }\n \n #if os(iOS)\n // Haptic feedback for iOS only\n guard UIApplication.shared.applicationState == .active else {\n return\n }\n // Check if this is a hug message directed at the user\n let isHugForMe = message.content.contains(\"🫂\") && \n (message.content.contains(\"hugs \\(nickname)\") ||\n message.content.contains(\"hugs you\"))\n \n // Check if this is a slap message directed at the user\n let isSlapForMe = message.content.contains(\"🐟\") && \n (message.content.contains(\"slaps \\(nickname) around\") ||\n message.content.contains(\"slaps you around\"))\n \n if isHugForMe && message.sender != nickname {\n // Long warm haptic for hugs - continuous gentle vibration\n let impactFeedback = UIImpactFeedbackGenerator(style: .medium)\n impactFeedback.prepare()\n \n // Create a warm, sustained haptic pattern\n for i in 0..<8 {\n DispatchQueue.main.asyncAfter(deadline: .now() + Double(i) * 0.15) {\n impactFeedback.impactOccurred()\n }\n }\n \n // Add a final stronger pulse\n DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {\n let strongFeedback = UIImpactFeedbackGenerator(style: .heavy)\n strongFeedback.prepare()\n strongFeedback.impactOccurred()\n }\n } else if isSlapForMe && message.sender != nickname {\n // Very harsh, fast, strong haptic for slaps - multiple sharp impacts\n let impactFeedback = UIImpactFeedbackGenerator(style: .heavy)\n impactFeedback.prepare()\n \n // Rapid-fire heavy impacts to simulate a hard slap\n impactFeedback.impactOccurred()\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) {\n impactFeedback.impactOccurred()\n }\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.06) {\n impactFeedback.impactOccurred()\n }\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.09) {\n impactFeedback.impactOccurred()\n }\n \n // Final extra heavy impact\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {\n let finalImpact = UIImpactFeedbackGenerator(style: .heavy)\n finalImpact.prepare()\n finalImpact.impactOccurred()\n }\n } else if isMentioned && message.sender != nickname {\n // Very prominent haptic for @mentions - triple tap with heavy impact\n let impactFeedback = UIImpactFeedbackGenerator(style: .heavy)\n impactFeedback.prepare()\n impactFeedback.impactOccurred()\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {\n impactFeedback.impactOccurred()\n }\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {\n impactFeedback.impactOccurred()\n }\n } else if message.isPrivate && message.sender != nickname {\n // Heavy haptic for private messages - more pronounced\n let impactFeedback = UIImpactFeedbackGenerator(style: .heavy)\n impactFeedback.prepare()\n impactFeedback.impactOccurred()\n \n // Double tap for extra emphasis\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {\n impactFeedback.impactOccurred()\n }\n } else if message.sender != nickname {\n // Light haptic for public messages from others\n let impactFeedback = UIImpactFeedbackGenerator(style: .light)\n impactFeedback.impactOccurred()\n }\n #endif\n }\n \n // MARK: - Peer Connection Events\n \n func didConnectToPeer(_ peerID: String) {\n isConnected = true\n \n // Register ephemeral session with identity manager\n SecureIdentityStateManager.shared.registerEphemeralSession(peerID: peerID)\n \n // Resolve nickname using helper\n let displayName = resolveNickname(for: peerID)\n \n // Ensure we have a valid display name\n let finalDisplayName = displayName.isEmpty ? \"peer\" : displayName\n \n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"\\(finalDisplayName) connected\",\n timestamp: Date(),\n isRelay: false,\n originalSender: nil\n )\n // Batch system messages\n addMessageToBatch(systemMessage)\n }\n \n func didDisconnectFromPeer(_ peerID: String) {\n // Remove ephemeral session from identity manager\n SecureIdentityStateManager.shared.removeEphemeralSession(peerID: peerID)\n \n // Clear sent read receipts for this peer since they'll need to be resent after reconnection\n // Only clear receipts for messages from this specific peer\n if let messages = privateChats[peerID] {\n for message in messages {\n // Remove read receipts for messages FROM this peer (not TO this peer)\n if message.senderPeerID == peerID {\n sentReadReceipts.remove(message.id)\n }\n }\n }\n \n // Resolve nickname using helper\n let displayName = resolveNickname(for: peerID)\n \n // Ensure we have a valid display name\n let finalDisplayName = displayName.isEmpty ? \"peer\" : displayName\n \n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"\\(finalDisplayName) disconnected\",\n timestamp: Date(),\n isRelay: false,\n originalSender: nil\n )\n // Batch system messages\n addMessageToBatch(systemMessage)\n }\n \n func didUpdatePeerList(_ peers: [String]) {\n // UI updates must run on the main thread.\n // The delegate callback is not guaranteed to be on the main thread.\n DispatchQueue.main.async {\n self.connectedPeers = peers\n self.isConnected = !peers.isEmpty\n \n // Register ephemeral sessions for all connected peers\n for peerID in peers {\n SecureIdentityStateManager.shared.registerEphemeralSession(peerID: peerID)\n }\n \n // Update encryption status for all peers\n self.updateEncryptionStatusForPeers()\n \n // Invalidate RSSI cache since peer data may have changed\n self.invalidateRSSIColorCache()\n\n // Explicitly notify SwiftUI that the object has changed.\n self.objectWillChange.send()\n \n // Check if we need to update private chat peer after reconnection\n if self.selectedPrivateChatFingerprint != nil {\n self.updatePrivateChatPeerIfNeeded()\n }\n \n // Only end private chat if we can't find the peer by fingerprint\n if let currentChatPeer = self.selectedPrivateChatPeer,\n !peers.contains(currentChatPeer),\n self.selectedPrivateChatFingerprint != nil {\n // Try one more time to find by fingerprint\n if self.getCurrentPeerIDForFingerprint(self.selectedPrivateChatFingerprint!) == nil {\n self.endPrivateChat()\n }\n }\n }\n }\n \n // MARK: - Helper Methods\n \n private func parseMentions(from content: String) -> [String] {\n let pattern = \"@([a-zA-Z0-9_]+)\"\n let regex = try? NSRegularExpression(pattern: pattern, options: [])\n let matches = regex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n \n var mentions: [String] = []\n let peerNicknames = meshService.getPeerNicknames()\n let allNicknames = Set(peerNicknames.values).union([nickname]) // Include self\n \n for match in matches {\n if let range = Range(match.range(at: 1), in: content) {\n let mentionedName = String(content[range])\n // Only include if it's a valid nickname\n if allNicknames.contains(mentionedName) {\n mentions.append(mentionedName)\n }\n }\n }\n \n return Array(Set(mentions)) // Remove duplicates\n }\n \n func isFavorite(fingerprint: String) -> Bool {\n return SecureIdentityStateManager.shared.isFavorite(fingerprint: fingerprint)\n }\n \n // MARK: - Delivery Tracking\n \n func didReceiveDeliveryAck(_ ack: DeliveryAck) {\n // Find the message and update its delivery status\n updateMessageDeliveryStatus(ack.originalMessageID, status: .delivered(to: ack.recipientNickname, at: ack.timestamp))\n }\n \n func didReceiveReadReceipt(_ receipt: ReadReceipt) {\n // Find the message and update its read status\n updateMessageDeliveryStatus(receipt.originalMessageID, status: .read(by: receipt.readerNickname, at: receipt.timestamp))\n \n // Clear delivery tracking since the message has been read\n // This prevents the timeout from marking it as failed\n DeliveryTracker.shared.clearDeliveryStatus(for: receipt.originalMessageID)\n }\n \n func didUpdateMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) {\n updateMessageDeliveryStatus(messageID, status: status)\n }\n \n private func updateMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) {\n SecureLogger.log(\"Updating UI delivery status for message \\(messageID): \\(status)\", category: SecureLogger.session, level: .debug)\n \n // Helper function to check if we should skip this update\n func shouldSkipUpdate(currentStatus: DeliveryStatus?, newStatus: DeliveryStatus) -> Bool {\n guard let current = currentStatus else { return false }\n \n // Don't downgrade from read to delivered\n switch (current, newStatus) {\n case (.read, .delivered):\n return true\n case (.read, .sent):\n return true\n default:\n return false\n }\n }\n \n // Update in main messages\n if let index = messages.firstIndex(where: { $0.id == messageID }) {\n let currentStatus = messages[index].deliveryStatus\n if !shouldSkipUpdate(currentStatus: currentStatus, newStatus: status) {\n messages[index].deliveryStatus = status\n }\n }\n \n // Update in private chats\n var updatedPrivateChats = privateChats\n for (peerID, chatMessages) in updatedPrivateChats {\n if let index = chatMessages.firstIndex(where: { $0.id == messageID }) {\n let currentStatus = chatMessages[index].deliveryStatus\n if !shouldSkipUpdate(currentStatus: currentStatus, newStatus: status) {\n chatMessages[index].deliveryStatus = status\n updatedPrivateChats[peerID] = chatMessages\n }\n }\n }\n \n // Force complete reassignment to trigger SwiftUI update\n DispatchQueue.main.async { [weak self] in\n guard let self = self else { return }\n self.privateChats = updatedPrivateChats\n self.objectWillChange.send()\n }\n \n }\n \n \n}\n"], ["/bitchat/bitchat/Services/BluetoothMeshService.swift", "//\n// BluetoothMeshService.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # BluetoothMeshService\n///\n/// The core networking component that manages peer-to-peer Bluetooth LE connections\n/// and implements the BitChat mesh networking protocol.\n///\n/// ## Overview\n/// This service is the heart of BitChat's decentralized architecture. It manages all\n/// Bluetooth LE communications, enabling devices to form an ad-hoc mesh network without\n/// any infrastructure. The service handles:\n/// - Peer discovery and connection management\n/// - Message routing and relay functionality\n/// - Protocol version negotiation\n/// - Connection state tracking and recovery\n/// - Integration with the Noise encryption layer\n///\n/// ## Architecture\n/// The service operates in a dual mode:\n/// - **Central Mode**: Scans for and connects to other BitChat devices\n/// - **Peripheral Mode**: Advertises its presence and accepts connections\n///\n/// This dual-mode operation enables true peer-to-peer connectivity where any device\n/// can initiate or accept connections, forming a resilient mesh topology.\n///\n/// ## Mesh Networking\n/// Messages are relayed through the mesh using a TTL (Time To Live) mechanism:\n/// - Each message has a TTL that decrements at each hop\n/// - Messages are cached to prevent loops (via Bloom filters)\n/// - Store-and-forward ensures delivery to temporarily offline peers\n///\n/// ## Connection Lifecycle\n/// 1. **Discovery**: Devices scan and advertise simultaneously\n/// 2. **Connection**: BLE connection established\n/// 3. **Version Negotiation**: Ensure protocol compatibility\n/// 4. **Authentication**: Noise handshake for encrypted channels\n/// 5. **Message Exchange**: Bidirectional communication\n/// 6. **Disconnection**: Graceful cleanup and state preservation\n///\n/// ## Security Integration\n/// - Coordinates with NoiseEncryptionService for private messages\n/// - Maintains peer identity mappings\n/// - Handles lazy handshake initiation\n/// - Ensures message authenticity\n///\n/// ## Performance Optimizations\n/// - Connection pooling and reuse\n/// - Adaptive scanning based on battery level\n/// - Message batching for efficiency\n/// - Smart retry logic with exponential backoff\n///\n/// ## Thread Safety\n/// All public methods are thread-safe. The service uses:\n/// - Serial queues for Core Bluetooth operations\n/// - Thread-safe collections for peer management\n/// - Atomic operations for state updates\n///\n/// ## Error Handling\n/// - Automatic reconnection for lost connections\n/// - Graceful degradation when Bluetooth is unavailable\n/// - Clear error reporting through BitchatDelegate\n///\n/// ## Usage Example\n/// ```swift\n/// let meshService = BluetoothMeshService()\n/// meshService.delegate = self\n/// meshService.localUserID = \"user123\"\n/// meshService.startMeshService()\n/// ```\n///\n\nimport Foundation\nimport CoreBluetooth\nimport Combine\nimport CryptoKit\nimport os.log\n#if os(macOS)\nimport AppKit\nimport IOKit.ps\n#else\nimport UIKit\n#endif\n\n// Hex encoding/decoding is now in BinaryEncodingUtils.swift\n\n// Extension for TimeInterval to Data conversion\nextension TimeInterval {\n var data: Data {\n var value = self\n return Data(bytes: &value, count: MemoryLayout.size)\n }\n}\n\n// Version negotiation state\nenum VersionNegotiationState {\n case none\n case helloSent\n case ackReceived(version: UInt8)\n case failed(reason: String)\n}\n\n// Peer connection state tracking\nenum PeerConnectionState: CustomStringConvertible {\n case disconnected\n case connecting\n case connected // BLE connected but not authenticated\n case authenticating // Performing handshake\n case authenticated // Handshake complete, ready for messages\n \n var isAvailable: Bool {\n switch self {\n case .authenticated:\n return true\n default:\n return false\n }\n }\n \n var description: String {\n switch self {\n case .disconnected: return \"disconnected\"\n case .connecting: return \"connecting\"\n case .connected: return \"connected\"\n case .authenticating: return \"authenticating\"\n case .authenticated: return \"authenticated\"\n }\n }\n}\n\n/// Manages all Bluetooth LE networking operations for the BitChat mesh network.\n/// This class handles peer discovery, connection management, message routing,\n/// and protocol negotiation. It acts as both a BLE central (scanner) and\n/// peripheral (advertiser) simultaneously to enable true peer-to-peer connectivity.\nclass BluetoothMeshService: NSObject {\n // MARK: - Constants\n \n static let serviceUUID = CBUUID(string: \"F47B5E2D-4A9E-4C5A-9B3F-8E1D2C3A4B5C\")\n static let characteristicUUID = CBUUID(string: \"A1B2C3D4-E5F6-4A5B-8C9D-0E1F2A3B4C5D\")\n \n // MARK: - Core Bluetooth Properties\n \n private var centralManager: CBCentralManager?\n private var peripheralManager: CBPeripheralManager?\n private var discoveredPeripherals: [CBPeripheral] = []\n private var connectedPeripherals: [String: CBPeripheral] = [:]\n private var peripheralCharacteristics: [CBPeripheral: CBCharacteristic] = [:]\n \n // MARK: - Connection Tracking\n \n private var lastConnectionTime: [String: Date] = [:] // Track when peers last connected\n private var lastSuccessfulMessageTime: [String: Date] = [:] // Track last successful message exchange\n private var lastHeardFromPeer: [String: Date] = [:] // Track last time we received ANY packet from peer\n \n // MARK: - Peer Availability\n \n // Peer availability tracking\n private var peerAvailabilityState: [String: Bool] = [:] // true = available, false = unavailable\n private let peerAvailabilityTimeout: TimeInterval = 30.0 // Mark unavailable after 30s of no response\n private var availabilityCheckTimer: Timer?\n \n // MARK: - Peripheral Management\n \n private var characteristic: CBMutableCharacteristic?\n private var subscribedCentrals: [CBCentral] = []\n \n // MARK: - Thread-Safe Collections\n \n private let collectionsQueue = DispatchQueue(label: \"bitchat.collections\", attributes: .concurrent)\n private var peerNicknames: [String: String] = [:]\n private var activePeers: Set = [] // Track all active peers\n private var peerRSSI: [String: NSNumber] = [:] // Track RSSI values for peers\n private var peripheralRSSI: [String: NSNumber] = [:] // Track RSSI by peripheral ID during discovery\n private var rssiRetryCount: [String: Int] = [:] // Track RSSI retry attempts per peripheral\n \n // MARK: - Encryption Queues\n \n // Per-peer encryption queues to prevent nonce desynchronization\n private var peerEncryptionQueues: [String: DispatchQueue] = [:]\n private let encryptionQueuesLock = NSLock()\n \n // MARK: - Peer Identity Rotation\n // Mappings between ephemeral peer IDs and permanent fingerprints\n private var peerIDToFingerprint: [String: String] = [:] // PeerID -> Fingerprint\n private var fingerprintToPeerID: [String: String] = [:] // Fingerprint -> Current PeerID\n private var peerIdentityBindings: [String: PeerIdentityBinding] = [:] // Fingerprint -> Full binding\n private var previousPeerID: String? // Our previous peer ID for grace period\n private var rotationTimestamp: Date? // When we last rotated\n private let rotationGracePeriod: TimeInterval = 60.0 // 1 minute grace period\n private var rotationLocked = false // Prevent rotation during critical operations\n private var rotationTimer: Timer? // Timer for scheduled rotations\n \n // MARK: - Identity Cache\n // In-memory cache for peer public keys to avoid keychain lookups\n private var peerPublicKeyCache: [String: Data] = [:] // PeerID -> Public Key Data\n private var peerSigningKeyCache: [String: Data] = [:] // PeerID -> Signing Key Data\n private let identityCacheTTL: TimeInterval = 3600.0 // 1 hour TTL\n private var identityCacheTimestamps: [String: Date] = [:] // Track when entries were cached\n \n // MARK: - Delegates and Services\n \n weak var delegate: BitchatDelegate?\n private let noiseService = NoiseEncryptionService()\n private let handshakeCoordinator = NoiseHandshakeCoordinator()\n \n // MARK: - Protocol Version Negotiation\n \n // Protocol version negotiation state\n private var versionNegotiationState: [String: VersionNegotiationState] = [:]\n private var negotiatedVersions: [String: UInt8] = [:] // peerID -> agreed version\n \n // MARK: - Write Queue for Disconnected Peripherals\n private struct QueuedWrite {\n let data: Data\n let peripheralID: String\n let peerID: String?\n let timestamp: Date\n let retryCount: Int\n }\n \n private var writeQueue: [String: [QueuedWrite]] = [:] // PeripheralID -> Queue of writes\n private let writeQueueLock = NSLock()\n private let maxWriteQueueSize = 50 // Max queued writes per peripheral\n private let maxWriteRetries = 3\n private let writeQueueTTL: TimeInterval = 60.0 // Expire queued writes after 1 minute\n private var writeQueueTimer: Timer? // Timer for processing expired writes\n \n // MARK: - Connection Pooling\n private let maxConnectedPeripherals = 10 // Limit simultaneous connections\n private let maxScanningDuration: TimeInterval = 5.0 // Stop scanning after 5 seconds to save battery\n \n func getNoiseService() -> NoiseEncryptionService {\n return noiseService\n }\n \n \n private func cleanExpiredIdentityCache() {\n collectionsQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n let now = Date()\n var expiredPeerIDs: [String] = []\n \n for (peerID, timestamp) in self.identityCacheTimestamps {\n if now.timeIntervalSince(timestamp) >= self.identityCacheTTL {\n expiredPeerIDs.append(peerID)\n }\n }\n \n for peerID in expiredPeerIDs {\n self.peerPublicKeyCache.removeValue(forKey: peerID)\n self.peerSigningKeyCache.removeValue(forKey: peerID)\n self.identityCacheTimestamps.removeValue(forKey: peerID)\n }\n \n if !expiredPeerIDs.isEmpty {\n SecureLogger.log(\"Cleaned \\(expiredPeerIDs.count) expired identity cache entries\", \n category: SecureLogger.session, level: .debug)\n }\n }\n }\n \n // MARK: - Write Queue Management\n \n private func writeToPeripheral(_ data: Data, peripheral: CBPeripheral, characteristic: CBCharacteristic, peerID: String? = nil) {\n let peripheralID = peripheral.identifier.uuidString\n \n // Double check the peripheral state to avoid API misuse\n guard peripheral.state == .connected else {\n // Queue write for disconnected peripheral\n queueWrite(data: data, peripheralID: peripheralID, peerID: peerID)\n return\n }\n \n // Verify characteristic is valid and writable\n guard characteristic.properties.contains(.write) || characteristic.properties.contains(.writeWithoutResponse) else {\n SecureLogger.log(\"Characteristic does not support writing for peripheral \\(peripheralID)\", \n category: SecureLogger.session, level: .warning)\n return\n }\n \n // Direct write if connected\n let writeType: CBCharacteristicWriteType = data.count > 512 ? .withResponse : .withoutResponse\n peripheral.writeValue(data, for: characteristic, type: writeType)\n \n // Update activity tracking\n updatePeripheralActivity(peripheralID)\n }\n \n private func queueWrite(data: Data, peripheralID: String, peerID: String?) {\n writeQueueLock.lock()\n defer { writeQueueLock.unlock() }\n \n // Check backpressure - drop oldest if queue is full\n var queue = writeQueue[peripheralID] ?? []\n \n if queue.count >= maxWriteQueueSize {\n // Remove oldest entries\n let removeCount = queue.count - maxWriteQueueSize + 1\n queue.removeFirst(removeCount)\n SecureLogger.log(\"Write queue full for \\(peripheralID), dropped \\(removeCount) oldest writes\", \n category: SecureLogger.session, level: .warning)\n }\n \n let queuedWrite = QueuedWrite(\n data: data,\n peripheralID: peripheralID,\n peerID: peerID,\n timestamp: Date(),\n retryCount: 0\n )\n \n queue.append(queuedWrite)\n writeQueue[peripheralID] = queue\n \n SecureLogger.log(\"Queued write for disconnected peripheral \\(peripheralID), queue size: \\(queue.count)\", \n category: SecureLogger.session, level: .debug)\n }\n \n private func processWriteQueue(for peripheral: CBPeripheral) {\n guard peripheral.state == .connected,\n let characteristic = peripheralCharacteristics[peripheral] else { return }\n \n let peripheralID = peripheral.identifier.uuidString\n \n writeQueueLock.lock()\n let queue = writeQueue[peripheralID] ?? []\n writeQueue[peripheralID] = []\n writeQueueLock.unlock()\n \n if !queue.isEmpty {\n SecureLogger.log(\"Processing \\(queue.count) queued writes for \\(peripheralID)\", \n category: SecureLogger.session, level: .info)\n }\n \n // Process queued writes with small delay between them\n for (index, queuedWrite) in queue.enumerated() {\n DispatchQueue.main.asyncAfter(deadline: .now() + Double(index) * 0.01) { [weak self] in\n guard let self = self,\n peripheral.state == .connected,\n characteristic.properties.contains(.write) || characteristic.properties.contains(.writeWithoutResponse) else { \n return \n }\n \n let writeType: CBCharacteristicWriteType = queuedWrite.data.count > 512 ? .withResponse : .withoutResponse\n peripheral.writeValue(queuedWrite.data, for: characteristic, type: writeType)\n \n // Update activity tracking\n self.updatePeripheralActivity(peripheralID)\n }\n }\n }\n \n private func cleanExpiredWriteQueues() {\n writeQueueLock.lock()\n defer { writeQueueLock.unlock() }\n \n let now = Date()\n var expiredWrites = 0\n \n for (peripheralID, queue) in writeQueue {\n let filteredQueue = queue.filter { write in\n now.timeIntervalSince(write.timestamp) < writeQueueTTL\n }\n \n expiredWrites += queue.count - filteredQueue.count\n \n if filteredQueue.isEmpty {\n writeQueue.removeValue(forKey: peripheralID)\n } else {\n writeQueue[peripheralID] = filteredQueue\n }\n }\n \n if expiredWrites > 0 {\n SecureLogger.log(\"Cleaned \\(expiredWrites) expired queued writes\", \n category: SecureLogger.session, level: .debug)\n }\n }\n // MARK: - Message Processing\n \n private let messageQueue = DispatchQueue(label: \"bitchat.messageQueue\", attributes: .concurrent) // Concurrent queue with barriers\n \n // Message state tracking for better duplicate detection\n private struct MessageState {\n let firstSeen: Date\n var lastSeen: Date\n var seenCount: Int\n var relayed: Bool\n var acknowledged: Bool\n \n mutating func updateSeen() {\n lastSeen = Date()\n seenCount += 1\n }\n }\n \n private var processedMessages = [String: MessageState]() // Track full message state\n private let processedMessagesLock = NSLock()\n private let maxProcessedMessages = 10000\n \n // Special handling for identity announces to prevent duplicates\n private var recentIdentityAnnounces = [String: Date]() // peerID -> last seen time\n private let identityAnnounceDuplicateWindow: TimeInterval = 30.0 // 30 second window\n \n // MARK: - Network State Management\n \n private let maxTTL: UInt8 = 7 // Maximum hops for long-distance delivery\n private var announcedToPeers = Set() // Track which peers we've announced to\n private var announcedPeers = Set() // Track peers who have already been announced\n private var hasNotifiedNetworkAvailable = false // Track if we've notified about network availability\n private var lastNetworkNotificationTime: Date? // Track when we last sent a network notification\n private var networkBecameEmptyTime: Date? // Track when the network became empty\n private let networkNotificationCooldown: TimeInterval = 300 // 5 minutes between notifications\n private let networkEmptyResetDelay: TimeInterval = 60 // 1 minute before resetting notification flag\n private var intentionalDisconnects = Set() // Track peripherals we're disconnecting intentionally\n private var gracefullyLeftPeers = Set() // Track peers that sent leave messages\n private var gracefulLeaveTimestamps: [String: Date] = [:] // Track when peers left\n private let gracefulLeaveExpirationTime: TimeInterval = 300.0 // 5 minutes\n private var peerLastSeenTimestamps = LRUCache(maxSize: 100) // Bounded cache for peer timestamps\n private var cleanupTimer: Timer? // Timer to clean up stale peers\n \n // MARK: - Store-and-Forward Cache\n \n // Store-and-forward message cache\n private struct StoredMessage {\n let packet: BitchatPacket\n let timestamp: Date\n let messageID: String\n let isForFavorite: Bool // Messages for favorites stored indefinitely\n }\n private var messageCache: [StoredMessage] = []\n private let messageCacheTimeout: TimeInterval = 43200 // 12 hours for regular peers\n private let maxCachedMessages = 100 // For regular peers\n private let maxCachedMessagesForFavorites = 1000 // Much larger cache for favorites\n private var favoriteMessageQueue: [String: [StoredMessage]] = [:] // Per-favorite message queues\n private let deliveredMessages = BoundedSet(maxSize: 5000) // Bounded to prevent memory growth\n private var cachedMessagesSentToPeer = Set() // Track which peers have already received cached messages\n private let receivedMessageTimestamps = LRUCache(maxSize: 1000) // Bounded cache\n private let recentlySentMessages = BoundedSet(maxSize: 500) // Short-term bounded cache\n private let lastMessageFromPeer = LRUCache(maxSize: 100) // Bounded cache\n private let processedNoiseMessages = BoundedSet(maxSize: 1000) // Bounded cache\n \n // MARK: - Battery and Performance Optimization\n \n // Battery and range optimizations\n private var scanDutyCycleTimer: Timer?\n private var isActivelyScanning = true\n private var activeScanDuration: TimeInterval = 5.0 // will be adjusted based on battery\n private var scanPauseDuration: TimeInterval = 10.0 // will be adjusted based on battery\n private var lastRSSIUpdate: [String: Date] = [:] // Throttle RSSI updates\n private var batteryMonitorTimer: Timer?\n private var currentBatteryLevel: Float = 1.0 // Default to full battery\n \n // Battery optimizer integration\n private let batteryOptimizer = BatteryOptimizer.shared\n private var batteryOptimizerCancellables = Set()\n \n // Peer list update debouncing\n private var peerListUpdateTimer: Timer?\n private let peerListUpdateDebounceInterval: TimeInterval = 0.1 // 100ms debounce for more responsive updates\n \n // Track when we last sent identity announcements to prevent flooding\n private var lastIdentityAnnounceTimes: [String: Date] = [:]\n private let identityAnnounceMinInterval: TimeInterval = 10.0 // Minimum 10 seconds between announcements per peer\n \n // Track handshake attempts to handle timeouts\n private var handshakeAttemptTimes: [String: Date] = [:]\n private let handshakeTimeout: TimeInterval = 5.0 // 5 seconds before retrying\n \n // Pending private messages waiting for handshake\n private var pendingPrivateMessages: [String: [(content: String, recipientNickname: String, messageID: String)]] = [:]\n \n // MARK: - Noise Protocol State\n \n // Noise session state tracking for lazy handshakes\n private var noiseSessionStates: [String: LazyHandshakeState] = [:]\n \n // MARK: - Cover Traffic\n \n // Cover traffic for privacy\n private var coverTrafficTimer: Timer?\n private let coverTrafficPrefix = \"☂DUMMY☂\" // Prefix to identify dummy messages after decryption\n private var lastCoverTrafficTime = Date()\n \n // MARK: - Connection State\n \n // Connection state tracking\n private var peerConnectionStates: [String: PeerConnectionState] = [:]\n private let connectionStateQueue = DispatchQueue(label: \"chat.bitchat.connectionState\", attributes: .concurrent)\n \n // MARK: - Protocol ACK Tracking\n \n // Protocol-level ACK tracking\n private var pendingAcks: [String: (packet: BitchatPacket, timestamp: Date, retries: Int)] = [:]\n private let ackTimeout: TimeInterval = 5.0 // 5 seconds to receive ACK\n private let maxAckRetries = 3\n private var ackTimer: Timer?\n private var advertisingTimer: Timer? // Timer for interval-based advertising\n private var connectionKeepAliveTimer: Timer? // Timer to send keepalive pings\n private let keepAliveInterval: TimeInterval = 20.0 // Send keepalive every 20 seconds\n \n // MARK: - Timing and Delays\n \n // Timing randomization for privacy (now with exponential distribution)\n private let minMessageDelay: TimeInterval = 0.01 // 10ms minimum for faster sync\n private let maxMessageDelay: TimeInterval = 0.1 // 100ms maximum for faster sync\n \n // MARK: - RSSI Management\n \n // Dynamic RSSI threshold based on network size (smart compromise)\n private var dynamicRSSIThreshold: Int {\n let peerCount = activePeers.count\n if peerCount < 5 {\n return -95 // Maximum range when network is small\n } else if peerCount < 10 {\n return -92 // Slightly reduced range\n } else {\n return -90 // Conservative for larger networks\n }\n }\n \n // MARK: - Fragment Handling\n \n // Fragment handling with security limits\n private var incomingFragments: [String: [Int: Data]] = [:] // fragmentID -> [index: data]\n private var fragmentMetadata: [String: (originalType: UInt8, totalFragments: Int, timestamp: Date)] = [:]\n private let maxFragmentSize = 469 // 512 bytes max MTU - 43 bytes for headers and metadata\n private let maxConcurrentFragmentSessions = 20 // Limit concurrent fragment sessions to prevent DoS\n private let fragmentTimeout: TimeInterval = 30 // 30 seconds timeout for incomplete fragments\n \n // MARK: - Peer Identity\n \n var myPeerID: String\n \n // MARK: - Scaling Optimizations\n \n // Connection pooling\n private var connectionPool: [String: CBPeripheral] = [:]\n private var connectionAttempts: [String: Int] = [:]\n private var connectionBackoff: [String: TimeInterval] = [:]\n private var lastActivityByPeripheralID: [String: Date] = [:] // Track last activity for LRU\n private var peerIDByPeripheralID: [String: String] = [:] // Map peripheral ID to peer ID\n private let maxConnectionAttempts = 3\n private let baseBackoffInterval: TimeInterval = 1.0\n \n // MARK: - Peripheral Mapping\n \n // Simplified peripheral mapping system\n private struct PeripheralMapping {\n let peripheral: CBPeripheral\n var peerID: String? // nil until we receive announce\n var rssi: NSNumber?\n var lastActivity: Date\n \n var isIdentified: Bool { peerID != nil }\n }\n private var peripheralMappings: [String: PeripheralMapping] = [:] // peripheralID -> mapping\n \n // Helper methods for peripheral mapping\n private func registerPeripheral(_ peripheral: CBPeripheral) {\n let peripheralID = peripheral.identifier.uuidString\n peripheralMappings[peripheralID] = PeripheralMapping(\n peripheral: peripheral,\n peerID: nil,\n rssi: nil,\n lastActivity: Date()\n )\n }\n \n private func updatePeripheralMapping(peripheralID: String, peerID: String) {\n guard var mapping = peripheralMappings[peripheralID] else { return }\n \n // Remove old temp mapping if it exists\n let tempID = peripheralID\n if connectedPeripherals[tempID] != nil {\n connectedPeripherals.removeValue(forKey: tempID)\n }\n \n mapping.peerID = peerID\n mapping.lastActivity = Date()\n peripheralMappings[peripheralID] = mapping\n \n // Update legacy mappings\n peerIDByPeripheralID[peripheralID] = peerID\n connectedPeripherals[peerID] = mapping.peripheral\n \n // Transfer RSSI\n if let rssi = mapping.rssi {\n peerRSSI[peerID] = rssi\n }\n }\n \n private func updatePeripheralRSSI(peripheralID: String, rssi: NSNumber) {\n guard var mapping = peripheralMappings[peripheralID] else { return }\n mapping.rssi = rssi\n mapping.lastActivity = Date()\n peripheralMappings[peripheralID] = mapping\n \n // Update peer RSSI if we have the peer ID\n if let peerID = mapping.peerID {\n peerRSSI[peerID] = rssi\n }\n }\n \n private func findPeripheralForPeerID(_ peerID: String) -> CBPeripheral? {\n for (_, mapping) in peripheralMappings {\n if mapping.peerID == peerID {\n return mapping.peripheral\n }\n }\n return nil\n }\n \n // MARK: - Probabilistic Flooding\n \n // Probabilistic flooding\n private var relayProbability: Double = 1.0 // Start at 100%, decrease with peer count\n private let minRelayProbability: Double = 0.4 // Minimum 40% relay chance - ensures coverage\n \n // MARK: - Message Aggregation\n \n // Message aggregation\n private var pendingMessages: [(message: BitchatPacket, destination: String?)] = []\n private var aggregationTimer: Timer?\n private var aggregationWindow: TimeInterval = 0.1 // 100ms window\n private let maxAggregatedMessages = 5\n \n // MARK: - Bloom Filter\n \n // Optimized Bloom filter for efficient duplicate detection\n private var messageBloomFilter = OptimizedBloomFilter(expectedItems: 2000, falsePositiveRate: 0.01)\n private var bloomFilterResetTimer: Timer?\n \n // MARK: - Network Size Estimation\n \n // Network size estimation\n private var estimatedNetworkSize: Int {\n return max(activePeers.count, connectedPeripherals.count)\n }\n \n // Adaptive parameters based on network size\n private var adaptiveTTL: UInt8 {\n // Keep TTL high enough for messages to travel far\n let networkSize = estimatedNetworkSize\n if networkSize <= 20 {\n return 6 // Small networks: max distance\n } else if networkSize <= 50 {\n return 5 // Medium networks: still good reach\n } else if networkSize <= 100 {\n return 4 // Large networks: reasonable reach\n } else {\n return 3 // Very large networks: minimum viable\n }\n }\n \n private var adaptiveRelayProbability: Double {\n // Adjust relay probability based on network size\n // Small networks don't need 100% relay - RSSI will handle edge nodes\n let networkSize = estimatedNetworkSize\n if networkSize <= 2 {\n return 0.0 // 0% for 2 nodes - no relay needed with only 2 peers\n } else if networkSize <= 5 {\n return 0.5 // 50% for very small networks\n } else if networkSize <= 10 {\n return 0.6 // 60% for small networks\n } else if networkSize <= 30 {\n return 0.7 // 70% for medium networks\n } else if networkSize <= 50 {\n return 0.6 // 60% for larger networks\n } else if networkSize <= 100 {\n return 0.5 // 50% for big networks\n } else {\n return 0.4 // 40% minimum for very large networks\n }\n }\n \n // MARK: - Relay Cancellation\n \n // Relay cancellation mechanism to prevent duplicate relays\n private var pendingRelays: [String: DispatchWorkItem] = [:] // messageID -> relay task\n private let pendingRelaysLock = NSLock()\n private let relayCancellationWindow: TimeInterval = 0.05 // 50ms window to detect other relays\n \n // MARK: - Memory Management\n \n // Global memory limits to prevent unbounded growth\n private let maxPendingPrivateMessages = 100\n private let maxCachedMessagesSentToPeer = 1000\n private let maxMemoryUsageBytes = 50 * 1024 * 1024 // 50MB limit\n private var memoryCleanupTimer: Timer?\n \n // Track acknowledged packets to prevent unnecessary retries\n private var acknowledgedPackets = Set()\n private let acknowledgedPacketsLock = NSLock()\n \n // MARK: - Rate Limiting\n \n // Rate limiting for flood control with separate limits for different message types\n private var messageRateLimiter: [String: [Date]] = [:] // peerID -> recent message timestamps\n private var protocolMessageRateLimiter: [String: [Date]] = [:] // peerID -> protocol msg timestamps\n private let rateLimiterLock = NSLock()\n private let rateLimitWindow: TimeInterval = 60.0 // 1 minute window\n private let maxChatMessagesPerPeerPerMinute = 300 // Allow fast typing (5 msgs/sec)\n private let maxProtocolMessagesPerPeerPerMinute = 100 // Protocol messages\n private let maxTotalMessagesPerMinute = 2000 // Increased for legitimate use\n private var totalMessageTimestamps: [Date] = []\n \n // MARK: - BLE Advertisement\n \n // BLE advertisement for lightweight presence\n private var advertisementData: [String: Any] = [:]\n private var isAdvertising = false\n \n // MARK: - Message Aggregation Implementation\n \n private func startAggregationTimer() {\n aggregationTimer?.invalidate()\n aggregationTimer = Timer.scheduledTimer(withTimeInterval: aggregationWindow, repeats: false) { [weak self] _ in\n self?.flushPendingMessages()\n }\n }\n \n private func flushPendingMessages() {\n guard !pendingMessages.isEmpty else { return }\n \n messageQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Group messages by destination\n var messagesByDestination: [String?: [BitchatPacket]] = [:]\n \n for (message, destination) in self.pendingMessages {\n if messagesByDestination[destination] == nil {\n messagesByDestination[destination] = []\n }\n messagesByDestination[destination]?.append(message)\n }\n \n // Send aggregated messages\n for (destination, messages) in messagesByDestination {\n if messages.count == 1 {\n // Single message, send normally\n if destination == nil {\n self.broadcastPacket(messages[0])\n } else if let dest = destination,\n let peripheral = self.connectedPeripherals[dest],\n let characteristic = self.peripheralCharacteristics[peripheral] {\n if let data = messages[0].toBinaryData() {\n self.writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: dest)\n }\n }\n } else {\n // Multiple messages - could aggregate into a single packet\n // For now, send with minimal delay between them\n for (index, message) in messages.enumerated() {\n let delay = Double(index) * 0.02 // 20ms between messages\n DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in\n if destination == nil {\n self?.broadcastPacket(message)\n } else if let dest = destination,\n let peripheral = self?.connectedPeripherals[dest],\n peripheral.state == .connected,\n let characteristic = self?.peripheralCharacteristics[peripheral] {\n if let data = message.toBinaryData() {\n self?.writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: dest)\n }\n }\n }\n }\n }\n }\n \n // Clear pending messages\n self.pendingMessages.removeAll()\n }\n }\n \n // Removed getPublicKeyFingerprint - no longer needed with Noise\n \n // MARK: - Peer Identity Mapping\n \n /// Retrieves the cryptographic fingerprint for a given peer.\n /// - Parameter peerID: The ephemeral peer ID\n /// - Returns: The peer's Noise static key fingerprint if known, nil otherwise\n /// - Note: This fingerprint remains stable across peer ID rotations\n func getPeerFingerprint(_ peerID: String) -> String? {\n return noiseService.getPeerFingerprint(peerID)\n }\n \n // Get fingerprint for a peer ID\n func getFingerprint(for peerID: String) -> String? {\n return collectionsQueue.sync {\n peerIDToFingerprint[peerID]\n }\n }\n \n /// Checks if a given peer ID belongs to the local device.\n /// - Parameter peerID: The peer ID to check\n /// - Returns: true if this is our current or recent peer ID, false otherwise\n /// - Note: Accounts for grace period during peer ID rotation\n func isPeerIDOurs(_ peerID: String) -> Bool {\n if peerID == myPeerID {\n return true\n }\n \n // Check if it's our previous ID within grace period\n if let previousID = previousPeerID,\n peerID == previousID,\n let rotationTime = rotationTimestamp,\n Date().timeIntervalSince(rotationTime) < rotationGracePeriod {\n return true\n }\n \n return false\n }\n \n /// Updates the identity binding for a peer when they rotate their ephemeral ID.\n /// - Parameters:\n /// - newPeerID: The peer's new ephemeral ID\n /// - fingerprint: The peer's stable cryptographic fingerprint\n /// - binding: The complete identity binding information\n /// - Note: This maintains continuity of identity across peer ID rotations\n func updatePeerBinding(_ newPeerID: String, fingerprint: String, binding: PeerIdentityBinding) {\n // Use async to ensure we're not blocking during view updates\n collectionsQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n var oldPeerID: String? = nil\n \n // Remove old peer ID mapping if exists\n if let existingPeerID = self.fingerprintToPeerID[fingerprint], existingPeerID != newPeerID {\n oldPeerID = existingPeerID\n SecureLogger.log(\"Peer ID rotation detected: \\(existingPeerID) -> \\(newPeerID) for fingerprint \\(fingerprint)\", category: SecureLogger.security, level: .info)\n \n // Transfer gracefullyLeftPeers state from old to new peer ID\n if self.gracefullyLeftPeers.contains(existingPeerID) {\n self.gracefullyLeftPeers.remove(existingPeerID)\n self.gracefullyLeftPeers.insert(newPeerID)\n SecureLogger.log(\"Transferred gracefullyLeft state from \\(existingPeerID) to \\(newPeerID)\", \n category: SecureLogger.session, level: .debug)\n }\n \n self.peerIDToFingerprint.removeValue(forKey: existingPeerID)\n \n // Transfer nickname if known\n if let nickname = self.peerNicknames[existingPeerID] {\n self.peerNicknames[newPeerID] = nickname\n self.peerNicknames.removeValue(forKey: existingPeerID)\n }\n \n // Update active peers set - always remove old peer ID\n self.activePeers.remove(existingPeerID)\n // Don't pre-insert the new peer ID - let the announce packet handle it\n // This ensures the connect message logic works properly\n \n // Transfer any connected peripherals\n if let peripheral = self.connectedPeripherals[existingPeerID] {\n self.connectedPeripherals.removeValue(forKey: existingPeerID)\n self.connectedPeripherals[newPeerID] = peripheral\n }\n \n // Transfer RSSI data\n if let rssi = self.peerRSSI[existingPeerID] {\n self.peerRSSI.removeValue(forKey: existingPeerID)\n self.peerRSSI[newPeerID] = rssi\n }\n \n // Transfer lastHeardFromPeer tracking\n if let lastHeard = self.lastHeardFromPeer[existingPeerID] {\n self.lastHeardFromPeer.removeValue(forKey: existingPeerID)\n self.lastHeardFromPeer[newPeerID] = lastHeard\n }\n \n // Clean up connection state for old peer ID\n self.peerConnectionStates.removeValue(forKey: existingPeerID)\n // Don't transfer connection state - let it be re-established naturally\n \n // Clean up any pending messages for old peer ID\n self.pendingPrivateMessages.removeValue(forKey: existingPeerID)\n // Don't transfer pending messages - they would be stale anyway\n }\n \n // Add new mapping\n self.peerIDToFingerprint[newPeerID] = fingerprint\n self.fingerprintToPeerID[fingerprint] = newPeerID\n self.peerIdentityBindings[fingerprint] = binding\n \n // Cache public keys to avoid keychain lookups\n self.peerPublicKeyCache[newPeerID] = binding.publicKey\n self.peerSigningKeyCache[newPeerID] = binding.signingPublicKey\n self.identityCacheTimestamps[newPeerID] = Date()\n \n // Also update nickname from binding\n self.peerNicknames[newPeerID] = binding.nickname\n \n // Notify about the change if it's a rotation\n if let oldID = oldPeerID {\n // Clear the old session instead of migrating it\n // This ensures both peers do a fresh handshake after ID rotation\n self.cleanupPeerCryptoState(oldID)\n self.handshakeCoordinator.resetHandshakeState(for: newPeerID)\n \n // Log the peer ID rotation\n SecureLogger.log(\"Cleared session for peer ID rotation: \\(oldID) -> \\(newPeerID), will establish fresh handshake\", \n category: SecureLogger.handshake, level: .info)\n \n self.notifyPeerIDChange(oldPeerID: oldID, newPeerID: newPeerID, fingerprint: fingerprint)\n \n // Lazy handshake: No longer initiate handshake on peer ID rotation\n // Handshake will be initiated when first private message is sent\n }\n }\n }\n \n // Public method to get current peer ID for a fingerprint\n func getCurrentPeerIDForFingerprint(_ fingerprint: String) -> String? {\n return collectionsQueue.sync {\n return fingerprintToPeerID[fingerprint]\n }\n }\n \n // Public method to get all current peer IDs for known fingerprints\n func getCurrentPeerIDs() -> [String: String] {\n return collectionsQueue.sync {\n return fingerprintToPeerID\n }\n }\n \n // Notify delegate when peer ID changes\n private func notifyPeerIDChange(oldPeerID: String, newPeerID: String, fingerprint: String) {\n DispatchQueue.main.async { [weak self] in\n // Remove old peer ID from active peers and announcedPeers\n self?.collectionsQueue.sync(flags: .barrier) {\n _ = self?.activePeers.remove(oldPeerID)\n // Don't pre-insert the new peer ID - let the announce packet handle it\n // This ensures the connect message logic works properly\n }\n \n // Also remove from announcedPeers so the new ID can trigger a connect message\n self?.announcedPeers.remove(oldPeerID)\n \n // Update peer list\n self?.notifyPeerListUpdate(immediate: true)\n \n // Don't send disconnect/connect messages for peer ID rotation\n // The peer didn't actually disconnect, they just rotated their ID\n // This prevents confusing messages like \"3a7e1c2c0d8943b9 disconnected\"\n \n // Instead, notify the delegate about the peer ID change if needed\n // (Could add a new delegate method for this in the future)\n }\n }\n \n // MARK: - Peer Connection Management\n \n func getCachedPublicKey(for peerID: String) -> Data? {\n return collectionsQueue.sync {\n // Check if cache entry exists and is not expired\n if let timestamp = identityCacheTimestamps[peerID],\n Date().timeIntervalSince(timestamp) < identityCacheTTL {\n return peerPublicKeyCache[peerID]\n }\n return nil\n }\n }\n \n func getCachedSigningKey(for peerID: String) -> Data? {\n return collectionsQueue.sync {\n // Check if cache entry exists and is not expired\n if let timestamp = identityCacheTimestamps[peerID],\n Date().timeIntervalSince(timestamp) < identityCacheTTL {\n return peerSigningKeyCache[peerID]\n }\n return nil\n }\n }\n \n private func updatePeerConnectionState(_ peerID: String, state: PeerConnectionState) {\n connectionStateQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n let previousState = self.peerConnectionStates[peerID]\n self.peerConnectionStates[peerID] = state\n \n SecureLogger.log(\"Peer \\(peerID) connection state: \\(previousState?.description ?? \"nil\") -> \\(state)\", \n category: SecureLogger.session, level: .debug)\n \n // Update activePeers based on authentication state\n self.collectionsQueue.async(flags: .barrier) {\n switch state {\n case .authenticated:\n if !self.activePeers.contains(peerID) {\n self.activePeers.insert(peerID)\n SecureLogger.log(\"Added \\(peerID) to activePeers (authenticated)\", \n category: SecureLogger.session, level: .info)\n }\n case .disconnected:\n if self.activePeers.contains(peerID) {\n self.activePeers.remove(peerID)\n SecureLogger.log(\"Removed \\(peerID) from activePeers (disconnected)\", \n category: SecureLogger.session, level: .info)\n }\n default:\n break\n }\n \n // Always notify peer list update when connection state changes\n DispatchQueue.main.async {\n self.notifyPeerListUpdate(immediate: true)\n }\n }\n }\n }\n \n // Get peer connection state\n func getPeerConnectionState(_ peerID: String) -> PeerConnectionState {\n return connectionStateQueue.sync {\n peerConnectionStates[peerID] ?? .disconnected\n }\n }\n \n // MARK: - Peer ID Rotation\n \n private func generateNewPeerID() -> String {\n // Generate 8 random bytes (64 bits) for strong collision resistance\n var randomBytes = [UInt8](repeating: 0, count: 8)\n let result = SecRandomCopyBytes(kSecRandomDefault, 8, &randomBytes)\n \n // If SecRandomCopyBytes fails, use alternative randomization\n if result != errSecSuccess {\n for i in 0..<8 {\n randomBytes[i] = UInt8.random(in: 0...255)\n }\n }\n \n // Add timestamp entropy to ensure uniqueness\n // Use lower 32 bits of timestamp in milliseconds to avoid overflow\n let timestampMs = UInt64(Date().timeIntervalSince1970 * 1000)\n let timestamp = UInt32(timestampMs & 0xFFFFFFFF)\n randomBytes[4] = UInt8((timestamp >> 24) & 0xFF)\n randomBytes[5] = UInt8((timestamp >> 16) & 0xFF)\n randomBytes[6] = UInt8((timestamp >> 8) & 0xFF)\n randomBytes[7] = UInt8(timestamp & 0xFF)\n \n return randomBytes.map { String(format: \"%02x\", $0) }.joined()\n }\n \n func rotatePeerID() {\n guard !rotationLocked else {\n // Schedule rotation for later\n scheduleRotation(delay: 30.0)\n return\n }\n \n collectionsQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n // Save current peer ID as previous\n let oldID = self.myPeerID\n self.previousPeerID = oldID\n self.rotationTimestamp = Date()\n \n // Generate new peer ID\n self.myPeerID = self.generateNewPeerID()\n \n SecureLogger.log(\"Peer ID rotated from \\(oldID) to \\(self.myPeerID)\", category: SecureLogger.security, level: .info)\n \n // Update advertising with new peer ID\n DispatchQueue.main.async { [weak self] in\n self?.updateAdvertisement()\n }\n \n // Send identity announcement with new peer ID\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n self?.sendNoiseIdentityAnnounce()\n }\n \n // Schedule next rotation\n self.scheduleNextRotation()\n }\n }\n \n private func scheduleRotation(delay: TimeInterval) {\n DispatchQueue.main.async { [weak self] in\n self?.rotationTimer?.invalidate()\n self?.rotationTimer = Timer.scheduledTimer(withTimeInterval: delay, repeats: false) { _ in\n self?.rotatePeerID()\n }\n }\n }\n \n private func scheduleNextRotation() {\n // Base interval: 1-6 hours\n let baseInterval = TimeInterval.random(in: 3600...21600)\n \n // Add jitter: ±30 minutes\n let jitter = TimeInterval.random(in: -1800...1800)\n \n // Additional random delay to prevent synchronization\n let networkDelay = TimeInterval.random(in: 0...300) // 0-5 minutes\n \n let nextRotation = baseInterval + jitter + networkDelay\n \n scheduleRotation(delay: nextRotation)\n }\n \n private func updateAdvertisement() {\n guard isAdvertising else { return }\n \n peripheralManager?.stopAdvertising()\n \n // Update advertisement data with new peer ID\n advertisementData = [\n CBAdvertisementDataServiceUUIDsKey: [BluetoothMeshService.serviceUUID],\n CBAdvertisementDataLocalNameKey: myPeerID\n ]\n \n peripheralManager?.startAdvertising(advertisementData)\n }\n \n func lockRotation() {\n rotationLocked = true\n }\n \n func unlockRotation() {\n rotationLocked = false\n }\n \n // MARK: - Initialization\n \n override init() {\n // Generate ephemeral peer ID for each session to prevent tracking\n self.myPeerID = \"\"\n super.init()\n self.myPeerID = generateNewPeerID()\n \n centralManager = CBCentralManager(delegate: self, queue: nil)\n peripheralManager = CBPeripheralManager(delegate: self, queue: nil)\n \n // Start bloom filter reset timer (reset every 5 minutes)\n bloomFilterResetTimer = Timer.scheduledTimer(withTimeInterval: 300.0, repeats: true) { [weak self] _ in\n self?.messageQueue.async(flags: .barrier) {\n guard let self = self else { return }\n \n // Adapt Bloom filter size based on network size\n let networkSize = self.estimatedNetworkSize\n self.messageBloomFilter = OptimizedBloomFilter.adaptive(for: networkSize)\n \n // Clear other duplicate detection sets\n self.processedMessagesLock.lock()\n self.processedMessages.removeAll()\n self.processedMessagesLock.unlock()\n \n }\n }\n \n // Start stale peer cleanup timer (every 30 seconds)\n cleanupTimer = Timer.scheduledTimer(withTimeInterval: 60.0, repeats: true) { [weak self] _ in\n self?.cleanupStalePeers()\n }\n \n // Start ACK timeout checking timer (every 2 seconds for timely retries)\n Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { [weak self] _ in\n self?.checkAckTimeouts()\n }\n \n // Start peer availability checking timer (every 15 seconds)\n availabilityCheckTimer = Timer.scheduledTimer(withTimeInterval: 15.0, repeats: true) { [weak self] _ in\n self?.checkPeerAvailability()\n }\n \n // Start RSSI update timer (every 10 seconds)\n Timer.scheduledTimer(withTimeInterval: 10.0, repeats: true) { [weak self] _ in\n self?.updateAllPeripheralRSSI()\n }\n \n // Start write queue cleanup timer (every 30 seconds)\n writeQueueTimer = Timer.scheduledTimer(withTimeInterval: 30.0, repeats: true) { [weak self] _ in\n self?.cleanExpiredWriteQueues()\n }\n \n // Start identity cache cleanup timer (every hour)\n Timer.scheduledTimer(withTimeInterval: 3600.0, repeats: true) { [weak self] _ in\n self?.cleanExpiredIdentityCache()\n }\n \n // Start memory cleanup timer (every minute)\n startMemoryCleanupTimer()\n \n // Start connection keep-alive timer to prevent iOS BLE timeouts\n connectionKeepAliveTimer = Timer.scheduledTimer(withTimeInterval: keepAliveInterval, repeats: true) { [weak self] _ in\n self?.sendKeepAlivePings()\n }\n \n // Log handshake states periodically for debugging and clean up stale states\n #if DEBUG\n Timer.scheduledTimer(withTimeInterval: 30.0, repeats: true) { [weak self] _ in\n guard let self = self else { return }\n \n // Clean up stale handshakes\n let stalePeerIDs = self.handshakeCoordinator.cleanupStaleHandshakes()\n if !stalePeerIDs.isEmpty {\n for peerID in stalePeerIDs {\n // Also remove from noise service\n self.cleanupPeerCryptoState(peerID)\n SecureLogger.log(\"Cleaned up stale handshake for \\(peerID)\", category: SecureLogger.handshake, level: .info)\n }\n }\n \n self.handshakeCoordinator.logHandshakeStates()\n }\n #endif\n \n // Schedule first peer ID rotation\n scheduleNextRotation()\n \n // Setup noise callbacks\n noiseService.onPeerAuthenticated = { [weak self] peerID, fingerprint in\n // Get peer's public key data from noise service\n if let publicKeyData = self?.noiseService.getPeerPublicKeyData(peerID) {\n // Register with ChatViewModel for verification tracking\n DispatchQueue.main.async {\n (self?.delegate as? ChatViewModel)?.registerPeerPublicKey(peerID: peerID, publicKeyData: publicKeyData)\n \n // Force UI to update encryption status for this specific peer\n (self?.delegate as? ChatViewModel)?.updateEncryptionStatusForPeer(peerID)\n }\n }\n \n // Send regular announce packet when authenticated to trigger connect message\n // This covers the case where we're the responder in the handshake\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in\n self?.sendAnnouncementToPeer(peerID)\n }\n }\n \n // Register for app termination notifications\n #if os(macOS)\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillTerminate),\n name: NSApplication.willTerminateNotification,\n object: nil\n )\n #else\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillTerminate),\n name: UIApplication.willTerminateNotification,\n object: nil\n )\n #endif\n }\n \n // MARK: - Deinitialization and Cleanup\n \n deinit {\n cleanup()\n scanDutyCycleTimer?.invalidate()\n batteryMonitorTimer?.invalidate()\n coverTrafficTimer?.invalidate()\n bloomFilterResetTimer?.invalidate()\n aggregationTimer?.invalidate()\n cleanupTimer?.invalidate()\n rotationTimer?.invalidate()\n memoryCleanupTimer?.invalidate()\n connectionKeepAliveTimer?.invalidate()\n availabilityCheckTimer?.invalidate()\n }\n \n @objc private func appWillTerminate() {\n cleanup()\n }\n \n private func cleanup() {\n // Send leave announcement before disconnecting\n sendLeaveAnnouncement()\n \n // Give the leave message time to send\n Thread.sleep(forTimeInterval: 0.2)\n \n // First, disconnect all peripherals which will trigger disconnect delegates\n for (_, peripheral) in connectedPeripherals {\n centralManager?.cancelPeripheralConnection(peripheral)\n }\n \n // Stop advertising\n if peripheralManager?.isAdvertising == true {\n peripheralManager?.stopAdvertising()\n }\n \n // Stop scanning\n centralManager?.stopScan()\n \n // Remove all services - this will disconnect any connected centrals\n if peripheralManager?.state == .poweredOn {\n peripheralManager?.removeAllServices()\n }\n \n // Clear all tracking\n connectedPeripherals.removeAll()\n subscribedCentrals.removeAll()\n collectionsQueue.sync(flags: .barrier) {\n activePeers.removeAll()\n }\n announcedPeers.removeAll()\n // For normal disconnect, respect the timing\n networkBecameEmptyTime = Date()\n \n // Clear announcement tracking\n announcedToPeers.removeAll()\n \n // Clear last seen timestamps\n peerLastSeenTimestamps.removeAll()\n \n // Clear all encryption queues\n encryptionQueuesLock.lock()\n peerEncryptionQueues.removeAll()\n encryptionQueuesLock.unlock()\n \n // Clear peer tracking\n lastHeardFromPeer.removeAll()\n }\n \n // MARK: - Service Management\n \n /// Starts the Bluetooth mesh networking services.\n /// This initializes both central (scanning) and peripheral (advertising) modes,\n /// enabling the device to both discover peers and be discovered.\n /// Call this method after setting the delegate and localUserID.\n func startServices() {\n // Starting services\n // Start both central and peripheral services\n if centralManager?.state == .poweredOn {\n startScanning()\n }\n if peripheralManager?.state == .poweredOn {\n setupPeripheral()\n startAdvertising()\n }\n \n // Send initial announces after services are ready\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [weak self] in\n self?.sendBroadcastAnnounce()\n }\n \n // Setup battery optimizer\n setupBatteryOptimizer()\n \n // Start cover traffic for privacy (disabled by default for now)\n // TODO: Make this configurable in settings\n let coverTrafficEnabled = true\n if coverTrafficEnabled {\n SecureLogger.log(\"Cover traffic enabled\", category: SecureLogger.security, level: .info)\n startCoverTraffic()\n }\n }\n \n // MARK: - Message Sending\n \n func sendBroadcastAnnounce() {\n guard let vm = delegate as? ChatViewModel else { return }\n \n \n let announcePacket = BitchatPacket(\n type: MessageType.announce.rawValue,\n ttl: 3, // Increase TTL so announce reaches all peers\n senderID: myPeerID,\n payload: Data(vm.nickname.utf8) )\n \n \n // Single send with smart collision avoidance\n let initialDelay = self.smartCollisionAvoidanceDelay(baseDelay: self.randomDelay())\n DispatchQueue.main.asyncAfter(deadline: .now() + initialDelay) { [weak self] in\n self?.broadcastPacket(announcePacket)\n \n // Don't automatically send identity announcement on startup\n // Let it happen naturally when peers connect\n }\n }\n \n func startAdvertising() {\n guard peripheralManager?.state == .poweredOn else { \n return \n }\n \n // Use generic advertising to avoid identification\n // No identifying prefixes or app names for activist safety\n \n // Only use allowed advertisement keys\n advertisementData = [\n CBAdvertisementDataServiceUUIDsKey: [BluetoothMeshService.serviceUUID],\n // Use only peer ID without any identifying prefix\n CBAdvertisementDataLocalNameKey: myPeerID\n ]\n \n isAdvertising = true\n peripheralManager?.startAdvertising(advertisementData)\n }\n \n func startScanning() {\n guard centralManager?.state == .poweredOn else { \n return \n }\n \n // Enable duplicate detection for RSSI tracking\n let scanOptions: [String: Any] = [\n CBCentralManagerScanOptionAllowDuplicatesKey: true\n ]\n \n centralManager?.scanForPeripherals(\n withServices: [BluetoothMeshService.serviceUUID],\n options: scanOptions\n )\n \n // Update scan parameters based on battery before starting\n updateScanParametersForBattery()\n \n // Implement scan duty cycling for battery efficiency\n scheduleScanDutyCycle()\n }\n \n private func scheduleScanDutyCycle() {\n guard scanDutyCycleTimer == nil else { return }\n \n // Start with active scanning\n isActivelyScanning = true\n \n scanDutyCycleTimer = Timer.scheduledTimer(withTimeInterval: activeScanDuration, repeats: true) { [weak self] _ in\n guard let self = self else { return }\n \n if self.isActivelyScanning {\n // Pause scanning to save battery\n self.centralManager?.stopScan()\n self.isActivelyScanning = false\n \n // Schedule resume\n DispatchQueue.main.asyncAfter(deadline: .now() + self.scanPauseDuration) { [weak self] in\n guard let self = self else { return }\n if self.centralManager?.state == .poweredOn {\n self.centralManager?.scanForPeripherals(\n withServices: [BluetoothMeshService.serviceUUID],\n options: [CBCentralManagerScanOptionAllowDuplicatesKey: true]\n )\n self.isActivelyScanning = true\n }\n }\n }\n }\n }\n \n private func setupPeripheral() {\n let characteristic = CBMutableCharacteristic(\n type: BluetoothMeshService.characteristicUUID,\n properties: [.read, .write, .writeWithoutResponse, .notify],\n value: nil,\n permissions: [.readable, .writeable]\n )\n \n let service = CBMutableService(type: BluetoothMeshService.serviceUUID, primary: true)\n service.characteristics = [characteristic]\n \n peripheralManager?.add(service)\n self.characteristic = characteristic\n }\n \n /// Sends a message through the mesh network.\n /// - Parameters:\n /// - content: The message content to send\n /// - mentions: Array of user IDs being mentioned in the message\n /// - recipientID: Optional recipient ID for directed messages (nil for broadcast)\n /// - messageID: Optional custom message ID (auto-generated if nil)\n /// - timestamp: Optional custom timestamp (current time if nil)\n /// - Note: Messages are automatically routed through the mesh using TTL-based forwarding\n func sendMessage(_ content: String, mentions: [String] = [], to recipientID: String? = nil, messageID: String? = nil, timestamp: Date? = nil) {\n // Defensive check for empty content\n guard !content.isEmpty else { return }\n messageQueue.async { [weak self] in\n guard let self = self else { return }\n \n let nickname = self.delegate as? ChatViewModel\n let senderNick = nickname?.nickname ?? self.myPeerID\n \n let message = BitchatMessage(\n id: messageID,\n sender: senderNick,\n content: content,\n timestamp: timestamp ?? Date(),\n isRelay: false,\n originalSender: nil,\n isPrivate: false,\n recipientNickname: nil,\n senderPeerID: self.myPeerID,\n mentions: mentions.isEmpty ? nil : mentions\n )\n \n if let messageData = message.toBinaryPayload() {\n \n \n // Use unified message type with broadcast recipient\n let packet = BitchatPacket(\n type: MessageType.message.rawValue,\n senderID: Data(hexString: self.myPeerID) ?? Data(),\n recipientID: SpecialRecipients.broadcast, // Special broadcast ID\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000), // milliseconds\n payload: messageData,\n signature: nil,\n ttl: self.adaptiveTTL )\n \n // Track this message to prevent duplicate sends\n let msgID = \"\\(packet.timestamp)-\\(self.myPeerID)-\\(packet.payload.prefix(32).hashValue)\"\n \n let shouldSend = !self.recentlySentMessages.contains(msgID)\n if shouldSend {\n self.recentlySentMessages.insert(msgID)\n }\n \n if shouldSend {\n // Clean up old entries after 10 seconds\n self.messageQueue.asyncAfter(deadline: .now() + 10.0) { [weak self] in\n guard let self = self else { return }\n self.recentlySentMessages.remove(msgID)\n }\n \n // Single send with smart collision avoidance\n let initialDelay = self.smartCollisionAvoidanceDelay(baseDelay: self.randomDelay())\n DispatchQueue.main.asyncAfter(deadline: .now() + initialDelay) { [weak self] in\n self?.broadcastPacket(packet)\n }\n }\n }\n }\n }\n \n \n /// Sends an end-to-end encrypted private message to a specific peer.\n /// - Parameters:\n /// - content: The message content to encrypt and send\n /// - recipientPeerID: The peer ID of the recipient\n /// - recipientNickname: The nickname of the recipient (for UI display)\n /// - messageID: Optional custom message ID (auto-generated if nil)\n /// - Note: This method automatically handles Noise handshake if not already established\n func sendPrivateMessage(_ content: String, to recipientPeerID: String, recipientNickname: String, messageID: String? = nil) {\n // Defensive checks\n guard !content.isEmpty, !recipientPeerID.isEmpty, !recipientNickname.isEmpty else { \n return \n }\n \n let msgID = messageID ?? UUID().uuidString\n \n messageQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Check if this is an old peer ID that has rotated\n var targetPeerID = recipientPeerID\n \n // If we have a fingerprint for this peer ID, check if there's a newer peer ID\n if let fingerprint = self.collectionsQueue.sync(execute: { self.peerIDToFingerprint[recipientPeerID] }),\n let currentPeerID = self.collectionsQueue.sync(execute: { self.fingerprintToPeerID[fingerprint] }),\n currentPeerID != recipientPeerID {\n // Use the current peer ID instead\n targetPeerID = currentPeerID\n }\n \n // Always use Noise encryption\n self.sendPrivateMessageViaNoise(content, to: targetPeerID, recipientNickname: recipientNickname, messageID: msgID)\n }\n }\n \n func sendDeliveryAck(_ ack: DeliveryAck, to recipientID: String) {\n // Use per-peer encryption queue to prevent nonce desynchronization\n let encryptionQueue = getEncryptionQueue(for: recipientID)\n \n encryptionQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Encode the ACK\n let ackData = ack.toBinaryData()\n \n // Check if we have a Noise session with this peer\n // Use noiseService directly\n if self.noiseService.hasEstablishedSession(with: recipientID) {\n // Use Noise encryption - encrypt only the ACK payload directly\n do {\n // Create a special payload that indicates this is a delivery ACK\n // Format: [1 byte type marker] + [ACK JSON data]\n var ackPayload = Data()\n ackPayload.append(MessageType.deliveryAck.rawValue) // Type marker\n ackPayload.append(ackData) // ACK JSON\n \n // Encrypt only the payload (not a full packet)\n let encryptedPayload = try noiseService.encrypt(ackPayload, for: recipientID)\n \n // Create outer Noise packet with the encrypted payload\n let outerPacket = BitchatPacket(\n type: MessageType.noiseEncrypted.rawValue,\n senderID: Data(hexString: self.myPeerID) ?? Data(),\n recipientID: Data(hexString: recipientID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: encryptedPayload,\n signature: nil,\n ttl: 3 )\n \n // Try direct delivery first for delivery ACKs\n if !self.sendDirectToRecipient(outerPacket, recipientPeerID: recipientID) {\n // Recipient not directly connected, use selective relay\n SecureLogger.log(\"Recipient \\(recipientID) not directly connected for delivery ACK, using relay\", \n category: SecureLogger.session, level: .info)\n self.sendViaSelectiveRelay(outerPacket, recipientPeerID: recipientID)\n }\n } catch {\n SecureLogger.logError(error, context: \"Failed to encrypt delivery ACK via Noise for \\(recipientID)\", category: SecureLogger.encryption)\n }\n } else {\n // Lazy handshake: No session available, drop the ACK\n SecureLogger.log(\"No Noise session with \\(recipientID) for delivery ACK - dropping (lazy handshake mode)\", \n category: SecureLogger.noise, level: .info)\n }\n }\n }\n \n private func getEncryptionQueue(for peerID: String) -> DispatchQueue {\n encryptionQueuesLock.lock()\n defer { encryptionQueuesLock.unlock() }\n \n if let queue = peerEncryptionQueues[peerID] {\n return queue\n }\n \n let queue = DispatchQueue(label: \"bitchat.encryption.\\(peerID)\", qos: .userInitiated)\n peerEncryptionQueues[peerID] = queue\n return queue\n }\n \n private func removeEncryptionQueue(for peerID: String) {\n encryptionQueuesLock.lock()\n defer { encryptionQueuesLock.unlock() }\n \n peerEncryptionQueues.removeValue(forKey: peerID)\n }\n \n // Centralized cleanup for peer crypto state\n private func cleanupPeerCryptoState(_ peerID: String) {\n noiseService.removePeer(peerID)\n handshakeCoordinator.resetHandshakeState(for: peerID)\n removeEncryptionQueue(for: peerID)\n }\n \n func sendReadReceipt(_ receipt: ReadReceipt, to recipientID: String) {\n // Use per-peer encryption queue to prevent nonce desynchronization\n let encryptionQueue = getEncryptionQueue(for: recipientID)\n \n encryptionQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Encode the receipt\n let receiptData = receipt.toBinaryData()\n \n // Check if we have a Noise session with this peer\n // Use noiseService directly\n if self.noiseService.hasEstablishedSession(with: recipientID) {\n // Use Noise encryption - encrypt only the receipt payload directly\n do {\n // Create a special payload that indicates this is a read receipt\n // Format: [1 byte type marker] + [receipt binary data]\n var receiptPayload = Data()\n receiptPayload.append(MessageType.readReceipt.rawValue) // Type marker\n receiptPayload.append(receiptData) // Receipt binary data\n \n // Encrypt only the payload (not a full packet)\n let encryptedPayload = try noiseService.encrypt(receiptPayload, for: recipientID)\n \n // Create outer Noise packet with the encrypted payload\n let outerPacket = BitchatPacket(\n type: MessageType.noiseEncrypted.rawValue,\n senderID: Data(hexString: self.myPeerID) ?? Data(),\n recipientID: Data(hexString: recipientID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: encryptedPayload,\n signature: nil,\n ttl: 3 )\n \n SecureLogger.log(\"Sending encrypted read receipt for message \\(receipt.originalMessageID) to \\(recipientID)\", category: SecureLogger.noise, level: .info)\n \n // Try direct delivery first for read receipts\n if !self.sendDirectToRecipient(outerPacket, recipientPeerID: recipientID) {\n // Recipient not directly connected, use selective relay\n SecureLogger.log(\"Recipient \\(recipientID) not directly connected for read receipt, using relay\", \n category: SecureLogger.session, level: .info)\n self.sendViaSelectiveRelay(outerPacket, recipientPeerID: recipientID)\n }\n } catch {\n SecureLogger.logError(error, context: \"Failed to encrypt read receipt via Noise for \\(recipientID)\", category: SecureLogger.encryption)\n }\n } else {\n // Lazy handshake: No session available, drop the read receipt\n SecureLogger.log(\"No Noise session with \\(recipientID) for read receipt - dropping (lazy handshake mode)\", \n category: SecureLogger.noise, level: .info)\n }\n }\n }\n \n \n \n \n \n private func sendAnnouncementToPeer(_ peerID: String) {\n guard let vm = delegate as? ChatViewModel else { return }\n \n \n // Always send announce, don't check if already announced\n // This ensures peers get our nickname even if they reconnect\n \n let packet = BitchatPacket(\n type: MessageType.announce.rawValue,\n ttl: 3, // Allow relay for better reach\n senderID: myPeerID,\n payload: Data(vm.nickname.utf8) )\n \n if let data = packet.toBinaryData() {\n // Try both broadcast and targeted send\n broadcastPacket(packet)\n \n // Also try targeted send if we have the peripheral\n if let peripheral = connectedPeripherals[peerID],\n peripheral.state == .connected,\n let characteristic = peripheral.services?.first(where: { $0.uuid == BluetoothMeshService.serviceUUID })?.characteristics?.first(where: { $0.uuid == BluetoothMeshService.characteristicUUID }) {\n writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: peerID)\n } else {\n }\n } else {\n }\n \n announcedToPeers.insert(peerID)\n }\n \n private func sendLeaveAnnouncement() {\n guard let vm = delegate as? ChatViewModel else { return }\n \n let packet = BitchatPacket(\n type: MessageType.leave.rawValue,\n ttl: 1, // Don't relay leave messages\n senderID: myPeerID,\n payload: Data(vm.nickname.utf8) )\n \n broadcastPacket(packet)\n }\n \n // Get Noise session state for UI display\n func getNoiseSessionState(for peerID: String) -> LazyHandshakeState {\n return collectionsQueue.sync {\n // First check our tracked state\n if let state = noiseSessionStates[peerID] {\n return state\n }\n \n // If no tracked state, check if we have an established session\n if noiseService.hasEstablishedSession(with: peerID) {\n return .established\n }\n \n // Default to none\n return .none\n }\n }\n \n // Trigger handshake with a peer (for UI)\n func triggerHandshake(with peerID: String) {\n SecureLogger.log(\"UI triggered handshake with \\(peerID)\", category: SecureLogger.noise, level: .info)\n \n // Check if we already have a session\n if noiseService.hasEstablishedSession(with: peerID) {\n SecureLogger.log(\"Already have session with \\(peerID), skipping handshake\", category: SecureLogger.noise, level: .debug)\n return\n }\n \n // Update state to handshakeQueued\n collectionsQueue.sync(flags: .barrier) {\n noiseSessionStates[peerID] = .handshakeQueued\n }\n \n // Always initiate handshake when triggered by UI\n // This ensures immediate handshake when opening PM\n initiateNoiseHandshake(with: peerID)\n }\n \n func getPeerNicknames() -> [String: String] {\n return collectionsQueue.sync {\n return peerNicknames\n }\n }\n \n func getPeerRSSI() -> [String: NSNumber] {\n var rssiValues = peerRSSI\n \n \n // Log connectedPeripherals state\n SecureLogger.log(\"connectedPeripherals has \\(connectedPeripherals.count) entries:\", category: SecureLogger.session, level: .debug)\n for (peerID, peripheral) in connectedPeripherals {\n SecureLogger.log(\" connectedPeripherals[\\(peerID)] = \\(peripheral.identifier.uuidString)\", category: SecureLogger.session, level: .debug)\n }\n \n \n // Also check peripheralRSSI for any connected peripherals\n // This handles cases where RSSI is stored under temp IDs\n for (peerID, peripheral) in connectedPeripherals {\n // Skip temp IDs when iterating\n if peerID.count != 16 {\n continue\n }\n \n // If we don't have RSSI for this peer ID\n if rssiValues[peerID] == nil {\n \n // Check if we have RSSI stored by peripheral ID\n let peripheralID = peripheral.identifier.uuidString\n if let rssi = peripheralRSSI[peripheralID] {\n rssiValues[peerID] = rssi\n }\n // Also check if RSSI is stored under the peer ID as a temp ID\n else if let rssi = peripheralRSSI[peerID] {\n rssiValues[peerID] = rssi\n }\n }\n }\n \n // Also check for any known peers that might have RSSI in peerRSSI but not in connectedPeripherals\n for (peerID, _) in peerNicknames {\n if rssiValues[peerID] == nil && peerID.count == 16 {\n // Check if we have RSSI stored directly\n if let rssi = peerRSSI[peerID] {\n rssiValues[peerID] = rssi\n } else if let rssi = peripheralRSSI[peerID] {\n rssiValues[peerID] = rssi\n }\n }\n }\n \n \n return rssiValues\n }\n \n // Emergency disconnect for panic situations\n func emergencyDisconnectAll() {\n SecureLogger.log(\"Emergency disconnect triggered\", category: SecureLogger.security, level: .warning)\n \n // Stop advertising immediately\n if peripheralManager?.isAdvertising == true {\n peripheralManager?.stopAdvertising()\n }\n \n // Stop scanning\n centralManager?.stopScan()\n scanDutyCycleTimer?.invalidate()\n scanDutyCycleTimer = nil\n \n // Disconnect all peripherals\n for (peerID, peripheral) in connectedPeripherals {\n SecureLogger.log(\"Emergency disconnect peer: \\(peerID)\", category: SecureLogger.session, level: .warning)\n centralManager?.cancelPeripheralConnection(peripheral)\n }\n \n // Clear all peer data\n connectedPeripherals.removeAll()\n peripheralCharacteristics.removeAll()\n discoveredPeripherals.removeAll()\n subscribedCentrals.removeAll()\n peerNicknames.removeAll()\n activePeers.removeAll()\n peerRSSI.removeAll()\n peripheralRSSI.removeAll()\n rssiRetryCount.removeAll()\n announcedToPeers.removeAll()\n announcedPeers.removeAll()\n // For emergency/panic, reset immediately\n hasNotifiedNetworkAvailable = false\n networkBecameEmptyTime = nil\n lastNetworkNotificationTime = nil\n processedMessagesLock.lock()\n processedMessages.removeAll()\n processedMessagesLock.unlock()\n incomingFragments.removeAll()\n \n // Clear all encryption queues\n encryptionQueuesLock.lock()\n peerEncryptionQueues.removeAll()\n encryptionQueuesLock.unlock()\n fragmentMetadata.removeAll()\n \n // Cancel all pending relays\n pendingRelaysLock.lock()\n for (_, relay) in pendingRelays {\n relay.cancel()\n }\n pendingRelays.removeAll()\n pendingRelaysLock.unlock()\n \n // Clear peer tracking\n lastHeardFromPeer.removeAll()\n \n // Clear persistent identity\n noiseService.clearPersistentIdentity()\n \n // Clear all handshake coordinator states\n handshakeCoordinator.clearAllHandshakeStates()\n \n // Clear handshake attempt times\n handshakeAttemptTimes.removeAll()\n \n // Notify UI that all peers are disconnected\n DispatchQueue.main.async { [weak self] in\n self?.delegate?.didUpdatePeerList([])\n }\n }\n \n private func getAllConnectedPeerIDs() -> [String] {\n // Return all valid active peers\n let peersCopy = collectionsQueue.sync {\n return activePeers\n }\n \n \n let validPeers = peersCopy.filter { peerID in\n // Ensure peerID is valid and not self\n let isEmpty = peerID.isEmpty\n let isUnknown = peerID == \"unknown\"\n let isSelf = peerID == self.myPeerID\n \n return !isEmpty && !isUnknown && !isSelf\n }\n \n let result = Array(validPeers).sorted()\n return result\n }\n \n // Debounced peer list update notification\n private func notifyPeerListUpdate(immediate: Bool = false) {\n if immediate {\n // For initial connections, update immediately\n let connectedPeerIDs = self.getAllConnectedPeerIDs()\n \n DispatchQueue.main.async {\n self.delegate?.didUpdatePeerList(connectedPeerIDs)\n }\n } else {\n // Must schedule timer on main thread\n DispatchQueue.main.async { [weak self] in\n guard let self = self else { return }\n \n // Cancel any pending update\n self.peerListUpdateTimer?.invalidate()\n \n // Schedule a new update after debounce interval\n self.peerListUpdateTimer = Timer.scheduledTimer(withTimeInterval: self.peerListUpdateDebounceInterval, repeats: false) { [weak self] _ in\n guard let self = self else { return }\n \n let connectedPeerIDs = self.getAllConnectedPeerIDs()\n \n self.delegate?.didUpdatePeerList(connectedPeerIDs)\n }\n }\n }\n }\n \n // Clean up stale peers that haven't been seen in a while\n private func cleanupStalePeers() {\n let staleThreshold: TimeInterval = 180.0 // 3 minutes - increased for better stability\n let now = Date()\n \n // Clean up expired gracefully left peers\n let expiredGracefulPeers = gracefulLeaveTimestamps.filter { (_, timestamp) in\n now.timeIntervalSince(timestamp) > gracefulLeaveExpirationTime\n }.map { $0.key }\n \n for peerID in expiredGracefulPeers {\n gracefullyLeftPeers.remove(peerID)\n gracefulLeaveTimestamps.removeValue(forKey: peerID)\n SecureLogger.log(\"Cleaned up expired gracefullyLeft entry for \\(peerID)\", \n category: SecureLogger.session, level: .debug)\n }\n \n let peersToRemove = collectionsQueue.sync(flags: .barrier) {\n let toRemove = activePeers.filter { peerID in\n if let lastSeen = peerLastSeenTimestamps.get(peerID) {\n return now.timeIntervalSince(lastSeen) > staleThreshold\n }\n return false // Keep peers we haven't tracked yet\n }\n \n var actuallyRemoved: [String] = []\n \n for peerID in toRemove {\n // Check if this peer has an active peripheral connection\n if let peripheral = connectedPeripherals[peerID], peripheral.state == .connected {\n // Skipping removal - still has active connection\n // Update last seen time to prevent immediate re-removal\n peerLastSeenTimestamps.set(peerID, value: Date())\n continue\n }\n \n let nickname = peerNicknames[peerID] ?? \"unknown\"\n activePeers.remove(peerID)\n peerLastSeenTimestamps.remove(peerID)\n SecureLogger.log(\"📴 Removed stale peer from network: \\(peerID) (\\(nickname))\", category: SecureLogger.session, level: .info)\n \n // Clean up all associated data\n connectedPeripherals.removeValue(forKey: peerID)\n peerRSSI.removeValue(forKey: peerID)\n announcedPeers.remove(peerID)\n announcedToPeers.remove(peerID)\n peerNicknames.removeValue(forKey: peerID)\n lastHeardFromPeer.removeValue(forKey: peerID)\n \n actuallyRemoved.append(peerID)\n // Removed stale peer\n }\n return actuallyRemoved\n }\n \n if !peersToRemove.isEmpty {\n notifyPeerListUpdate()\n \n // Mark when network became empty, but don't reset flag immediately\n let currentNetworkSize = collectionsQueue.sync { activePeers.count }\n if currentNetworkSize == 0 && networkBecameEmptyTime == nil {\n networkBecameEmptyTime = Date()\n }\n }\n \n // Check if we should reset the notification flag\n if let emptyTime = networkBecameEmptyTime {\n let currentNetworkSize = collectionsQueue.sync { activePeers.count }\n if currentNetworkSize == 0 {\n // Network is still empty, check if enough time has passed\n let timeSinceEmpty = Date().timeIntervalSince(emptyTime)\n if timeSinceEmpty >= networkEmptyResetDelay {\n // Reset the flag after network has been empty for the delay period\n hasNotifiedNetworkAvailable = false\n // Keep the empty time set so we don't immediately notify again\n }\n } else {\n // Network is no longer empty, clear the empty time\n networkBecameEmptyTime = nil\n }\n }\n }\n \n // MARK: - Store-and-Forward Methods\n \n private func cacheMessage(_ packet: BitchatPacket, messageID: String) {\n messageQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n // Don't cache certain message types\n guard packet.type != MessageType.announce.rawValue,\n packet.type != MessageType.leave.rawValue,\n packet.type != MessageType.fragmentStart.rawValue,\n packet.type != MessageType.fragmentContinue.rawValue,\n packet.type != MessageType.fragmentEnd.rawValue else {\n return\n }\n \n // Don't cache broadcast messages\n if let recipientID = packet.recipientID,\n recipientID == SpecialRecipients.broadcast {\n return // Never cache broadcast messages\n }\n \n // Check if this is a private message for a favorite\n var isForFavorite = false\n if packet.type == MessageType.message.rawValue,\n let recipientID = packet.recipientID {\n let recipientPeerID = recipientID.hexEncodedString()\n // Check if recipient is a favorite via their public key fingerprint\n if let fingerprint = self.noiseService.getPeerFingerprint(recipientPeerID) {\n isForFavorite = self.delegate?.isFavorite(fingerprint: fingerprint) ?? false\n }\n }\n \n // Create stored message with original packet timestamp preserved\n let storedMessage = StoredMessage(\n packet: packet,\n timestamp: Date(timeIntervalSince1970: TimeInterval(packet.timestamp) / 1000.0), // convert from milliseconds\n messageID: messageID,\n isForFavorite: isForFavorite\n )\n \n \n if isForFavorite {\n if let recipientID = packet.recipientID {\n let recipientPeerID = recipientID.hexEncodedString()\n if self.favoriteMessageQueue[recipientPeerID] == nil {\n self.favoriteMessageQueue[recipientPeerID] = []\n }\n self.favoriteMessageQueue[recipientPeerID]?.append(storedMessage)\n \n // Limit favorite queue size\n if let count = self.favoriteMessageQueue[recipientPeerID]?.count,\n count > self.maxCachedMessagesForFavorites {\n self.favoriteMessageQueue[recipientPeerID]?.removeFirst()\n }\n \n }\n } else {\n // Clean up old messages first (only for regular cache)\n self.cleanupMessageCache()\n \n // Add to regular cache\n self.messageCache.append(storedMessage)\n \n // Limit cache size\n if self.messageCache.count > self.maxCachedMessages {\n self.messageCache.removeFirst()\n }\n \n }\n }\n }\n \n private func cleanupMessageCache() {\n let cutoffTime = Date().addingTimeInterval(-messageCacheTimeout)\n // Only remove non-favorite messages that are older than timeout\n messageCache.removeAll { !$0.isForFavorite && $0.timestamp < cutoffTime }\n \n // Clean up delivered messages set periodically (keep recent 1000 entries)\n if deliveredMessages.count > 1000 {\n // Clear older entries while keeping recent ones\n deliveredMessages.removeAll()\n }\n }\n \n private func sendCachedMessages(to peerID: String) {\n messageQueue.async { [weak self] in\n guard let self = self,\n let peripheral = self.connectedPeripherals[peerID],\n let characteristic = self.peripheralCharacteristics[peripheral] else {\n return\n }\n \n \n // Check if we've already sent cached messages to this peer in this session\n if self.cachedMessagesSentToPeer.contains(peerID) {\n return // Already sent cached messages to this peer in this session\n }\n \n // Mark that we're sending cached messages to this peer\n self.cachedMessagesSentToPeer.insert(peerID)\n \n // Clean up old messages first\n self.cleanupMessageCache()\n \n var messagesToSend: [StoredMessage] = []\n \n // First, check if this peer has any favorite messages waiting\n if let favoriteMessages = self.favoriteMessageQueue[peerID] {\n // Filter out already delivered messages\n let undeliveredFavoriteMessages = favoriteMessages.filter { !self.deliveredMessages.contains($0.messageID) }\n messagesToSend.append(contentsOf: undeliveredFavoriteMessages)\n // Clear the favorite queue after adding to send list\n self.favoriteMessageQueue[peerID] = nil\n }\n \n // Filter regular cached messages for this specific recipient\n let recipientMessages = self.messageCache.filter { storedMessage in\n if self.deliveredMessages.contains(storedMessage.messageID) {\n return false\n }\n if let recipientID = storedMessage.packet.recipientID {\n let recipientPeerID = recipientID.hexEncodedString()\n return recipientPeerID == peerID\n }\n return false // Don't forward broadcast messages\n }\n messagesToSend.append(contentsOf: recipientMessages)\n \n \n // Sort messages by timestamp to ensure proper ordering\n messagesToSend.sort { $0.timestamp < $1.timestamp }\n \n if !messagesToSend.isEmpty {\n }\n \n // Mark messages as delivered immediately to prevent duplicates\n let messageIDsToRemove = messagesToSend.map { $0.messageID }\n for messageID in messageIDsToRemove {\n self.deliveredMessages.insert(messageID)\n }\n \n // Send cached messages with slight delay between each\n for (index, storedMessage) in messagesToSend.enumerated() {\n let delay = Double(index) * 0.02 // 20ms between messages for faster sync\n \n DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self, weak peripheral] in\n guard let peripheral = peripheral,\n peripheral.state == .connected else {\n return\n }\n \n // Send the original packet with preserved timestamp\n let packetToSend = storedMessage.packet\n \n if let data = packetToSend.toBinaryData(),\n characteristic.properties.contains(.writeWithoutResponse) {\n self?.writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: peerID)\n }\n }\n }\n \n // Remove sent messages immediately\n if !messageIDsToRemove.isEmpty {\n self.messageQueue.async(flags: .barrier) {\n // Remove only the messages we sent to this specific peer\n self.messageCache.removeAll { message in\n messageIDsToRemove.contains(message.messageID)\n }\n \n // Also remove from favorite queue if any\n if var favoriteQueue = self.favoriteMessageQueue[peerID] {\n favoriteQueue.removeAll { message in\n messageIDsToRemove.contains(message.messageID)\n }\n self.favoriteMessageQueue[peerID] = favoriteQueue.isEmpty ? nil : favoriteQueue\n }\n }\n }\n }\n }\n \n private func estimateDistance(rssi: Int) -> Int {\n // Rough distance estimation based on RSSI\n // Using path loss formula: RSSI = TxPower - 10 * n * log10(distance)\n // Assuming TxPower = -59 dBm at 1m, n = 2.0 (free space)\n let txPower = -59.0\n let pathLossExponent = 2.0\n \n let ratio = (txPower - Double(rssi)) / (10.0 * pathLossExponent)\n let distance = pow(10.0, ratio)\n \n return Int(distance)\n }\n \n private func broadcastPacket(_ packet: BitchatPacket) {\n // CRITICAL CHECK: Never send unencrypted JSON\n if packet.type == MessageType.deliveryAck.rawValue {\n // Check if payload looks like JSON\n if let jsonCheck = String(data: packet.payload.prefix(1), encoding: .utf8), jsonCheck == \"{\" {\n // Block unencrypted JSON in delivery ACKs\n return\n }\n }\n \n \n guard let data = packet.toBinaryData() else { \n // Failed to convert packet - add to retry queue if it's our message\n let senderID = packet.senderID.hexEncodedString()\n if senderID == self.myPeerID,\n packet.type == MessageType.message.rawValue,\n let message = BitchatMessage.fromBinaryPayload(packet.payload) {\n MessageRetryService.shared.addMessageForRetry(\n content: message.content,\n mentions: message.mentions,\n isPrivate: message.isPrivate,\n recipientPeerID: nil,\n recipientNickname: message.recipientNickname,\n originalMessageID: message.id,\n originalTimestamp: message.timestamp\n )\n }\n return \n }\n \n // Check if fragmentation is needed for large packets\n if data.count > 512 && packet.type != MessageType.fragmentStart.rawValue && \n packet.type != MessageType.fragmentContinue.rawValue && \n packet.type != MessageType.fragmentEnd.rawValue {\n sendFragmentedPacket(packet)\n return\n }\n \n // Track which peers we've sent to (to avoid duplicates)\n var sentToPeers = Set()\n \n // Send to connected peripherals (as central)\n var sentToPeripherals = 0\n \n // Log if this is a private message being broadcast\n if packet.type == MessageType.noiseEncrypted.rawValue,\n let recipientID = packet.recipientID?.hexEncodedString(),\n !recipientID.isEmpty {\n SecureLogger.log(\"WARNING: Broadcasting private message intended for \\(recipientID) to all peers\", \n category: SecureLogger.session, level: .warning)\n }\n \n // Broadcasting to connected peripherals\n for (peerID, peripheral) in connectedPeripherals {\n if let characteristic = peripheralCharacteristics[peripheral] {\n // Check if peripheral is connected before writing\n if peripheral.state == .connected {\n // Additional safety check for characteristic properties\n if characteristic.properties.contains(.write) || \n characteristic.properties.contains(.writeWithoutResponse) {\n // Writing packet to peripheral\n writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: peerID)\n sentToPeripherals += 1\n sentToPeers.insert(peerID)\n }\n } else {\n if let peerID = connectedPeripherals.first(where: { $0.value == peripheral })?.key {\n connectedPeripherals.removeValue(forKey: peerID)\n peripheralCharacteristics.removeValue(forKey: peripheral)\n }\n }\n }\n }\n \n // Send to subscribed centrals (as peripheral) - but only if we didn't already send via peripheral connections\n var sentToCentrals = 0\n if let char = characteristic, !subscribedCentrals.isEmpty && sentToPeripherals == 0 {\n // Only send to centrals if we haven't sent via peripheral connections\n // This prevents duplicate sends in 2-peer networks where peers connect both ways\n // Broadcasting to subscribed centrals\n let success = peripheralManager?.updateValue(data, for: char, onSubscribedCentrals: nil) ?? false\n if success {\n sentToCentrals = subscribedCentrals.count\n }\n } else if sentToPeripherals > 0 && !subscribedCentrals.isEmpty {\n // Skip central broadcast - already sent via peripherals\n }\n \n // If no peers received the message, add to retry queue ONLY if it's our own message\n if sentToPeripherals == 0 && sentToCentrals == 0 {\n // Check if this packet originated from us\n let senderID = packet.senderID.hexEncodedString()\n if senderID == self.myPeerID {\n // This is our own message that failed to send\n if packet.type == MessageType.message.rawValue,\n let message = BitchatMessage.fromBinaryPayload(packet.payload) {\n MessageRetryService.shared.addMessageForRetry(\n content: message.content,\n mentions: message.mentions,\n isPrivate: message.isPrivate,\n recipientPeerID: nil,\n recipientNickname: message.recipientNickname,\n originalMessageID: message.id,\n originalTimestamp: message.timestamp\n )\n }\n }\n }\n }\n \n private func handleReceivedPacket(_ packet: BitchatPacket, from peerID: String, peripheral: CBPeripheral? = nil) {\n messageQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n // Track that we heard from this peer\n let senderID = packet.senderID.hexEncodedString()\n if !senderID.isEmpty && senderID != self.myPeerID {\n // Update peer availability\n self.updatePeerAvailability(senderID)\n \n // IMPORTANT: Update peripheral mapping for ALL message types including handshakes\n // This ensures disconnect messages work even if peer disconnects right after handshake\n if let peripheral = peripheral {\n let peripheralID = peripheral.identifier.uuidString\n \n // Check if we need to update the mapping\n if peerIDByPeripheralID[peripheralID] != senderID {\n SecureLogger.log(\"Updating peripheral mapping: \\(peripheralID) -> \\(senderID)\", \n category: SecureLogger.session, level: .debug)\n peerIDByPeripheralID[peripheralID] = senderID\n \n // Also ensure connectedPeripherals has the correct mapping\n // Remove any temp ID mapping if it exists\n let tempIDToRemove = connectedPeripherals.first(where: { $0.value == peripheral && $0.key != senderID })?.key\n if let tempID = tempIDToRemove {\n connectedPeripherals.removeValue(forKey: tempID)\n }\n connectedPeripherals[senderID] = peripheral\n }\n }\n \n // Check if this is a reconnection after a long silence\n let wasReconnection: Bool\n if let lastHeard = self.lastHeardFromPeer[senderID] {\n let timeSinceLastHeard = Date().timeIntervalSince(lastHeard)\n wasReconnection = timeSinceLastHeard > 30.0\n } else {\n // First time hearing from this peer\n wasReconnection = true\n }\n \n self.lastHeardFromPeer[senderID] = Date()\n \n // If this is a reconnection, send our identity announcement\n if wasReconnection && packet.type != MessageType.noiseIdentityAnnounce.rawValue {\n SecureLogger.log(\"Detected reconnection from \\(senderID) after silence, sending identity announcement\", category: SecureLogger.noise, level: .info)\n DispatchQueue.main.async { [weak self] in\n self?.sendNoiseIdentityAnnounce(to: senderID)\n }\n }\n }\n \n \n // Log specific Noise packet types\n \n guard packet.ttl > 0 else { \n return \n }\n \n // Validate packet has payload\n guard !packet.payload.isEmpty else {\n return\n }\n \n // Update last seen timestamp for this peer\n if senderID != \"unknown\" && senderID != self.myPeerID {\n peerLastSeenTimestamps.set(senderID, value: Date())\n }\n \n // Replay attack protection: Check timestamp is within reasonable window (5 minutes)\n let currentTime = UInt64(Date().timeIntervalSince1970 * 1000) // milliseconds\n let timeDiff = abs(Int64(currentTime) - Int64(packet.timestamp))\n if timeDiff > 300000 { // 5 minutes in milliseconds\n SecureLogger.log(\"Replay attack detected - timestamp from \\(senderID)\", category: SecureLogger.security, level: .warning)\n SecureLogger.log(\"Dropped message with stale timestamp. Age: \\(timeDiff/1000)s from \\(senderID)\", category: SecureLogger.security, level: .warning)\n return\n }\n \n // Log message type for debugging\n let messageTypeName: String\n switch MessageType(rawValue: packet.type) {\n case .message:\n messageTypeName = \"MESSAGE\"\n case .protocolAck:\n messageTypeName = \"PROTOCOL_ACK\"\n case .protocolNack:\n messageTypeName = \"PROTOCOL_NACK\"\n case .noiseHandshakeInit:\n messageTypeName = \"NOISE_HANDSHAKE_INIT\"\n case .noiseHandshakeResp:\n messageTypeName = \"NOISE_HANDSHAKE_RESP\"\n case .noiseIdentityAnnounce:\n messageTypeName = \"NOISE_IDENTITY_ANNOUNCE\"\n case .noiseEncrypted:\n messageTypeName = \"NOISE_ENCRYPTED\"\n case .leave:\n messageTypeName = \"LEAVE\"\n case .readReceipt:\n messageTypeName = \"READ_RECEIPT\"\n case .versionHello:\n messageTypeName = \"VERSION_HELLO\"\n case .versionAck:\n messageTypeName = \"VERSION_ACK\"\n case .systemValidation:\n messageTypeName = \"SYSTEM_VALIDATION\"\n case .handshakeRequest:\n messageTypeName = \"HANDSHAKE_REQUEST\"\n default:\n messageTypeName = \"UNKNOWN(\\(packet.type))\"\n }\n \n // Processing packet\n \n // Rate limiting check with message type awareness\n let isHighPriority = [MessageType.protocolAck.rawValue,\n MessageType.protocolNack.rawValue,\n MessageType.noiseHandshakeInit.rawValue,\n MessageType.noiseHandshakeResp.rawValue,\n MessageType.noiseIdentityAnnounce.rawValue,\n MessageType.leave.rawValue].contains(packet.type)\n \n \n if senderID != self.myPeerID && isRateLimited(peerID: senderID, messageType: packet.type) {\n if !isHighPriority {\n SecureLogger.log(\"RATE_LIMITED: Dropped \\(messageTypeName) from \\(senderID)\", \n category: SecureLogger.security, level: .warning)\n return\n } else {\n SecureLogger.log(\"RATE_LIMITED: Allowing high-priority \\(messageTypeName) from \\(senderID)\", \n category: SecureLogger.security, level: .info)\n }\n }\n \n // Record message for rate limiting based on type\n if senderID != self.myPeerID && !isHighPriority {\n recordMessage(from: senderID, messageType: packet.type)\n }\n \n // Content-based duplicate detection using packet ID\n let messageID = generatePacketID(for: packet)\n \n // Check if we've seen this exact message before\n processedMessagesLock.lock()\n if let existingState = processedMessages[messageID] {\n // Update the state\n var updatedState = existingState\n updatedState.updateSeen()\n processedMessages[messageID] = updatedState\n processedMessagesLock.unlock()\n \n SecureLogger.log(\"Dropped duplicate message from \\(senderID) (seen \\(updatedState.seenCount) times)\", category: SecureLogger.security, level: .debug)\n // Cancel any pending relay for this message\n cancelPendingRelay(messageID: messageID)\n return\n }\n processedMessagesLock.unlock()\n \n // Use bloom filter for efficient duplicate detection\n if messageBloomFilter.contains(messageID) {\n // Double check with exact set (bloom filter can have false positives)\n processedMessagesLock.lock()\n let isProcessed = processedMessages[messageID] != nil\n processedMessagesLock.unlock()\n if !isProcessed {\n SecureLogger.log(\"Bloom filter false positive for message: \\(messageID)\", category: SecureLogger.security, level: .debug)\n }\n }\n \n // Record this message as processed\n messageBloomFilter.insert(messageID)\n processedMessagesLock.lock()\n processedMessages[messageID] = MessageState(\n firstSeen: Date(),\n lastSeen: Date(),\n seenCount: 1,\n relayed: false,\n acknowledged: false\n )\n \n // Prune old entries if needed\n if processedMessages.count > maxProcessedMessages {\n // Remove oldest entries\n let sortedByFirstSeen = processedMessages.sorted { $0.value.firstSeen < $1.value.firstSeen }\n let toRemove = sortedByFirstSeen.prefix(processedMessages.count - maxProcessedMessages + 1000)\n for (key, _) in toRemove {\n processedMessages.removeValue(forKey: key)\n }\n }\n processedMessagesLock.unlock()\n \n \n // Log statistics periodically\n if messageBloomFilter.insertCount % 100 == 0 {\n _ = messageBloomFilter.estimatedFalsePositiveRate\n }\n \n // Bloom filter will be reset by timer, processedMessages is now bounded\n \n // let _ = packet.senderID.hexEncodedString()\n \n \n // Note: We'll decode messages in the switch statement below, not here\n \n switch MessageType(rawValue: packet.type) {\n case .message:\n // Unified message handler for both broadcast and private messages\n // Convert binary senderID back to hex string\n let senderID = packet.senderID.hexEncodedString()\n if senderID.isEmpty {\n return\n }\n \n \n // Ignore our own messages\n if senderID == myPeerID {\n return\n }\n \n // Check if this is a broadcast or private message\n if let recipientID = packet.recipientID {\n if recipientID == SpecialRecipients.broadcast {\n // BROADCAST MESSAGE\n \n // No signature verification - broadcasts are not authenticated\n \n // Parse broadcast message (not encrypted)\n if let message = BitchatMessage.fromBinaryPayload(packet.payload) {\n \n // Store nickname mapping\n collectionsQueue.sync(flags: .barrier) {\n self.peerNicknames[senderID] = message.sender\n }\n \n let finalContent = message.content\n \n let messageWithPeerID = BitchatMessage(\n id: message.id, // Preserve the original message ID\n sender: message.sender,\n content: finalContent,\n timestamp: message.timestamp,\n isRelay: message.isRelay,\n originalSender: message.originalSender,\n isPrivate: false,\n recipientNickname: nil,\n senderPeerID: senderID,\n mentions: message.mentions\n )\n \n // Track last message time from this peer\n let peerID = packet.senderID.hexEncodedString()\n self.lastMessageFromPeer.set(peerID, value: Date())\n \n DispatchQueue.main.async {\n self.delegate?.didReceiveMessage(messageWithPeerID)\n }\n \n }\n \n // Relay broadcast messages\n var relayPacket = packet\n relayPacket.ttl -= 1\n if relayPacket.ttl > 0 {\n // RSSI-based relay probability\n let rssiValue = peerRSSI[senderID]?.intValue ?? -70\n let relayProb = self.calculateRelayProbability(baseProb: self.adaptiveRelayProbability, rssi: rssiValue)\n \n // Relay based on probability only - no TTL boost if base probability is 0\n let effectiveProb = relayProb > 0 ? relayProb : 0.0\n let shouldRelay = effectiveProb > 0 && Double.random(in: 0...1) < effectiveProb\n \n if shouldRelay {\n // Relaying broadcast\n // High priority messages relay immediately, others use exponential delay\n if self.isHighPriorityMessage(type: relayPacket.type) {\n self.broadcastPacket(relayPacket)\n } else {\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n } else {\n // Dropped broadcast relay\n }\n }\n \n } else if isPeerIDOurs(recipientID.hexEncodedString()) {\n // PRIVATE MESSAGE FOR US\n \n \n // No signature verification - broadcasts are not authenticated\n \n // Private messages should only come through Noise now\n // If we're getting a private message here, it must already be decrypted from Noise\n let decryptedPayload = packet.payload\n \n // Parse the message\n if let message = BitchatMessage.fromBinaryPayload(decryptedPayload) {\n \n // Check if this is a dummy message for cover traffic\n if message.content.hasPrefix(self.coverTrafficPrefix) {\n return // Silently discard dummy messages\n }\n \n // Check if we've seen this exact message recently (within 5 seconds)\n let messageKey = \"\\(senderID)-\\(message.content)-\\(message.timestamp)\"\n if let lastReceived = self.receivedMessageTimestamps.get(messageKey) {\n let timeSinceLastReceived = Date().timeIntervalSince(lastReceived)\n if timeSinceLastReceived < 5.0 {\n }\n }\n self.receivedMessageTimestamps.set(messageKey, value: Date())\n \n // LRU cache handles cleanup automatically\n \n collectionsQueue.sync(flags: .barrier) {\n if self.peerNicknames[senderID] == nil {\n self.peerNicknames[senderID] = message.sender\n }\n }\n \n let messageWithPeerID = BitchatMessage(\n id: message.id, // Preserve the original message ID\n sender: message.sender,\n content: message.content,\n timestamp: message.timestamp,\n isRelay: message.isRelay,\n originalSender: message.originalSender,\n isPrivate: message.isPrivate,\n recipientNickname: message.recipientNickname,\n senderPeerID: senderID,\n mentions: message.mentions,\n deliveryStatus: nil // Will be set to .delivered in ChatViewModel\n )\n \n // Track last message time from this peer\n let peerID = packet.senderID.hexEncodedString()\n self.lastMessageFromPeer.set(peerID, value: Date())\n \n DispatchQueue.main.async {\n self.delegate?.didReceiveMessage(messageWithPeerID)\n }\n \n // Generate and send ACK for private messages\n let viewModel = self.delegate as? ChatViewModel\n let myNickname = viewModel?.nickname ?? self.myPeerID\n if let ack = DeliveryTracker.shared.generateAck(\n for: messageWithPeerID,\n myPeerID: self.myPeerID,\n myNickname: myNickname,\n hopCount: UInt8(self.maxTTL - packet.ttl)\n ) {\n self.sendDeliveryAck(ack, to: senderID)\n }\n } else {\n SecureLogger.log(\"Failed to parse private message from binary, size: \\(decryptedPayload.count)\", category: SecureLogger.encryption, level: .error)\n }\n \n } else if packet.ttl > 0 {\n // RELAY PRIVATE MESSAGE (not for us)\n var relayPacket = packet\n relayPacket.ttl -= 1\n \n // Check if this message is for an offline favorite and cache it\n let recipientIDString = recipientID.hexEncodedString()\n if let fingerprint = self.noiseService.getPeerFingerprint(recipientIDString) {\n // Only cache if recipient is a favorite AND is currently offline\n if (self.delegate?.isFavorite(fingerprint: fingerprint) ?? false) && !self.activePeers.contains(recipientIDString) {\n self.cacheMessage(relayPacket, messageID: messageID)\n }\n }\n \n // Private messages are important - use RSSI-based relay with boost\n let rssiValue = peerRSSI[senderID]?.intValue ?? -70\n let baseProb = min(self.adaptiveRelayProbability + 0.15, 1.0) // Boost by 15%\n let relayProb = self.calculateRelayProbability(baseProb: baseProb, rssi: rssiValue)\n \n // Relay based on probability only - no forced relay for small networks\n let shouldRelay = Double.random(in: 0...1) < relayProb\n \n if shouldRelay {\n // High priority messages relay immediately, others use exponential delay\n if self.isHighPriorityMessage(type: relayPacket.type) {\n self.broadcastPacket(relayPacket)\n } else {\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n }\n } else {\n // Message has recipient ID but not for us and TTL is 0\n // Message not for us - will be relayed if TTL > 0\n }\n } else {\n // No recipient ID - this shouldn't happen for messages\n SecureLogger.log(\"Message packet with no recipient ID from \\(senderID)\", category: SecureLogger.security, level: .warning)\n }\n \n // Note: 0x02 was legacy keyExchange - removed\n \n case .announce:\n if let rawNickname = String(data: packet.payload, encoding: .utf8) {\n // Trim whitespace from received nickname\n let nickname = rawNickname.trimmingCharacters(in: .whitespacesAndNewlines)\n let senderID = packet.senderID.hexEncodedString()\n \n SecureLogger.log(\"handleReceivedPacket: Received announce from \\(senderID), peripheral is \\(peripheral != nil ? \"present\" : \"nil\")\", category: SecureLogger.session, level: .debug)\n \n // Ignore if it's from ourselves (including previous peer IDs)\n if isPeerIDOurs(senderID) {\n return\n }\n \n // Check if we've already announced this peer\n let isFirstAnnounce = !announcedPeers.contains(senderID)\n \n // Clean up stale peer IDs with the same nickname\n collectionsQueue.sync(flags: .barrier) {\n var stalePeerIDs: [String] = []\n for (existingPeerID, existingNickname) in self.peerNicknames {\n if existingNickname == nickname && existingPeerID != senderID {\n // Check if this peer was seen very recently (within 10 seconds)\n let wasRecentlySeen = self.peerLastSeenTimestamps.get(existingPeerID).map { Date().timeIntervalSince($0) < 10.0 } ?? false\n if !wasRecentlySeen {\n // Found a stale peer ID with the same nickname\n stalePeerIDs.append(existingPeerID)\n // Found stale peer ID\n } else {\n // Peer was seen recently, keeping both\n }\n }\n }\n \n // Remove stale peer IDs\n for stalePeerID in stalePeerIDs {\n // Removing stale peer\n self.peerNicknames.removeValue(forKey: stalePeerID)\n \n // Also remove from active peers\n self.activePeers.remove(stalePeerID)\n \n // Remove from announced peers\n self.announcedPeers.remove(stalePeerID)\n self.announcedToPeers.remove(stalePeerID)\n \n // Clear tracking data\n self.lastHeardFromPeer.removeValue(forKey: stalePeerID)\n \n // Disconnect any peripherals associated with stale ID\n if let peripheral = self.connectedPeripherals[stalePeerID] {\n self.intentionalDisconnects.insert(peripheral.identifier.uuidString)\n self.centralManager?.cancelPeripheralConnection(peripheral)\n self.connectedPeripherals.removeValue(forKey: stalePeerID)\n self.peripheralCharacteristics.removeValue(forKey: peripheral)\n }\n \n // Remove RSSI data\n self.peerRSSI.removeValue(forKey: stalePeerID)\n \n // Clear cached messages tracking\n self.cachedMessagesSentToPeer.remove(stalePeerID)\n \n // Remove from last seen timestamps\n self.peerLastSeenTimestamps.remove(stalePeerID)\n \n // No longer tracking key exchanges\n }\n \n // If we had stale peers, notify the UI immediately\n if !stalePeerIDs.isEmpty {\n DispatchQueue.main.async { [weak self] in\n self?.notifyPeerListUpdate(immediate: true)\n }\n }\n \n // Now add the new peer ID with the nickname\n self.peerNicknames[senderID] = nickname\n }\n \n // Update peripheral mapping if we have it\n // If peripheral is nil (e.g., from relay), try to find it\n var peripheralToUpdate = peripheral\n if peripheralToUpdate == nil {\n // Look for any peripheral that might be this peer\n // First check if we already have a mapping for this peer ID\n peripheralToUpdate = self.connectedPeripherals[senderID]\n \n if peripheralToUpdate == nil {\n SecureLogger.log(\"handleReceivedPacket: No peripheral passed and no existing mapping for \\(senderID)\", category: SecureLogger.session, level: .debug)\n \n // Try to find an unidentified peripheral that might be this peer\n // This handles case where announce is relayed and we need to update RSSI mapping\n var unmappedPeripherals: [(String, CBPeripheral)] = []\n for (tempID, peripheral) in self.connectedPeripherals {\n // Check if this is a temp ID (UUID format, not a peer ID)\n if tempID.count == 36 && tempID.contains(\"-\") { // UUID length with dashes\n unmappedPeripherals.append((tempID, peripheral))\n SecureLogger.log(\"handleReceivedPacket: Found unmapped peripheral with temp ID \\(tempID)\", category: SecureLogger.session, level: .debug)\n }\n }\n \n // If we have exactly one unmapped peripheral, it's likely this one\n if unmappedPeripherals.count == 1 {\n let (tempID, peripheral) = unmappedPeripherals[0]\n SecureLogger.log(\"handleReceivedPacket: Single unmapped peripheral \\(tempID), mapping to \\(senderID)\", category: SecureLogger.session, level: .info)\n peripheralToUpdate = peripheral\n \n // Remove temp mapping and add real mapping\n self.connectedPeripherals.removeValue(forKey: tempID)\n self.connectedPeripherals[senderID] = peripheral\n \n // Transfer RSSI if available\n if let rssi = self.peripheralRSSI[tempID] {\n self.peripheralRSSI.removeValue(forKey: tempID)\n self.peripheralRSSI[senderID] = rssi\n self.peerRSSI[senderID] = rssi\n }\n \n // Also check the peripheral's UUID-based RSSI\n let peripheralUUID = peripheral.identifier.uuidString\n if peripheralUUID == tempID && peripheralRSSI[peripheralUUID] != nil {\n // Already handled above\n } else if let rssi = self.peripheralRSSI[peripheralUUID] {\n self.peerRSSI[senderID] = rssi\n }\n } else if unmappedPeripherals.count > 1 {\n SecureLogger.log(\"handleReceivedPacket: Multiple unmapped peripherals (\\(unmappedPeripherals.count)), cannot determine which is \\(senderID)\", category: SecureLogger.session, level: .debug)\n // TODO: Could use timing heuristics or other methods to match\n }\n }\n }\n \n if let peripheral = peripheralToUpdate {\n let peripheralID = peripheral.identifier.uuidString\n SecureLogger.log(\"Updating peripheral \\(peripheralID) mapping to peer ID \\(senderID)\", \n category: SecureLogger.session, level: .info)\n \n // Update simplified mapping\n updatePeripheralMapping(peripheralID: peripheralID, peerID: senderID)\n \n // Find and remove any temp ID mapping for this peripheral\n var tempIDToRemove: String? = nil\n for (id, per) in self.connectedPeripherals {\n if per == peripheral && id != senderID && id == peripheralID {\n tempIDToRemove = id\n break\n }\n }\n \n if let tempID = tempIDToRemove {\n // RSSI transfer is handled by updatePeripheralMapping\n self.peripheralRSSI.removeValue(forKey: tempID)\n \n // IMPORTANT: Remove old peer ID from activePeers to prevent duplicates\n collectionsQueue.sync(flags: .barrier) {\n if self.activePeers.contains(tempID) {\n _ = self.activePeers.remove(tempID)\n }\n }\n \n // Don't notify about disconnect - this is just cleanup of temporary ID\n } else {\n SecureLogger.log(\"handleReceivedPacket: No temp ID found for peripheral, directly mapping \\(senderID)\", category: SecureLogger.session, level: .debug)\n // No temp ID found, just add the mapping\n self.connectedPeripherals[senderID] = peripheral\n self.peerIDByPeripheralID[peripheral.identifier.uuidString] = senderID\n \n // Check if RSSI is stored under peripheral UUID and transfer it\n let peripheralUUID = peripheral.identifier.uuidString\n if let peripheralStoredRSSI = self.peripheralRSSI[peripheralUUID] {\n self.peerRSSI[senderID] = peripheralStoredRSSI\n }\n }\n }\n \n // Add to active peers if not already there\n if senderID != \"unknown\" && senderID != self.myPeerID {\n // Check for duplicate nicknames and remove old peer IDs\n collectionsQueue.sync(flags: .barrier) {\n // Find any existing peers with the same nickname\n var oldPeerIDsToRemove: [String] = []\n for existingPeerID in self.activePeers {\n if existingPeerID != senderID {\n let existingNickname = self.peerNicknames[existingPeerID] ?? \"\"\n if existingNickname == nickname && !existingNickname.isEmpty && existingNickname != \"unknown\" {\n oldPeerIDsToRemove.append(existingPeerID)\n }\n }\n }\n \n // Remove old peer IDs with same nickname\n for oldPeerID in oldPeerIDsToRemove {\n self.activePeers.remove(oldPeerID)\n self.peerNicknames.removeValue(forKey: oldPeerID)\n self.connectedPeripherals.removeValue(forKey: oldPeerID)\n \n // Don't notify about disconnect - this is just cleanup of duplicate\n }\n }\n \n let wasInserted = collectionsQueue.sync(flags: .barrier) {\n // Final safety check\n if senderID == self.myPeerID {\n SecureLogger.log(\"Blocked self from being added to activePeers\", category: SecureLogger.noise, level: .error)\n return false\n }\n let result = self.activePeers.insert(senderID).inserted\n return result\n }\n if wasInserted {\n SecureLogger.log(\"📡 Peer joined network: \\(senderID) (\\(nickname))\", category: SecureLogger.session, level: .info)\n }\n \n // Show join message only for first announce AND if we actually added the peer\n if isFirstAnnounce && wasInserted {\n announcedPeers.insert(senderID)\n \n // Delay the connect message slightly to allow identity announcement to be processed\n // This helps ensure fingerprint mappings are available for nickname resolution\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {\n self.delegate?.didConnectToPeer(senderID)\n }\n self.notifyPeerListUpdate(immediate: true)\n \n // Send network available notification if appropriate\n let currentNetworkSize = collectionsQueue.sync { self.activePeers.count }\n if currentNetworkSize > 0 {\n // Clear empty time since network is active\n networkBecameEmptyTime = nil\n \n if !hasNotifiedNetworkAvailable {\n // Check if enough time has passed since last notification\n let now = Date()\n var shouldSendNotification = true\n \n if let lastNotification = lastNetworkNotificationTime {\n let timeSinceLastNotification = now.timeIntervalSince(lastNotification)\n if timeSinceLastNotification < networkNotificationCooldown {\n // Too soon to send another notification\n shouldSendNotification = false\n }\n }\n \n if shouldSendNotification {\n hasNotifiedNetworkAvailable = true\n lastNetworkNotificationTime = now\n NotificationService.shared.sendNetworkAvailableNotification(peerCount: currentNetworkSize)\n }\n }\n }\n \n DispatchQueue.main.async {\n // Check if this is a favorite peer and send notification\n // Note: This might not work immediately if key exchange hasn't happened yet\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n guard let self = self else { return }\n \n // Check if this is a favorite using their public key fingerprint\n if let fingerprint = self.noiseService.getPeerFingerprint(senderID) {\n if self.delegate?.isFavorite(fingerprint: fingerprint) ?? false {\n NotificationService.shared.sendFavoriteOnlineNotification(nickname: nickname)\n \n // Send any cached messages for this favorite\n self.sendCachedMessages(to: senderID)\n }\n }\n }\n }\n } else {\n // Just update the peer list\n self.notifyPeerListUpdate()\n }\n }\n \n // Relay announce if TTL > 0\n if packet.ttl > 1 {\n var relayPacket = packet\n relayPacket.ttl -= 1\n \n // Add small delay to prevent collision\n let delay = Double.random(in: 0.1...0.3)\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n }\n \n case .leave:\n let senderID = packet.senderID.hexEncodedString()\n // Legacy peer disconnect (keeping for backwards compatibility)\n if String(data: packet.payload, encoding: .utf8) != nil {\n // Remove from active peers with proper locking\n collectionsQueue.sync(flags: .barrier) {\n let wasRemoved = self.activePeers.remove(senderID) != nil\n let nickname = self.peerNicknames.removeValue(forKey: senderID) ?? \"unknown\"\n \n if wasRemoved {\n // Mark as gracefully left to prevent duplicate disconnect message\n self.gracefullyLeftPeers.insert(senderID)\n self.gracefulLeaveTimestamps[senderID] = Date()\n \n SecureLogger.log(\"📴 Peer left network: \\(senderID) (\\(nickname)) - marked as gracefully left\", category: SecureLogger.session, level: .info)\n }\n }\n \n announcedPeers.remove(senderID)\n \n // Show disconnect message immediately when peer leaves\n DispatchQueue.main.async {\n self.delegate?.didDisconnectFromPeer(senderID)\n }\n self.notifyPeerListUpdate()\n }\n \n case .fragmentStart, .fragmentContinue, .fragmentEnd:\n // let fragmentTypeStr = packet.type == MessageType.fragmentStart.rawValue ? \"START\" : \n // (packet.type == MessageType.fragmentContinue.rawValue ? \"CONTINUE\" : \"END\")\n \n // Validate fragment has minimum required size\n if packet.payload.count < 13 {\n return\n }\n \n handleFragment(packet, from: peerID)\n \n // Relay fragments if TTL > 0\n var relayPacket = packet\n relayPacket.ttl -= 1\n if relayPacket.ttl > 0 {\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n \n \n case .deliveryAck:\n // Handle delivery acknowledgment\n if let recipientIDData = packet.recipientID,\n isPeerIDOurs(recipientIDData.hexEncodedString()) {\n // This ACK is for us\n let senderID = packet.senderID.hexEncodedString()\n // Check if payload is already decrypted (came through Noise)\n if let ack = DeliveryAck.fromBinaryData(packet.payload) {\n // Already decrypted - process directly\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n } else if let ack = DeliveryAck.decode(from: packet.payload) {\n // Fallback to JSON for backward compatibility\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n } else {\n // Try legacy decryption\n do {\n let decryptedData = try noiseService.decrypt(packet.payload, from: senderID)\n if let ack = DeliveryAck.fromBinaryData(decryptedData) {\n // Process the ACK\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n } else if let ack = DeliveryAck.decode(from: decryptedData) {\n // Fallback to JSON\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n }\n } catch {\n SecureLogger.log(\"Failed to decrypt delivery ACK from \\(senderID): \\(error)\", \n category: SecureLogger.encryption, level: .error)\n }\n }\n } else if packet.ttl > 0 {\n // Relay the ACK if not for us\n \n // SAFETY CHECK: Never relay unencrypted JSON\n if let jsonCheck = String(data: packet.payload.prefix(1), encoding: .utf8), jsonCheck == \"{\" {\n return\n }\n \n var relayPacket = packet\n relayPacket.ttl -= 1\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n \n case .readReceipt:\n // Handle read receipt\n if let recipientIDData = packet.recipientID,\n isPeerIDOurs(recipientIDData.hexEncodedString()) {\n // This read receipt is for us\n let senderID = packet.senderID.hexEncodedString()\n // Received read receipt\n // Check if payload is already decrypted (came through Noise)\n if let receipt = ReadReceipt.fromBinaryData(packet.payload) {\n // Already decrypted - process directly\n // Processing read receipt\n DispatchQueue.main.async {\n self.delegate?.didReceiveReadReceipt(receipt)\n }\n } else if let receipt = ReadReceipt.decode(from: packet.payload) {\n // Fallback to JSON for backward compatibility\n // Processing read receipt (JSON)\n DispatchQueue.main.async {\n self.delegate?.didReceiveReadReceipt(receipt)\n }\n } else {\n // Try legacy decryption\n do {\n let decryptedData = try noiseService.decrypt(packet.payload, from: senderID)\n if let receipt = ReadReceipt.fromBinaryData(decryptedData) {\n // Process the read receipt\n DispatchQueue.main.async {\n self.delegate?.didReceiveReadReceipt(receipt)\n }\n } else if let receipt = ReadReceipt.decode(from: decryptedData) {\n // Fallback to JSON\n DispatchQueue.main.async {\n self.delegate?.didReceiveReadReceipt(receipt)\n }\n }\n } catch {\n // Failed to decrypt read receipt - might be from unknown sender\n }\n }\n } else if packet.ttl > 0 {\n // Relay the read receipt if not for us\n var relayPacket = packet\n relayPacket.ttl -= 1\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n \n case .noiseIdentityAnnounce:\n // Handle Noise identity announcement\n let senderID = packet.senderID.hexEncodedString()\n \n // Check if this identity announce is targeted to someone else\n if let recipientID = packet.recipientID,\n !isPeerIDOurs(recipientID.hexEncodedString()) {\n // Not for us, relay if TTL > 0\n if packet.ttl > 0 {\n // Relay identity announce\n var relayPacket = packet\n relayPacket.ttl -= 1\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n return\n }\n \n // Special duplicate detection for identity announces\n processedMessagesLock.lock()\n if let lastSeenTime = recentIdentityAnnounces[senderID] {\n let timeSince = Date().timeIntervalSince(lastSeenTime)\n if timeSince < identityAnnounceDuplicateWindow {\n processedMessagesLock.unlock()\n SecureLogger.log(\"Dropped duplicate identity announce from \\(senderID) (last seen \\(timeSince)s ago)\", \n category: SecureLogger.security, level: .debug)\n return\n }\n }\n recentIdentityAnnounces[senderID] = Date()\n processedMessagesLock.unlock()\n \n if senderID != myPeerID && !isPeerIDOurs(senderID) {\n // Create defensive copy and validate\n let payloadCopy = Data(packet.payload)\n \n guard !payloadCopy.isEmpty else {\n SecureLogger.log(\"Received empty NoiseIdentityAnnouncement from \\(senderID)\", category: SecureLogger.noise, level: .error)\n return\n }\n \n // Decode the announcement\n let announcement: NoiseIdentityAnnouncement?\n if let firstByte = payloadCopy.first, firstByte == 0x7B { // '{' character - JSON\n announcement = NoiseIdentityAnnouncement.decode(from: payloadCopy) ?? NoiseIdentityAnnouncement.fromBinaryData(payloadCopy)\n } else {\n announcement = NoiseIdentityAnnouncement.fromBinaryData(payloadCopy) ?? NoiseIdentityAnnouncement.decode(from: payloadCopy)\n }\n \n guard let announcement = announcement else {\n SecureLogger.log(\"Failed to decode NoiseIdentityAnnouncement from \\(senderID), size: \\(payloadCopy.count)\", category: SecureLogger.noise, level: .error)\n return\n }\n \n // Verify the signature using the signing public key\n let timestampData = String(Int64(announcement.timestamp.timeIntervalSince1970 * 1000)).data(using: .utf8)!\n let bindingData = announcement.peerID.data(using: .utf8)! + announcement.publicKey + timestampData\n if !noiseService.verifySignature(announcement.signature, for: bindingData, publicKey: announcement.signingPublicKey) {\n SecureLogger.log(\"Signature verification failed for \\(senderID)\", category: SecureLogger.noise, level: .warning)\n return // Reject announcements with invalid signatures\n }\n \n // Calculate fingerprint from public key\n let hash = SHA256.hash(data: announcement.publicKey)\n let fingerprint = hash.map { String(format: \"%02x\", $0) }.joined()\n \n // Log receipt of identity announce\n SecureLogger.log(\"Received identity announce from \\(announcement.peerID) (\\(announcement.nickname))\", \n category: SecureLogger.noise, level: .info)\n \n // Create the binding\n let binding = PeerIdentityBinding(\n currentPeerID: announcement.peerID,\n fingerprint: fingerprint,\n publicKey: announcement.publicKey,\n signingPublicKey: announcement.signingPublicKey,\n nickname: announcement.nickname,\n bindingTimestamp: announcement.timestamp,\n signature: announcement.signature\n )\n \n SecureLogger.log(\"Creating identity binding for \\(announcement.peerID) -> \\(fingerprint)\", category: SecureLogger.security, level: .info)\n \n // Handle peer ID rotation if previousPeerID is provided\n if let previousID = announcement.previousPeerID, previousID != announcement.peerID {\n SecureLogger.log(\"Peer announced rotation from \\(previousID) to \\(announcement.peerID)\", \n category: SecureLogger.security, level: .info)\n \n // Transfer states from previous ID\n collectionsQueue.sync(flags: .barrier) {\n // Transfer gracefullyLeft state\n if self.gracefullyLeftPeers.contains(previousID) {\n self.gracefullyLeftPeers.remove(previousID)\n self.gracefullyLeftPeers.insert(announcement.peerID)\n }\n \n // Clean up the old peer ID from active peers\n if self.activePeers.contains(previousID) {\n self.activePeers.remove(previousID)\n // Don't add new ID yet - let normal flow handle it\n }\n }\n }\n \n // Update our mappings\n updatePeerBinding(announcement.peerID, fingerprint: fingerprint, binding: binding)\n \n // Update connection state only if we're not already authenticated\n let currentState = peerConnectionStates[announcement.peerID] ?? .disconnected\n if currentState != .authenticated {\n updatePeerConnectionState(announcement.peerID, state: .connected)\n }\n \n // Register the peer's public key with ChatViewModel for verification tracking\n DispatchQueue.main.async { [weak self] in\n (self?.delegate as? ChatViewModel)?.registerPeerPublicKey(peerID: announcement.peerID, publicKeyData: announcement.publicKey)\n }\n \n // Lazy handshake: No longer initiate handshake on identity announcement\n // Just respond with our own identity announcement\n if !noiseService.hasEstablishedSession(with: announcement.peerID) {\n // Send our identity back so they know we're here\n SecureLogger.log(\"Responding to identity announce from \\(announcement.peerID) with our own (lazy handshake mode)\", \n category: SecureLogger.noise, level: .info)\n sendNoiseIdentityAnnounce(to: announcement.peerID)\n } else {\n // We already have a session, ensure ChatViewModel knows about the fingerprint\n // This handles the case where handshake completed before identity announcement\n DispatchQueue.main.async { [weak self] in\n if let publicKeyData = self?.noiseService.getPeerPublicKeyData(announcement.peerID) {\n (self?.delegate as? ChatViewModel)?.registerPeerPublicKey(peerID: announcement.peerID, publicKeyData: publicKeyData)\n }\n }\n }\n }\n \n case .noiseHandshakeInit:\n // Handle incoming Noise handshake initiation\n let senderID = packet.senderID.hexEncodedString()\n SecureLogger.logHandshake(\"initiation received\", peerID: senderID, success: true)\n \n // Check if this handshake is for us or broadcast\n if let recipientID = packet.recipientID,\n !isPeerIDOurs(recipientID.hexEncodedString()) {\n // Not for us, relay if TTL > 0\n if packet.ttl > 0 {\n // Relay handshake init\n var relayPacket = packet\n relayPacket.ttl -= 1\n broadcastPacket(relayPacket)\n }\n return\n }\n if !isPeerIDOurs(senderID) {\n // Check if we already have an established session\n if noiseService.hasEstablishedSession(with: senderID) {\n // Determine who should be initiator based on peer ID comparison\n let shouldBeInitiator = myPeerID < senderID\n \n if shouldBeInitiator {\n // We should be initiator but peer is initiating - likely they had a session failure\n SecureLogger.log(\"Received handshake init from \\(senderID) who should be responder - likely session mismatch, clearing and accepting\", category: SecureLogger.noise, level: .warning)\n cleanupPeerCryptoState(senderID)\n } else {\n // Check if we've heard from this peer recently\n let lastHeard = lastHeardFromPeer[senderID] ?? Date.distantPast\n let timeSinceLastHeard = Date().timeIntervalSince(lastHeard)\n \n // Check session validity before clearing\n let lastSuccess = lastSuccessfulMessageTime[senderID] ?? Date.distantPast\n let sessionAge = Date().timeIntervalSince(lastSuccess)\n \n // If the peer is initiating a handshake despite us having a valid session,\n // they must have cleared their session for a good reason (e.g., decryption failure).\n // We should always accept the handshake to re-establish encryption.\n SecureLogger.log(\"Received handshake init from \\(senderID) with existing session (age: \\(Int(sessionAge))s, last heard: \\(Int(timeSinceLastHeard))s ago) - accepting to re-establish encryption\", \n category: SecureLogger.handshake, level: .info)\n cleanupPeerCryptoState(senderID)\n }\n }\n \n // If we have a handshaking session, reset it to allow new handshake\n if noiseService.hasSession(with: senderID) && !noiseService.hasEstablishedSession(with: senderID) {\n SecureLogger.log(\"Received handshake init from \\(senderID) while already handshaking - resetting to allow new handshake\", category: SecureLogger.noise, level: .info)\n cleanupPeerCryptoState(senderID)\n }\n \n // Check if we've completed version negotiation with this peer\n if negotiatedVersions[senderID] == nil {\n // Legacy peer - assume version 1 for backward compatibility\n SecureLogger.log(\"Received Noise handshake from \\(senderID) without version negotiation, assuming v1\", \n category: SecureLogger.session, level: .debug)\n negotiatedVersions[senderID] = 1\n versionNegotiationState[senderID] = .ackReceived(version: 1)\n }\n handleNoiseHandshakeMessage(from: senderID, message: packet.payload, isInitiation: true)\n \n // Send protocol ACK for successfully processed handshake initiation\n sendProtocolAck(for: packet, to: senderID)\n }\n \n case .noiseHandshakeResp:\n // Handle Noise handshake response\n let senderID = packet.senderID.hexEncodedString()\n SecureLogger.logHandshake(\"response received\", peerID: senderID, success: true)\n \n // Check if this handshake response is for us\n if let recipientID = packet.recipientID {\n let recipientIDStr = recipientID.hexEncodedString()\n SecureLogger.log(\"Response targeted to: \\(recipientIDStr), is us: \\(isPeerIDOurs(recipientIDStr))\", category: SecureLogger.noise, level: .debug)\n if !isPeerIDOurs(recipientIDStr) {\n // Not for us, relay if TTL > 0\n if packet.ttl > 0 {\n // Relay handshake response\n var relayPacket = packet\n relayPacket.ttl -= 1\n broadcastPacket(relayPacket)\n }\n return\n }\n }\n \n if !isPeerIDOurs(senderID) {\n // Check our current handshake state\n let currentState = handshakeCoordinator.getHandshakeState(for: senderID)\n SecureLogger.log(\"Processing handshake response from \\(senderID), current state: \\(currentState)\", category: SecureLogger.noise, level: .info)\n \n // Process the response - this could be message 2 or message 3 in the XX pattern\n handleNoiseHandshakeMessage(from: senderID, message: packet.payload, isInitiation: false)\n \n // Send protocol ACK for successfully processed handshake response\n sendProtocolAck(for: packet, to: senderID)\n }\n \n case .noiseEncrypted:\n // Handle Noise encrypted message\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n let recipientID = packet.recipientID?.hexEncodedString() ?? \"\"\n \n // Check if this message is for us\n if isPeerIDOurs(recipientID) {\n // Message is for us, try to decrypt\n handleNoiseEncryptedMessage(from: senderID, encryptedData: packet.payload, originalPacket: packet, peripheral: peripheral)\n } else if packet.ttl > 1 {\n // Message is not for us but has TTL > 1, consider relaying\n // Only relay if we think we might be able to reach the recipient\n \n // Check if recipient is directly connected to us\n let canReachDirectly = connectedPeripherals[recipientID] != nil\n \n // Check if we've seen this recipient recently (might be reachable via relay)\n let seenRecently = collectionsQueue.sync {\n if let lastSeen = self.peerLastSeenTimestamps.get(recipientID) {\n return Date().timeIntervalSince(lastSeen) < 180.0 // Seen in last 3 minutes\n }\n return false\n }\n \n if canReachDirectly || seenRecently {\n // Relay the message with reduced TTL\n var relayPacket = packet\n relayPacket.ttl = min(packet.ttl - 1, 2) // Decrement TTL, max 2 for relayed private messages\n \n SecureLogger.log(\"Relaying private message from \\(senderID) to \\(recipientID) (TTL: \\(relayPacket.ttl))\", \n category: SecureLogger.session, level: .debug)\n \n if canReachDirectly {\n // Send directly to recipient\n _ = sendDirectToRecipient(relayPacket, recipientPeerID: recipientID)\n } else {\n // Use selective relay\n sendViaSelectiveRelay(relayPacket, recipientPeerID: recipientID)\n }\n } else {\n SecureLogger.log(\"Not relaying private message to \\(recipientID) - recipient not reachable\", \n category: SecureLogger.session, level: .debug)\n }\n } else {\n // recipientID is empty or invalid, try to decrypt anyway (backwards compatibility)\n handleNoiseEncryptedMessage(from: senderID, encryptedData: packet.payload, originalPacket: packet, peripheral: peripheral)\n }\n }\n \n case .versionHello:\n // Handle version negotiation hello\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n handleVersionHello(from: senderID, data: packet.payload, peripheral: peripheral)\n }\n \n case .versionAck:\n // Handle version negotiation acknowledgment\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n handleVersionAck(from: senderID, data: packet.payload)\n }\n \n case .protocolAck:\n // Handle protocol-level acknowledgment\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n handleProtocolAck(from: senderID, data: packet.payload)\n }\n \n case .protocolNack:\n // Handle protocol-level negative acknowledgment\n let senderID = packet.senderID.hexEncodedString()\n if let recipientIDData = packet.recipientID,\n isPeerIDOurs(recipientIDData.hexEncodedString())\n && !isPeerIDOurs(senderID) {\n handleProtocolNack(from: senderID, data: packet.payload)\n }\n \n case .systemValidation:\n // Handle system validation ping (for session sync verification)\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n // Try to decrypt the validation ping\n do {\n let decrypted = try noiseService.decrypt(packet.payload, from: senderID)\n SecureLogger.log(\"Successfully validated session with \\(senderID) - ping: \\(String(data: decrypted, encoding: .utf8) ?? \"?\")\", \n category: SecureLogger.session, level: .debug)\n \n // Session is valid, update last successful message time\n lastSuccessfulMessageTime[senderID] = Date()\n } catch {\n // Validation failed - session is out of sync\n SecureLogger.log(\"Session validation failed with \\(senderID): \\(error)\", \n category: SecureLogger.session, level: .warning)\n \n // Send NACK to trigger session re-establishment\n sendProtocolNack(for: packet, to: senderID, \n reason: \"Session validation failed\", \n errorCode: .decryptionFailed)\n }\n }\n \n case .handshakeRequest:\n // Handle handshake request for pending messages\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n handleHandshakeRequest(from: senderID, data: packet.payload)\n }\n \n default:\n break\n }\n }\n }\n \n private func sendFragmentedPacket(_ packet: BitchatPacket) {\n guard let fullData = packet.toBinaryData() else { return }\n \n // Generate a fixed 8-byte fragment ID\n var fragmentID = Data(count: 8)\n fragmentID.withUnsafeMutableBytes { bytes in\n arc4random_buf(bytes.baseAddress, 8)\n }\n \n let fragments = stride(from: 0, to: fullData.count, by: maxFragmentSize).map { offset in\n fullData[offset..> 8) & 0xFF))\n fragmentPayload.append(UInt8(index & 0xFF))\n fragmentPayload.append(UInt8((fragments.count >> 8) & 0xFF))\n fragmentPayload.append(UInt8(fragments.count & 0xFF))\n fragmentPayload.append(packet.type)\n fragmentPayload.append(fragmentData)\n \n let fragmentType: MessageType\n if index == 0 {\n fragmentType = .fragmentStart\n } else if index == fragments.count - 1 {\n fragmentType = .fragmentEnd\n } else {\n fragmentType = .fragmentContinue\n }\n \n let fragmentPacket = BitchatPacket(\n type: fragmentType.rawValue,\n senderID: packet.senderID, // Use original packet's senderID (already Data)\n recipientID: packet.recipientID, // Preserve recipient if any\n timestamp: packet.timestamp, // Use original timestamp\n payload: fragmentPayload,\n signature: nil, // Fragments don't need signatures\n ttl: packet.ttl )\n \n // Send fragments with linear delay\n let totalDelay = Double(index) * delayBetweenFragments\n \n // Send fragments on background queue with calculated delay\n messageQueue.asyncAfter(deadline: .now() + totalDelay) { [weak self] in\n self?.broadcastPacket(fragmentPacket)\n }\n }\n \n let _ = Double(fragments.count - 1) * delayBetweenFragments\n }\n \n private func handleFragment(_ packet: BitchatPacket, from peerID: String) {\n // Handling fragment\n \n guard packet.payload.count >= 13 else { \n return \n }\n \n // Convert to array for safer access\n let payloadArray = Array(packet.payload)\n var offset = 0\n \n // Extract fragment ID as binary data (8 bytes)\n guard payloadArray.count >= 8 else {\n return\n }\n \n let fragmentIDData = Data(payloadArray[0..<8])\n let fragmentID = fragmentIDData.hexEncodedString()\n offset = 8\n \n // Safely extract index\n guard payloadArray.count >= offset + 2 else { \n // Not enough data for index\n return \n }\n let index = Int(payloadArray[offset]) << 8 | Int(payloadArray[offset + 1])\n offset += 2\n \n // Safely extract total\n guard payloadArray.count >= offset + 2 else { \n // Not enough data for total\n return \n }\n let total = Int(payloadArray[offset]) << 8 | Int(payloadArray[offset + 1])\n offset += 2\n \n // Safely extract original type\n guard payloadArray.count >= offset + 1 else { \n // Not enough data for type\n return \n }\n let originalType = payloadArray[offset]\n offset += 1\n \n // Extract fragment data\n let fragmentData: Data\n if payloadArray.count > offset {\n fragmentData = Data(payloadArray[offset...])\n } else {\n fragmentData = Data()\n }\n \n \n // Initialize fragment collection if needed\n if incomingFragments[fragmentID] == nil {\n // Check if we've reached the concurrent session limit\n if incomingFragments.count >= maxConcurrentFragmentSessions {\n // Clean up oldest fragments first\n cleanupOldFragments()\n \n // If still at limit, reject new session to prevent DoS\n if incomingFragments.count >= maxConcurrentFragmentSessions {\n return\n }\n }\n \n incomingFragments[fragmentID] = [:]\n fragmentMetadata[fragmentID] = (originalType, total, Date())\n }\n \n incomingFragments[fragmentID]?[index] = fragmentData\n \n \n // Check if we have all fragments\n if let fragments = incomingFragments[fragmentID],\n fragments.count == total {\n \n // Reassemble the original packet\n var reassembledData = Data()\n for i in 0.. maxFragmentBytes {\n // Remove oldest fragments until under limit\n let sortedFragments = fragmentMetadata.sorted { $0.value.timestamp < $1.value.timestamp }\n for (fragID, _) in sortedFragments {\n incomingFragments.removeValue(forKey: fragID)\n fragmentMetadata.removeValue(forKey: fragID)\n \n // Recalculate total\n totalFragmentBytes = 0\n for (_, fragments) in incomingFragments {\n for (_, data) in fragments {\n totalFragmentBytes += data.count\n }\n }\n \n if totalFragmentBytes <= maxFragmentBytes {\n break\n }\n }\n }\n }\n} // End of BluetoothMeshService class\n\nextension BluetoothMeshService: CBCentralManagerDelegate {\n // MARK: - CBCentralManagerDelegate\n \n func centralManagerDidUpdateState(_ central: CBCentralManager) {\n // Central manager state updated\n switch central.state {\n case .unknown: break\n case .resetting: break\n case .unsupported: break\n case .unauthorized: break\n case .poweredOff: break\n case .poweredOn: break\n @unknown default: break\n }\n \n if central.state == .unsupported {\n } else if central.state == .unauthorized {\n } else if central.state == .poweredOff {\n } else if central.state == .poweredOn {\n startScanning()\n \n // Send announces when central manager is ready\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n self?.sendBroadcastAnnounce()\n }\n }\n }\n \n func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {\n // Optimize for 300m range - only connect to strong enough signals\n let rssiValue = RSSI.intValue\n \n // Dynamic RSSI threshold based on peer count (smart compromise)\n let rssiThreshold = dynamicRSSIThreshold\n guard rssiValue > rssiThreshold else { \n // Ignoring peripheral due to weak signal (threshold: \\(rssiThreshold) dBm)\n return \n }\n \n // Throttle RSSI updates to save CPU\n let peripheralID = peripheral.identifier.uuidString\n if let lastUpdate = lastRSSIUpdate[peripheralID],\n Date().timeIntervalSince(lastUpdate) < 1.0 {\n return // Skip update if less than 1 second since last update\n }\n lastRSSIUpdate[peripheralID] = Date()\n \n // Store RSSI by peripheral ID for later use\n peripheralRSSI[peripheralID] = RSSI\n \n // Extract peer ID from name (no prefix for stealth)\n // Peer IDs are 8 bytes = 16 hex characters\n if let name = peripheral.name, name.count == 16 {\n // Assume 16-character hex names are peer IDs\n let peerID = name\n SecureLogger.log(\"Discovery: Found peer ID \\(peerID) from peripheral name\", category: SecureLogger.session, level: .debug)\n \n // Don't process our own advertisements (including previous peer IDs)\n if isPeerIDOurs(peerID) {\n SecureLogger.log(\"Discovery: Ignoring our own peer ID \\(peerID)\", category: SecureLogger.session, level: .debug)\n return\n }\n \n // Validate RSSI before storing\n let rssiValue = RSSI.intValue\n if rssiValue != 127 && rssiValue >= -100 && rssiValue <= 0 {\n peerRSSI[peerID] = RSSI\n }\n // Discovered potential peer\n SecureLogger.log(\"Discovered peer with ID: \\(peerID), self ID: \\(myPeerID)\", category: SecureLogger.noise, level: .debug)\n }\n \n // Connection pooling with exponential backoff\n // peripheralID already declared above\n \n // Check if we should attempt connection (considering backoff)\n if let backoffTime = connectionBackoff[peripheralID],\n Date().timeIntervalSince1970 < backoffTime {\n // Still in backoff period, skip connection\n return\n }\n \n // Check if we already have this peripheral in our pool\n if let pooledPeripheral = connectionPool[peripheralID] {\n // Reuse existing peripheral from pool\n if pooledPeripheral.state == CBPeripheralState.disconnected {\n // Reconnect if disconnected with optimized parameters\n let connectionOptions: [String: Any] = [\n CBConnectPeripheralOptionNotifyOnConnectionKey: true,\n CBConnectPeripheralOptionNotifyOnDisconnectionKey: true,\n CBConnectPeripheralOptionNotifyOnNotificationKey: true\n ]\n \n // Smart compromise: would set low latency for small networks if API supported it\n // iOS/macOS don't expose connection interval control in public API\n \n central.connect(pooledPeripheral, options: connectionOptions)\n }\n return\n }\n \n // New peripheral - add to pool and connect\n if !discoveredPeripherals.contains(peripheral) {\n // Check connection pool limits\n let connectedCount = connectionPool.values.filter { $0.state == .connected }.count\n if connectedCount >= maxConnectedPeripherals {\n // Connection pool is full - find least recently used peripheral to disconnect\n if let lruPeripheralID = findLeastRecentlyUsedPeripheral() {\n if let lruPeripheral = connectionPool[lruPeripheralID] {\n SecureLogger.log(\"Connection pool full, disconnecting LRU peripheral: \\(lruPeripheralID)\", \n category: SecureLogger.session, level: .debug)\n central.cancelPeripheralConnection(lruPeripheral)\n connectionPool.removeValue(forKey: lruPeripheralID)\n }\n }\n }\n \n discoveredPeripherals.append(peripheral)\n peripheral.delegate = self\n connectionPool[peripheralID] = peripheral\n \n // Track connection attempts\n let attempts = connectionAttempts[peripheralID] ?? 0\n connectionAttempts[peripheralID] = attempts + 1\n \n // Only attempt if under max attempts\n if attempts < maxConnectionAttempts {\n // Use optimized connection parameters based on peer count\n let connectionOptions: [String: Any] = [\n CBConnectPeripheralOptionNotifyOnConnectionKey: true,\n CBConnectPeripheralOptionNotifyOnDisconnectionKey: true,\n CBConnectPeripheralOptionNotifyOnNotificationKey: true\n ]\n \n // Smart compromise: would set low latency for small networks if API supported it\n // iOS/macOS don't expose connection interval control in public API\n \n central.connect(peripheral, options: connectionOptions)\n }\n }\n }\n \n func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {\n let peripheralID = peripheral.identifier.uuidString\n \n peripheral.delegate = self\n peripheral.discoverServices([BluetoothMeshService.serviceUUID])\n \n // Register peripheral in simplified mapping system\n registerPeripheral(peripheral)\n \n // Store peripheral temporarily until we get the real peer ID\n connectedPeripherals[peripheralID] = peripheral\n \n SecureLogger.log(\"Connected to peripheral \\(peripheralID) - awaiting peer ID\", \n category: SecureLogger.session, level: .debug)\n \n // Update connection state to connected (but not authenticated yet)\n // We don't know the real peer ID yet, so we can't update the state\n \n // Don't show connected message yet - wait for key exchange\n // This prevents the connect/disconnect/connect pattern\n \n // Request RSSI reading\n peripheral.readRSSI()\n \n // iOS 11+ BLE 5.0: Request 2M PHY for better range and speed\n if #available(iOS 11.0, macOS 10.14, *) {\n // 2M PHY provides better range than 1M PHY\n // This is a hint - system will use best available\n }\n }\n \n func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {\n let peripheralID = peripheral.identifier.uuidString\n \n // Clean up RSSI retry count\n rssiRetryCount.removeValue(forKey: peripheralID)\n \n // Check if this was an intentional disconnect\n if intentionalDisconnects.contains(peripheralID) {\n intentionalDisconnects.remove(peripheralID)\n SecureLogger.log(\"Intentional disconnect: \\(peripheralID)\", category: SecureLogger.session, level: .debug)\n // Don't process this disconnect further\n return\n }\n \n // Log disconnect with error if present\n if let error = error {\n SecureLogger.logError(error, context: \"Peripheral disconnected: \\(peripheralID)\", category: SecureLogger.session)\n } else {\n SecureLogger.log(\"Peripheral disconnected normally: \\(peripheralID)\", category: SecureLogger.session, level: .info)\n }\n \n // Find the real peer ID using simplified mapping\n var realPeerID: String? = nil\n \n if let mapping = peripheralMappings[peripheralID], let peerID = mapping.peerID {\n realPeerID = peerID\n SecureLogger.log(\"Found peer ID \\(peerID) for peripheral \\(peripheralID)\", \n category: SecureLogger.session, level: .debug)\n } else if let peerID = peerIDByPeripheralID[peripheralID] {\n // Fallback to legacy mapping\n realPeerID = peerID\n SecureLogger.log(\"Found peer ID \\(peerID) from legacy mapping for peripheral \\(peripheralID)\", \n category: SecureLogger.session, level: .debug)\n } else {\n SecureLogger.log(\"No peer ID mapping found for peripheral \\(peripheralID)\", \n category: SecureLogger.session, level: .debug)\n \n // Fallback: check if we have a direct mapping from peripheral to peer ID\n for (peerID, connectedPeripheral) in connectedPeripherals {\n if connectedPeripheral.identifier == peripheral.identifier {\n // Check if this is a real peer ID (16 hex chars) not a temp ID\n if peerID.count == 16 && peerID.allSatisfy({ $0.isHexDigit }) {\n realPeerID = peerID\n SecureLogger.log(\"Found peer ID \\(peerID) from connectedPeripherals fallback\", \n category: SecureLogger.session, level: .debug)\n break\n } else {\n SecureLogger.log(\"Skipping non-peer ID '\\(peerID)' (length: \\(peerID.count))\", \n category: SecureLogger.session, level: .debug)\n }\n }\n }\n }\n \n // Update connection state immediately if we have a real peer ID\n if let peerID = realPeerID {\n // Update peer connection state\n updatePeerConnectionState(peerID, state: .disconnected)\n \n // Clear pending messages for disconnected peer to prevent retry loops\n collectionsQueue.async(flags: .barrier) { [weak self] in\n if let pendingCount = self?.pendingPrivateMessages[peerID]?.count, pendingCount > 0 {\n SecureLogger.log(\"Clearing \\(pendingCount) pending messages for disconnected peer \\(peerID)\", \n category: SecureLogger.session, level: .info)\n self?.pendingPrivateMessages[peerID]?.removeAll()\n }\n }\n \n // Reset handshake state to prevent stuck handshakes\n handshakeCoordinator.resetHandshakeState(for: peerID)\n \n // Check if peer gracefully left and notify delegate\n let shouldNotifyDisconnect = collectionsQueue.sync {\n let isGracefullyLeft = self.gracefullyLeftPeers.contains(peerID)\n if isGracefullyLeft {\n SecureLogger.log(\"Physical disconnect for \\(peerID) - was gracefully left, NOT notifying delegate\", category: SecureLogger.session, level: .info)\n } else {\n SecureLogger.log(\"Physical disconnect for \\(peerID) - was NOT gracefully left, will notify delegate\", category: SecureLogger.session, level: .info)\n }\n return !isGracefullyLeft\n }\n \n if shouldNotifyDisconnect {\n DispatchQueue.main.async {\n self.delegate?.didDisconnectFromPeer(peerID)\n }\n }\n }\n \n // Implement exponential backoff for failed connections\n if error != nil {\n let attempts = connectionAttempts[peripheralID] ?? 0\n if attempts >= maxConnectionAttempts {\n // Max attempts reached, apply long backoff\n let backoffDuration = baseBackoffInterval * pow(2.0, Double(attempts))\n connectionBackoff[peripheralID] = Date().timeIntervalSince1970 + backoffDuration\n }\n } else {\n // Clean disconnect, reset attempts\n connectionAttempts[peripheralID] = 0\n connectionBackoff.removeValue(forKey: peripheralID)\n }\n \n // Clean up peripheral tracking\n peripheralMappings.removeValue(forKey: peripheralID)\n peerIDByPeripheralID.removeValue(forKey: peripheralID)\n lastActivityByPeripheralID.removeValue(forKey: peripheralID)\n \n // Find peer ID for this peripheral (could be temp ID or real ID)\n var foundPeerID: String? = nil\n for (id, per) in connectedPeripherals {\n if per == peripheral {\n foundPeerID = id\n break\n }\n }\n \n if let peerID = foundPeerID {\n connectedPeripherals.removeValue(forKey: peerID)\n peripheralCharacteristics.removeValue(forKey: peripheral)\n \n // Don't clear Noise session on disconnect - sessions should survive disconnects\n // The Noise protocol is designed to maintain sessions across network interruptions\n // Only clear sessions on authentication failure\n if peerID.count == 16 { // Real peer ID\n // Clear connection time and last heard tracking on disconnect to properly detect stale sessions\n lastConnectionTime.removeValue(forKey: peerID)\n lastHeardFromPeer.removeValue(forKey: peerID)\n // Keep lastSuccessfulMessageTime to validate session on reconnect\n let lastSuccess = lastSuccessfulMessageTime[peerID] ?? Date.distantPast\n let sessionAge = Date().timeIntervalSince(lastSuccess)\n SecureLogger.log(\"Peer disconnected: \\(peerID), keeping Noise session (age: \\(Int(sessionAge))s)\", category: SecureLogger.noise, level: .info)\n }\n \n // Only remove from active peers if it's not a temp ID\n // Temp IDs shouldn't be in activePeers anyway\n let (removed, _) = collectionsQueue.sync(flags: .barrier) {\n var removed = false\n if peerID.count == 16 { // Real peer ID (8 bytes = 16 hex chars)\n removed = activePeers.remove(peerID) != nil\n if removed {\n // Only log disconnect if peer didn't gracefully leave\n if !self.gracefullyLeftPeers.contains(peerID) {\n let nickname = self.peerNicknames[peerID] ?? \"unknown\"\n SecureLogger.log(\"📴 Peer disconnected from network: \\(peerID) (\\(nickname))\", category: SecureLogger.session, level: .info)\n } else {\n // Peer gracefully left, just clean up the tracking\n self.gracefullyLeftPeers.remove(peerID)\n self.gracefulLeaveTimestamps.removeValue(forKey: peerID)\n SecureLogger.log(\"Cleaning up gracefullyLeftPeers for \\(peerID)\", category: SecureLogger.session, level: .debug)\n }\n }\n \n _ = announcedPeers.remove(peerID)\n _ = announcedToPeers.remove(peerID)\n } else {\n }\n \n // Clear cached messages tracking for this peer to allow re-sending if they reconnect\n cachedMessagesSentToPeer.remove(peerID)\n \n // Clear version negotiation state\n versionNegotiationState.removeValue(forKey: peerID)\n negotiatedVersions.removeValue(forKey: peerID)\n \n // Peer disconnected\n \n return (removed, peerNicknames[peerID])\n }\n \n // Always notify peer list update on disconnect, regardless of whether peer was in activePeers\n // This ensures UI stays in sync even if there was a state mismatch\n self.notifyPeerListUpdate(immediate: true)\n \n if removed {\n // Mark when network became empty, but don't reset flag immediately\n let currentNetworkSize = collectionsQueue.sync { activePeers.count }\n if currentNetworkSize == 0 && networkBecameEmptyTime == nil {\n networkBecameEmptyTime = Date()\n }\n }\n }\n \n // Keep in pool but remove from discovered list\n discoveredPeripherals.removeAll { $0 == peripheral }\n \n // Continue scanning for reconnection\n if centralManager?.state == .poweredOn {\n // Stop and restart to ensure clean state\n centralManager?.stopScan()\n centralManager?.scanForPeripherals(withServices: [BluetoothMeshService.serviceUUID], options: [CBCentralManagerScanOptionAllowDuplicatesKey: false])\n }\n }\n}\n\nextension BluetoothMeshService: CBPeripheralDelegate {\n // MARK: - CBPeripheralDelegate\n \n func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {\n if let error = error {\n SecureLogger.log(\"Error discovering services: \\(error)\", \n category: SecureLogger.encryption, level: .error)\n return\n }\n \n guard let services = peripheral.services else { return }\n \n \n for service in services {\n peripheral.discoverCharacteristics([BluetoothMeshService.characteristicUUID], for: service)\n }\n }\n \n func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {\n if let error = error {\n SecureLogger.log(\"Error discovering characteristics: \\(error)\", \n category: SecureLogger.encryption, level: .error)\n return\n }\n \n guard let characteristics = service.characteristics else { return }\n \n \n for characteristic in characteristics {\n if characteristic.uuid == BluetoothMeshService.characteristicUUID {\n peripheral.setNotifyValue(true, for: characteristic)\n peripheralCharacteristics[peripheral] = characteristic\n \n // Request maximum MTU for faster data transfer\n // iOS supports up to 512 bytes with BLE 5.0\n peripheral.maximumWriteValueLength(for: .withoutResponse)\n \n // Start version negotiation instead of immediately sending Noise identity\n self.sendVersionHello(to: peripheral)\n \n // Send announce packet after version negotiation completes\n if let vm = self.delegate as? ChatViewModel {\n // Send single announce with slight delay\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in\n guard let self = self else { return }\n let announcePacket = BitchatPacket(\n type: MessageType.announce.rawValue,\n ttl: 3,\n senderID: self.myPeerID,\n payload: Data(vm.nickname.utf8) )\n self.broadcastPacket(announcePacket)\n }\n \n // Also send targeted announce to this specific peripheral\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [weak self, weak peripheral] in\n guard let self = self,\n let peripheral = peripheral,\n peripheral.state == .connected,\n let characteristic = peripheral.services?.first(where: { $0.uuid == BluetoothMeshService.serviceUUID })?.characteristics?.first(where: { $0.uuid == BluetoothMeshService.characteristicUUID }) else { return }\n \n let announcePacket = BitchatPacket(\n type: MessageType.announce.rawValue,\n ttl: 3,\n senderID: self.myPeerID,\n payload: Data(vm.nickname.utf8) )\n if let data = announcePacket.toBinaryData() {\n self.writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: nil)\n }\n }\n }\n }\n }\n }\n \n func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {\n guard let data = characteristic.value else {\n return\n }\n \n // Update activity tracking for this peripheral\n updatePeripheralActivity(peripheral.identifier.uuidString)\n \n \n guard let packet = BitchatPacket.from(data) else { \n return \n }\n \n \n // Use the sender ID from the packet, not our local mapping which might still be a temp ID\n let _ = connectedPeripherals.first(where: { $0.value == peripheral })?.key ?? \"unknown\"\n let packetSenderID = packet.senderID.hexEncodedString()\n \n \n // Always handle received packets\n handleReceivedPacket(packet, from: packetSenderID, peripheral: peripheral)\n }\n \n func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {\n if let error = error {\n // Log error but don't spam for common errors\n let errorCode = (error as NSError).code\n if errorCode != 242 { // Don't log the common \"Unknown ATT error\"\n }\n } else {\n }\n }\n \n func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {\n peripheral.discoverServices([BluetoothMeshService.serviceUUID])\n }\n \n func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {\n // Handle notification state updates if needed\n }\n \n func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {\n let peripheralID = peripheral.identifier.uuidString\n \n if error != nil {\n return\n }\n \n // Validate RSSI value - 127 means no RSSI available\n let rssiValue = RSSI.intValue\n \n // Only store valid RSSI values\n if rssiValue == 127 || rssiValue < -100 || rssiValue > 0 {\n // Track retry count\n let retryCount = rssiRetryCount[peripheralID] ?? 0\n rssiRetryCount[peripheralID] = retryCount + 1\n \n \n // Retry up to 5 times with exponential backoff\n if retryCount < 5 {\n let delay = min(0.2 * pow(2.0, Double(retryCount)), 2.0) // 0.2s, 0.4s, 0.8s, 1.6s, 2.0s max\n DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self, weak peripheral] in\n guard let peripheral = peripheral, peripheral.state == .connected else { \n self?.rssiRetryCount.removeValue(forKey: peripheralID)\n return \n }\n peripheral.readRSSI()\n }\n } else {\n // Give up after 5 retries, reset counter\n rssiRetryCount.removeValue(forKey: peripheralID)\n }\n return\n }\n \n // Valid RSSI received, reset retry count\n rssiRetryCount.removeValue(forKey: peripheralID)\n \n // Update RSSI in simplified mapping\n updatePeripheralRSSI(peripheralID: peripheralID, rssi: RSSI)\n \n // Also store in legacy mapping for compatibility\n peripheralRSSI[peripheralID] = RSSI\n \n // If we have a peer ID, update peer RSSI (handled in updatePeripheralRSSI)\n if let mapping = peripheralMappings[peripheralID], mapping.isIdentified {\n // Force UI update when we have a real peer ID\n DispatchQueue.main.async { [weak self] in\n self?.notifyPeerListUpdate()\n }\n } else {\n // Keep trying to read RSSI until we get real peer ID\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak peripheral] in\n guard let peripheral = peripheral, peripheral.state == .connected else { return }\n peripheral.readRSSI()\n }\n }\n \n // Periodically update RSSI\n DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) { [weak peripheral] in\n guard let peripheral = peripheral, peripheral.state == .connected else { return }\n peripheral.readRSSI()\n }\n }\n}\n\nextension BluetoothMeshService: CBPeripheralManagerDelegate {\n // MARK: - CBPeripheralManagerDelegate\n \n func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {\n // Peripheral manager state updated\n switch peripheral.state {\n case .unknown: break\n case .resetting: break\n case .unsupported: break\n case .unauthorized: break\n case .poweredOff: break\n case .poweredOn: break\n @unknown default: break\n }\n \n switch peripheral.state {\n case .unsupported:\n break\n case .unauthorized:\n break\n case .poweredOff:\n break\n case .poweredOn:\n setupPeripheral()\n startAdvertising()\n \n // Send announces when peripheral manager is ready\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n self?.sendBroadcastAnnounce()\n }\n default:\n break\n }\n }\n \n func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) {\n // Service added\n }\n \n func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) {\n // Advertising state changed\n }\n \n func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {\n for request in requests {\n if let data = request.value {\n \n if let packet = BitchatPacket.from(data) {\n \n // Log specific Noise packet types\n switch packet.type {\n case MessageType.noiseHandshakeInit.rawValue:\n break\n case MessageType.noiseHandshakeResp.rawValue:\n break\n case MessageType.noiseEncrypted.rawValue:\n break\n default:\n break\n }\n \n // Try to identify peer from packet\n let peerID = packet.senderID.hexEncodedString()\n \n // Store the central for updates\n if !subscribedCentrals.contains(request.central) {\n subscribedCentrals.append(request.central)\n }\n \n // Track this peer as connected\n if peerID != \"unknown\" && peerID != myPeerID {\n // Double-check we're not adding ourselves\n if peerID == self.myPeerID {\n SecureLogger.log(\"Preventing self from being added as peer (peripheral manager)\", category: SecureLogger.noise, level: .warning)\n peripheral.respond(to: request, withResult: .success)\n return\n }\n \n // Note: Legacy keyExchange (0x02) no longer handled\n \n self.notifyPeerListUpdate()\n }\n \n handleReceivedPacket(packet, from: peerID)\n peripheral.respond(to: request, withResult: .success)\n } else {\n peripheral.respond(to: request, withResult: .invalidPdu)\n }\n } else {\n peripheral.respond(to: request, withResult: .invalidPdu)\n }\n }\n }\n \n func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {\n if !subscribedCentrals.contains(central) {\n subscribedCentrals.append(central)\n \n // Only send identity announcement if we haven't recently\n // This reduces spam when multiple centrals connect quickly\n // sendNoiseIdentityAnnounce() will check rate limits internally\n \n // Update peer list to show we're connected (even without peer ID yet)\n self.notifyPeerListUpdate()\n }\n }\n \n func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) {\n subscribedCentrals.removeAll { $0 == central }\n \n // Don't aggressively remove peers when centrals unsubscribe\n // Peers may be connected through multiple paths\n \n // Ensure advertising continues for reconnection\n if peripheralManager?.state == .poweredOn && peripheralManager?.isAdvertising == false {\n startAdvertising()\n }\n }\n \n // MARK: - Battery Monitoring\n \n private func setupBatteryOptimizer() {\n // Subscribe to power mode changes\n batteryOptimizer.$currentPowerMode\n .sink { [weak self] powerMode in\n self?.handlePowerModeChange(powerMode)\n }\n .store(in: &batteryOptimizerCancellables)\n \n // Subscribe to battery level changes\n batteryOptimizer.$batteryLevel\n .sink { [weak self] level in\n self?.currentBatteryLevel = level\n }\n .store(in: &batteryOptimizerCancellables)\n \n // Initial update\n handlePowerModeChange(batteryOptimizer.currentPowerMode)\n }\n \n private func handlePowerModeChange(_ powerMode: PowerMode) {\n let params = batteryOptimizer.scanParameters\n activeScanDuration = params.duration\n scanPauseDuration = params.pause\n \n // Update max connections\n let maxConnections = powerMode.maxConnections\n \n // If we have too many connections, disconnect from the least important ones\n if connectedPeripherals.count > maxConnections {\n disconnectLeastImportantPeripherals(keepCount: maxConnections)\n }\n \n // Update message aggregation window\n aggregationWindow = powerMode.messageAggregationWindow\n \n // If we're currently scanning, restart with new parameters\n if scanDutyCycleTimer != nil {\n scanDutyCycleTimer?.invalidate()\n scheduleScanDutyCycle()\n }\n \n // Handle advertising intervals\n if powerMode.advertisingInterval > 0 {\n // Stop continuous advertising and use interval-based\n scheduleAdvertisingCycle(interval: powerMode.advertisingInterval)\n } else {\n // Continuous advertising for performance mode\n startAdvertising()\n }\n }\n \n private func disconnectLeastImportantPeripherals(keepCount: Int) {\n // Disconnect peripherals with lowest activity/importance\n let sortedPeripherals = connectedPeripherals.values\n .sorted { peer1, peer2 in\n // Keep peripherals we've recently communicated with\n let peer1Activity = lastMessageFromPeer.get(peer1.identifier.uuidString) ?? Date.distantPast\n let peer2Activity = lastMessageFromPeer.get(peer2.identifier.uuidString) ?? Date.distantPast\n return peer1Activity > peer2Activity\n }\n \n // Disconnect the least active ones\n let toDisconnect = sortedPeripherals.dropFirst(keepCount)\n for peripheral in toDisconnect {\n centralManager?.cancelPeripheralConnection(peripheral)\n }\n }\n \n private func scheduleAdvertisingCycle(interval: TimeInterval) {\n advertisingTimer?.invalidate()\n \n // Stop advertising\n if isAdvertising {\n peripheralManager?.stopAdvertising()\n isAdvertising = false\n }\n \n // Schedule next advertising burst\n advertisingTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in\n self?.advertiseBurst()\n }\n }\n \n private func advertiseBurst() {\n guard batteryOptimizer.currentPowerMode != .ultraLowPower || !batteryOptimizer.isInBackground else {\n return // Skip advertising in ultra low power + background\n }\n \n startAdvertising()\n \n // Stop advertising after a short burst (1 second)\n DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in\n if self?.batteryOptimizer.currentPowerMode.advertisingInterval ?? 0 > 0 {\n self?.peripheralManager?.stopAdvertising()\n self?.isAdvertising = false\n }\n }\n }\n \n // Legacy battery monitoring methods - kept for compatibility\n // Now handled by BatteryOptimizer\n private func updateBatteryLevel() {\n // This method is now handled by BatteryOptimizer\n // Keeping empty implementation for compatibility\n }\n \n private func updateScanParametersForBattery() {\n // This method is now handled by BatteryOptimizer through handlePowerModeChange\n // Keeping empty implementation for compatibility\n }\n \n // MARK: - Privacy Utilities\n \n private func randomDelay() -> TimeInterval {\n // Generate random delay between min and max for timing obfuscation\n return TimeInterval.random(in: minMessageDelay...maxMessageDelay)\n }\n \n // MARK: - Range Optimization Methods\n \n // Calculate relay probability based on RSSI (edge nodes relay more)\n private func calculateRelayProbability(baseProb: Double, rssi: Int) -> Double {\n // RSSI typically ranges from -30 (very close) to -90 (far)\n // We want edge nodes (weak RSSI) to relay more aggressively\n let rssiFactor = Double(100 + rssi) / 100.0 // -90 = 0.1, -70 = 0.3, -50 = 0.5\n \n // Invert the factor so weak signals relay more\n let edgeFactor = max(0.5, 2.0 - rssiFactor)\n \n return min(1.0, baseProb * edgeFactor)\n }\n \n // Exponential delay distribution to prevent synchronized collision storms\n private func exponentialRelayDelay() -> TimeInterval {\n // Use exponential distribution with mean of (min + max) / 2\n let meanDelay = (minMessageDelay + maxMessageDelay) / 2.0\n let lambda = 1.0 / meanDelay\n \n // Generate exponential random value\n let u = Double.random(in: 0..<1)\n let exponentialDelay = -log(1.0 - u) / lambda\n \n // Clamp to our bounds\n return min(maxMessageDelay, max(minMessageDelay, exponentialDelay))\n }\n \n // Check if message type is high priority (should bypass aggregation)\n private func isHighPriorityMessage(type: UInt8) -> Bool {\n switch MessageType(rawValue: type) {\n case .noiseHandshakeInit, .noiseHandshakeResp, .protocolAck,\n .versionHello, .versionAck, .deliveryAck, .systemValidation,\n .handshakeRequest:\n return true\n case .message, .announce, .leave, .readReceipt, .deliveryStatusRequest,\n .fragmentStart, .fragmentContinue, .fragmentEnd,\n .noiseIdentityAnnounce, .noiseEncrypted, .protocolNack, .none:\n return false\n }\n }\n \n // Calculate exponential backoff for retries\n private func calculateExponentialBackoff(retry: Int) -> TimeInterval {\n // Start with 1s, double each time: 1s, 2s, 4s, 8s, 16s, max 30s\n let baseDelay = 1.0\n let maxDelay = 30.0\n let delay = min(maxDelay, baseDelay * pow(2.0, Double(retry - 1)))\n \n // Add 10% jitter to prevent synchronized retries\n let jitter = delay * 0.1 * (Double.random(in: -1...1))\n return delay + jitter\n }\n \n // MARK: - Collision Avoidance\n \n // Calculate jitter based on node ID to spread transmissions\n private func calculateNodeIDJitter() -> TimeInterval {\n // Use hash of peer ID to generate consistent jitter for this node\n let hashValue = myPeerID.hash\n let normalizedHash = Double(abs(hashValue % 1000)) / 1000.0 // 0.0 to 0.999\n \n // Jitter range: 0-20ms based on node ID\n let jitterRange: TimeInterval = 0.02 // 20ms max jitter\n return normalizedHash * jitterRange\n }\n \n // Add smart delay to avoid collisions\n private func smartCollisionAvoidanceDelay(baseDelay: TimeInterval) -> TimeInterval {\n // Add node-specific jitter to base delay\n let nodeJitter = calculateNodeIDJitter()\n \n // Add small random component to avoid perfect synchronization\n let randomJitter = TimeInterval.random(in: 0...0.005) // 0-5ms additional random\n \n return baseDelay + nodeJitter + randomJitter\n }\n \n // MARK: - Relay Cancellation\n \n private func scheduleRelay(_ packet: BitchatPacket, messageID: String, delay: TimeInterval) {\n pendingRelaysLock.lock()\n defer { pendingRelaysLock.unlock() }\n \n // Cancel any existing relay for this message\n if let existingRelay = pendingRelays[messageID] {\n existingRelay.cancel()\n }\n \n // Apply smart collision avoidance to delay\n let adjustedDelay = smartCollisionAvoidanceDelay(baseDelay: delay)\n \n // Create new relay task\n let relayTask = DispatchWorkItem { [weak self] in\n guard let self = self else { return }\n \n // Remove from pending when executed\n self.pendingRelaysLock.lock()\n self.pendingRelays.removeValue(forKey: messageID)\n self.pendingRelaysLock.unlock()\n \n // Mark this message as relayed\n self.processedMessagesLock.lock()\n if var state = self.processedMessages[messageID] {\n state.relayed = true\n self.processedMessages[messageID] = state\n }\n self.processedMessagesLock.unlock()\n \n // Actually relay the packet\n self.broadcastPacket(packet)\n }\n \n // Store the task\n pendingRelays[messageID] = relayTask\n \n // Schedule it with adjusted delay\n DispatchQueue.global(qos: .default).asyncAfter(deadline: .now() + adjustedDelay, execute: relayTask)\n }\n \n private func cancelPendingRelay(messageID: String) {\n pendingRelaysLock.lock()\n defer { pendingRelaysLock.unlock() }\n \n if let pendingRelay = pendingRelays[messageID] {\n pendingRelay.cancel()\n pendingRelays.removeValue(forKey: messageID)\n // Cancelled pending relay - another node handled it\n }\n }\n \n // MARK: - Memory Management\n \n private func startMemoryCleanupTimer() {\n memoryCleanupTimer?.invalidate()\n memoryCleanupTimer = Timer.scheduledTimer(withTimeInterval: 60.0, repeats: true) { [weak self] _ in\n self?.performMemoryCleanup()\n }\n }\n \n private func performMemoryCleanup() {\n messageQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n let startTime = Date()\n \n // Clean up old fragments\n let fragmentTimeout = Date().addingTimeInterval(-self.fragmentTimeout)\n var expiredFragments = [String]()\n for (fragmentID, metadata) in self.fragmentMetadata {\n if metadata.timestamp < fragmentTimeout {\n expiredFragments.append(fragmentID)\n }\n }\n for fragmentID in expiredFragments {\n self.incomingFragments.removeValue(forKey: fragmentID)\n self.fragmentMetadata.removeValue(forKey: fragmentID)\n }\n \n // Limit pending private messages\n if self.pendingPrivateMessages.count > self.maxPendingPrivateMessages {\n let excess = self.pendingPrivateMessages.count - self.maxPendingPrivateMessages\n let keysToRemove = Array(self.pendingPrivateMessages.keys.prefix(excess))\n for key in keysToRemove {\n self.pendingPrivateMessages.removeValue(forKey: key)\n }\n SecureLogger.log(\"Removed \\(excess) oldest pending private message queues\", \n category: SecureLogger.session, level: .info)\n }\n \n // Limit cached messages sent to peer\n if self.cachedMessagesSentToPeer.count > self.maxCachedMessagesSentToPeer {\n let excess = self.cachedMessagesSentToPeer.count - self.maxCachedMessagesSentToPeer\n let toRemove = self.cachedMessagesSentToPeer.prefix(excess)\n self.cachedMessagesSentToPeer.subtract(toRemove)\n SecureLogger.log(\"Removed \\(excess) oldest cached message tracking entries\", \n category: SecureLogger.session, level: .debug)\n }\n \n // Clean up pending relays\n self.pendingRelaysLock.lock()\n _ = self.pendingRelays.count\n self.pendingRelaysLock.unlock()\n \n // Clean up rate limiters\n self.cleanupRateLimiters()\n \n // Log memory status\n _ = Date().timeIntervalSince(startTime)\n // Memory cleanup completed\n \n // Estimate current memory usage and log if high\n let estimatedMemory = self.estimateMemoryUsage()\n if estimatedMemory > self.maxMemoryUsageBytes {\n SecureLogger.log(\"Warning: Estimated memory usage \\(estimatedMemory / 1024 / 1024)MB exceeds limit\", \n category: SecureLogger.session, level: .warning)\n }\n }\n }\n \n private func estimateMemoryUsage() -> Int {\n // Rough estimates based on typical sizes\n let messageSize = 512 // Average message size\n let fragmentSize = 512 // Average fragment size\n \n var totalBytes = 0\n \n // Processed messages (string storage + MessageState)\n processedMessagesLock.lock()\n totalBytes += processedMessages.count * 150 // messageID strings + MessageState struct\n processedMessagesLock.unlock()\n \n // Fragments\n for (_, fragments) in incomingFragments {\n totalBytes += fragments.count * fragmentSize\n }\n \n // Pending private messages\n for (_, messages) in pendingPrivateMessages {\n totalBytes += messages.count * messageSize\n }\n \n // Other caches\n totalBytes += cachedMessagesSentToPeer.count * 50 // peerID strings\n totalBytes += deliveredMessages.count * 100 // messageID strings\n totalBytes += recentlySentMessages.count * 100 // messageID strings\n \n return totalBytes\n }\n \n // MARK: - Rate Limiting\n \n private func isRateLimited(peerID: String, messageType: UInt8) -> Bool {\n rateLimiterLock.lock()\n defer { rateLimiterLock.unlock() }\n \n let now = Date()\n let cutoff = now.addingTimeInterval(-rateLimitWindow)\n \n // Clean old timestamps from total counter\n totalMessageTimestamps.removeAll { $0 < cutoff }\n \n // Check global rate limit with progressive throttling\n if totalMessageTimestamps.count >= maxTotalMessagesPerMinute {\n // Apply progressive throttling for global limit\n let overageRatio = Double(totalMessageTimestamps.count - maxTotalMessagesPerMinute) / Double(maxTotalMessagesPerMinute)\n let dropProbability = min(0.95, 0.5 + overageRatio * 0.5) // 50% to 95% drop rate\n \n if Double.random(in: 0...1) < dropProbability {\n SecureLogger.log(\"Global rate limit throttling: \\(totalMessageTimestamps.count) messages, drop prob: \\(Int(dropProbability * 100))%\", \n category: SecureLogger.security, level: .warning)\n return true\n }\n }\n \n // Determine which rate limiter to use based on message type\n let isChatMessage = messageType == MessageType.message.rawValue\n \n let limiter = isChatMessage ? messageRateLimiter : protocolMessageRateLimiter\n let maxPerMinute = isChatMessage ? maxChatMessagesPerPeerPerMinute : maxProtocolMessagesPerPeerPerMinute\n \n // Clean old timestamps for this peer\n if var timestamps = limiter[peerID] {\n timestamps.removeAll { $0 < cutoff }\n \n // Update the appropriate limiter\n if isChatMessage {\n messageRateLimiter[peerID] = timestamps\n } else {\n protocolMessageRateLimiter[peerID] = timestamps\n }\n \n // Progressive throttling for per-peer limit\n if timestamps.count >= maxPerMinute {\n // Calculate how much over the limit we are\n let overageRatio = Double(timestamps.count - maxPerMinute) / Double(maxPerMinute)\n \n // Progressive drop probability: starts at 30% when just over limit, increases to 90%\n let dropProbability = min(0.9, 0.3 + overageRatio * 0.6)\n \n if Double.random(in: 0...1) < dropProbability {\n let messageTypeStr = isChatMessage ? \"chat\" : \"protocol\"\n SecureLogger.log(\"Peer \\(peerID) \\(messageTypeStr) rate throttling: \\(timestamps.count) msgs/min, drop prob: \\(Int(dropProbability * 100))%\", \n category: SecureLogger.security, level: .info)\n return true\n } else {\n SecureLogger.log(\"Peer \\(peerID) rate throttling: allowing message (\\(timestamps.count) msgs/min)\", \n category: SecureLogger.security, level: .debug)\n }\n }\n }\n \n return false\n }\n \n private func recordMessage(from peerID: String, messageType: UInt8) {\n rateLimiterLock.lock()\n defer { rateLimiterLock.unlock() }\n \n let now = Date()\n \n // Record in global counter\n totalMessageTimestamps.append(now)\n \n // Determine which rate limiter to use based on message type\n let isChatMessage = messageType == MessageType.message.rawValue\n \n // Record for specific peer in the appropriate limiter\n if isChatMessage {\n if messageRateLimiter[peerID] == nil {\n messageRateLimiter[peerID] = []\n }\n messageRateLimiter[peerID]?.append(now)\n } else {\n if protocolMessageRateLimiter[peerID] == nil {\n protocolMessageRateLimiter[peerID] = []\n }\n protocolMessageRateLimiter[peerID]?.append(now)\n }\n }\n \n private func cleanupRateLimiters() {\n rateLimiterLock.lock()\n defer { rateLimiterLock.unlock() }\n \n let cutoff = Date().addingTimeInterval(-rateLimitWindow)\n \n // Clean global timestamps\n totalMessageTimestamps.removeAll { $0 < cutoff }\n \n // Clean up old identity announce tracking\n processedMessagesLock.lock()\n let identityCutoff = Date().addingTimeInterval(-identityAnnounceDuplicateWindow * 2)\n recentIdentityAnnounces = recentIdentityAnnounces.filter { $0.value > identityCutoff }\n processedMessagesLock.unlock()\n \n // Clean per-peer chat message timestamps\n for (peerID, timestamps) in messageRateLimiter {\n let filtered = timestamps.filter { $0 >= cutoff }\n if filtered.isEmpty {\n messageRateLimiter.removeValue(forKey: peerID)\n } else {\n messageRateLimiter[peerID] = filtered\n }\n }\n \n // Clean per-peer protocol message timestamps\n for (peerID, timestamps) in protocolMessageRateLimiter {\n let filtered = timestamps.filter { $0 >= cutoff }\n if filtered.isEmpty {\n protocolMessageRateLimiter.removeValue(forKey: peerID)\n } else {\n protocolMessageRateLimiter[peerID] = filtered\n }\n }\n \n SecureLogger.log(\"Rate limiter cleanup: tracking \\(messageRateLimiter.count) chat peers, \\(protocolMessageRateLimiter.count) protocol peers, \\(totalMessageTimestamps.count) total messages\", \n category: SecureLogger.session, level: .debug)\n }\n \n // MARK: - Cover Traffic\n \n private func startCoverTraffic() {\n // Start cover traffic with random interval\n scheduleCoverTraffic()\n }\n \n private func scheduleCoverTraffic() {\n // Random interval between 30-120 seconds\n let interval = TimeInterval.random(in: 30...120)\n \n coverTrafficTimer?.invalidate()\n coverTrafficTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { [weak self] _ in\n self?.sendDummyMessage()\n self?.scheduleCoverTraffic() // Schedule next dummy message\n }\n }\n \n private func sendDummyMessage() {\n // Only send dummy messages if we have connected peers with established sessions\n let peersWithSessions = getAllConnectedPeerIDs().filter { peerID in\n return noiseService.hasEstablishedSession(with: peerID)\n }\n \n guard !peersWithSessions.isEmpty else { \n SecureLogger.log(\"Cover traffic: No peers with established sessions, skipping dummy message\", \n category: SecureLogger.security, level: .debug)\n return \n }\n \n // Skip if battery is low\n if currentBatteryLevel < 0.2 {\n SecureLogger.log(\"Cover traffic: Battery low, skipping dummy message\", \n category: SecureLogger.security, level: .debug)\n return\n }\n \n // Pick a random peer with an established session to send to\n guard let randomPeer = peersWithSessions.randomElement() else { return }\n \n // Generate random dummy content\n let dummyContent = generateDummyContent()\n \n SecureLogger.log(\"Cover traffic: Sending dummy message to \\(randomPeer)\", \n category: SecureLogger.security, level: .info)\n \n // Send as a private message so it's encrypted\n let recipientNickname = collectionsQueue.sync {\n return peerNicknames[randomPeer] ?? \"unknown\"\n }\n \n sendPrivateMessage(dummyContent, to: randomPeer, recipientNickname: recipientNickname)\n }\n \n private func generateDummyContent() -> String {\n // Generate realistic-looking dummy messages\n let templates = [\n \"hey\",\n \"ok\",\n \"got it\",\n \"sure\",\n \"sounds good\",\n \"thanks\",\n \"np\",\n \"see you there\",\n \"on my way\",\n \"running late\",\n \"be there soon\",\n \"���\",\n \"✓\",\n \"meeting at the usual spot\",\n \"confirmed\",\n \"roger that\"\n ]\n \n // Prefix with dummy marker (will be encrypted)\n return coverTrafficPrefix + (templates.randomElement() ?? \"ok\")\n }\n \n \n private func updatePeerLastSeen(_ peerID: String) {\n peerLastSeenTimestamps.set(peerID, value: Date())\n }\n \n private func sendPendingPrivateMessages(to peerID: String) {\n messageQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n // Get pending messages with proper queue synchronization\n let pendingMessages = self.collectionsQueue.sync {\n return self.pendingPrivateMessages[peerID]\n }\n \n guard let messages = pendingMessages else { return }\n \n SecureLogger.log(\"Sending \\(messages.count) pending private messages to \\(peerID)\", category: SecureLogger.session, level: .info)\n \n // Clear pending messages for this peer\n self.collectionsQueue.sync(flags: .barrier) {\n _ = self.pendingPrivateMessages.removeValue(forKey: peerID)\n }\n \n // Send each pending message\n for (content, recipientNickname, messageID) in messages {\n // Check if this is a read receipt\n if content.hasPrefix(\"READ_RECEIPT:\") {\n // Extract the original message ID\n let originalMessageID = String(content.dropFirst(\"READ_RECEIPT:\".count))\n SecureLogger.log(\"Sending queued read receipt for message \\(originalMessageID) to \\(peerID)\", category: SecureLogger.session, level: .debug)\n \n // Create and send the actual read receipt\n let receipt = ReadReceipt(\n originalMessageID: originalMessageID,\n readerID: self.myPeerID,\n readerNickname: recipientNickname // This is actually the reader's nickname\n )\n \n // Send the read receipt using the normal method\n DispatchQueue.global().async { [weak self] in\n self?.sendReadReceipt(receipt, to: peerID)\n }\n } else {\n // Regular message\n SecureLogger.log(\"Sending pending message \\(messageID) to \\(peerID)\", category: SecureLogger.session, level: .debug)\n // Use async to avoid blocking the queue\n DispatchQueue.global().async { [weak self] in\n self?.sendPrivateMessage(content, to: peerID, recipientNickname: recipientNickname, messageID: messageID)\n }\n }\n }\n }\n }\n \n // MARK: - Noise Protocol Support\n \n private func attemptHandshakeIfNeeded(with peerID: String, forceIfStale: Bool = false) {\n // Check if we already have an established session\n if noiseService.hasEstablishedSession(with: peerID) {\n SecureLogger.log(\"Already have established session with \\(peerID), skipping handshake\", \n category: SecureLogger.handshake, level: .debug)\n return\n }\n \n // Check if we should initiate using the handshake coordinator\n if !handshakeCoordinator.shouldInitiateHandshake(\n myPeerID: myPeerID, \n remotePeerID: peerID,\n forceIfStale: forceIfStale\n ) {\n SecureLogger.log(\"Should not initiate handshake with \\(peerID) at this time\", \n category: SecureLogger.handshake, level: .debug)\n return\n }\n \n // Initiate the handshake\n initiateNoiseHandshake(with: peerID)\n }\n \n // Send keep-alive pings to all connected peers to prevent iOS BLE timeouts\n private func sendKeepAlivePings() {\n let connectedPeers = collectionsQueue.sync {\n return Array(activePeers).filter { peerID in\n // Only send keepalive to authenticated peers that still exist\n // Check if this peer ID is still current (not rotated)\n guard let fingerprint = peerIDToFingerprint[peerID],\n let currentPeerID = fingerprintToPeerID[fingerprint],\n currentPeerID == peerID else {\n // This peer ID has rotated, skip it\n SecureLogger.log(\"Skipping keepalive for rotated peer ID: \\(peerID)\", \n category: SecureLogger.session, level: .debug)\n return false\n }\n \n // Check if we actually have a Noise session with this peer\n guard noiseService.hasEstablishedSession(with: peerID) else {\n SecureLogger.log(\"Skipping keepalive for \\(peerID) - no established session\", \n category: SecureLogger.session, level: .debug)\n return false\n }\n \n return peerConnectionStates[peerID] == .authenticated\n }\n }\n \n SecureLogger.log(\"Keep-alive timer: checking \\(connectedPeers.count) peers for pings\", \n category: SecureLogger.session, level: .debug)\n \n for peerID in connectedPeers {\n // Don't spam if we recently heard from them\n if let lastHeard = lastHeardFromPeer[peerID], \n Date().timeIntervalSince(lastHeard) < keepAliveInterval / 2 {\n SecureLogger.log(\"Skipping keepalive for \\(peerID) - heard recently\", \n category: SecureLogger.session, level: .debug)\n continue // Skip if we heard from them in the last 10 seconds\n }\n \n SecureLogger.log(\"Sending keepalive ping to \\(peerID)\", \n category: SecureLogger.session, level: .debug)\n validateNoiseSession(with: peerID)\n }\n }\n \n // Validate an existing Noise session by sending an encrypted ping\n private func validateNoiseSession(with peerID: String) {\n let encryptionQueue = getEncryptionQueue(for: peerID)\n \n encryptionQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Create a ping packet with minimal data\n let pingData = \"ping:\\(Date().timeIntervalSince1970)\".data(using: .utf8)!\n \n do {\n // Try to encrypt a small ping message\n let encrypted = try self.noiseService.encrypt(pingData, for: peerID)\n \n // Create a validation packet (won't be displayed to user)\n let packet = BitchatPacket(\n type: MessageType.systemValidation.rawValue,\n senderID: Data(hexString: self.myPeerID) ?? Data(),\n recipientID: Data(hexString: peerID),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: encrypted,\n signature: nil,\n ttl: 1 )\n \n // System validation should go directly to the peer when possible\n if !self.sendDirectToRecipient(packet, recipientPeerID: peerID) {\n // Fall back to selective relay if direct delivery fails\n self.sendViaSelectiveRelay(packet, recipientPeerID: peerID)\n }\n \n SecureLogger.log(\"Sent session validation ping to \\(peerID)\", \n category: SecureLogger.session, level: .debug)\n } catch {\n // Encryption failed - session is invalid\n SecureLogger.log(\"Session validation failed for \\(peerID): \\(error)\", \n category: SecureLogger.session, level: .warning)\n \n // Clear the invalid session\n self.cleanupPeerCryptoState(peerID)\n \n // Initiate fresh handshake\n DispatchQueue.main.async { [weak self] in\n self?.attemptHandshakeIfNeeded(with: peerID, forceIfStale: true)\n }\n }\n }\n }\n \n private func initiateNoiseHandshake(with peerID: String) {\n // Use noiseService directly\n \n SecureLogger.log(\"Initiating Noise handshake with \\(peerID)\", category: SecureLogger.noise, level: .info)\n \n // Check if we already have an established session\n if noiseService.hasEstablishedSession(with: peerID) {\n SecureLogger.log(\"Already have established session with \\(peerID)\", category: SecureLogger.noise, level: .debug)\n // Clear any lingering handshake attempt time\n handshakeAttemptTimes.removeValue(forKey: peerID)\n handshakeCoordinator.recordHandshakeSuccess(peerID: peerID)\n \n // Update session state to established\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[peerID] = .established\n }\n \n // Update connection state to authenticated\n updatePeerConnectionState(peerID, state: .authenticated)\n \n // Force UI update since we have an existing session\n DispatchQueue.main.async { [weak self] in\n (self?.delegate as? ChatViewModel)?.updateEncryptionStatusForPeers()\n }\n \n return\n }\n \n // Update state to handshaking\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[peerID] = .handshaking\n }\n \n // Check if we have pending messages\n let hasPendingMessages = collectionsQueue.sync {\n return pendingPrivateMessages[peerID]?.isEmpty == false\n }\n \n // Check with coordinator if we should initiate\n if !handshakeCoordinator.shouldInitiateHandshake(myPeerID: myPeerID, remotePeerID: peerID, forceIfStale: hasPendingMessages) {\n SecureLogger.log(\"Coordinator says we should not initiate handshake with \\(peerID)\", category: SecureLogger.handshake, level: .debug)\n \n if hasPendingMessages {\n // Check if peer is still connected before retrying\n let connectionState = collectionsQueue.sync { peerConnectionStates[peerID] ?? .disconnected }\n \n if connectionState == .disconnected {\n // Peer is disconnected - clear pending messages and stop retrying\n SecureLogger.log(\"Peer \\(peerID) is disconnected, clearing pending messages\", category: SecureLogger.handshake, level: .info)\n collectionsQueue.async(flags: .barrier) { [weak self] in\n self?.pendingPrivateMessages[peerID]?.removeAll()\n }\n handshakeCoordinator.resetHandshakeState(for: peerID)\n } else {\n // Peer is still connected but handshake is stuck\n // Send identity announce to prompt them to initiate if they have lower ID\n SecureLogger.log(\"Handshake stuck with connected peer \\(peerID), sending identity announce\", category: SecureLogger.handshake, level: .info)\n sendNoiseIdentityAnnounce(to: peerID)\n \n // Only retry if we haven't retried too many times\n let retryCount = handshakeCoordinator.getRetryCount(for: peerID)\n if retryCount < 3 {\n handshakeCoordinator.incrementRetryCount(for: peerID)\n DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { [weak self] in\n self?.initiateNoiseHandshake(with: peerID)\n }\n } else {\n SecureLogger.log(\"Max retries reached for \\(peerID), clearing pending messages\", category: SecureLogger.handshake, level: .warning)\n collectionsQueue.async(flags: .barrier) { [weak self] in\n self?.pendingPrivateMessages[peerID]?.removeAll()\n }\n handshakeCoordinator.resetHandshakeState(for: peerID)\n }\n }\n }\n return\n }\n \n // Check if there's a retry delay\n if let retryDelay = handshakeCoordinator.getRetryDelay(for: peerID), retryDelay > 0 {\n SecureLogger.log(\"Waiting \\(retryDelay)s before retrying handshake with \\(peerID)\", category: SecureLogger.handshake, level: .debug)\n DispatchQueue.main.asyncAfter(deadline: .now() + retryDelay) { [weak self] in\n self?.initiateNoiseHandshake(with: peerID)\n }\n return\n }\n \n // Record that we're initiating\n handshakeCoordinator.recordHandshakeInitiation(peerID: peerID)\n handshakeAttemptTimes[peerID] = Date()\n \n // Update connection state to authenticating\n updatePeerConnectionState(peerID, state: .authenticating)\n \n do {\n // Generate handshake initiation message\n let handshakeData = try noiseService.initiateHandshake(with: peerID)\n SecureLogger.logHandshake(\"initiated\", peerID: peerID, success: true)\n \n // Send handshake initiation\n let packet = BitchatPacket(\n type: MessageType.noiseHandshakeInit.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: peerID) ?? Data(), // Add recipient ID for targeted delivery\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: handshakeData,\n signature: nil,\n ttl: 6 // Increased TTL for better delivery on startup\n )\n \n // Track packet for ACK\n trackPacketForAck(packet)\n \n // Try direct delivery first for handshake init\n if !sendDirectToRecipient(packet, recipientPeerID: peerID) {\n // Handshakes are critical - use broadcast as fallback to ensure delivery\n SecureLogger.log(\"Recipient \\(peerID) not directly connected for handshake init, using broadcast\", \n category: SecureLogger.session, level: .info)\n broadcastPacket(packet)\n }\n \n // Schedule a retry check after 5 seconds\n DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) { [weak self] in\n guard let self = self else { return }\n // Check if handshake completed\n if !self.noiseService.hasEstablishedSession(with: peerID) {\n let state = self.handshakeCoordinator.getHandshakeState(for: peerID)\n if case .initiating = state {\n SecureLogger.log(\"Handshake with \\(peerID) not completed after 5s, will retry\", category: SecureLogger.handshake, level: .warning)\n // The handshake coordinator will handle retry logic\n }\n }\n }\n \n } catch NoiseSessionError.alreadyEstablished {\n // Session already established, no need to handshake\n handshakeCoordinator.recordHandshakeSuccess(peerID: peerID)\n } catch {\n // Failed to initiate handshake\n handshakeCoordinator.recordHandshakeFailure(peerID: peerID, reason: error.localizedDescription)\n SecureLogger.logSecurityEvent(.handshakeFailed(peerID: peerID, error: error.localizedDescription))\n }\n }\n \n private func handleNoiseHandshakeMessage(from peerID: String, message: Data, isInitiation: Bool) {\n // Use noiseService directly\n SecureLogger.logHandshake(\"processing \\(isInitiation ? \"init\" : \"response\")\", peerID: peerID, success: true)\n \n // Get current handshake state before processing\n let currentState = handshakeCoordinator.getHandshakeState(for: peerID)\n let hasEstablishedSession = noiseService.hasEstablishedSession(with: peerID)\n SecureLogger.log(\"Current handshake state for \\(peerID): \\(currentState), hasEstablishedSession: \\(hasEstablishedSession)\", category: SecureLogger.noise, level: .info)\n \n // Check for duplicate handshake messages\n if handshakeCoordinator.isDuplicateHandshakeMessage(message) {\n SecureLogger.log(\"Duplicate handshake message from \\(peerID), ignoring\", category: SecureLogger.handshake, level: .debug)\n return\n }\n \n // If this is an initiation, check if we should accept it\n if isInitiation {\n if !handshakeCoordinator.shouldAcceptHandshakeInitiation(myPeerID: myPeerID, remotePeerID: peerID) {\n SecureLogger.log(\"Coordinator says we should not accept handshake from \\(peerID)\", category: SecureLogger.handshake, level: .debug)\n return\n }\n // Record that we're responding\n handshakeCoordinator.recordHandshakeResponse(peerID: peerID)\n \n // Update connection state to authenticating\n updatePeerConnectionState(peerID, state: .authenticating)\n }\n \n do {\n // Process handshake message\n if let response = try noiseService.processHandshakeMessage(from: peerID, message: message) {\n // Handshake response ready to send\n \n // Always send responses as handshake response type\n let packet = BitchatPacket(\n type: MessageType.noiseHandshakeResp.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: peerID) ?? Data(), // Add recipient ID for targeted delivery\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: response,\n signature: nil,\n ttl: 6 // Increased TTL for better delivery on startup\n )\n \n // Track packet for ACK\n trackPacketForAck(packet)\n \n // Try direct delivery first for handshake response\n if !sendDirectToRecipient(packet, recipientPeerID: peerID) {\n // Handshakes are critical - use broadcast as fallback to ensure delivery\n SecureLogger.log(\"Recipient \\(peerID) not directly connected for handshake response, using broadcast\", \n category: SecureLogger.session, level: .info)\n broadcastPacket(packet)\n }\n } else {\n SecureLogger.log(\"No response needed from processHandshakeMessage (isInitiation: \\(isInitiation))\", category: SecureLogger.noise, level: .debug)\n }\n \n // Check if handshake is complete\n let sessionEstablished = noiseService.hasEstablishedSession(with: peerID)\n _ = handshakeCoordinator.getHandshakeState(for: peerID)\n // Handshake state updated\n \n if sessionEstablished {\n SecureLogger.logSecurityEvent(.handshakeCompleted(peerID: peerID))\n // Unlock rotation now that handshake is complete\n unlockRotation()\n \n // Session established successfully\n handshakeCoordinator.recordHandshakeSuccess(peerID: peerID)\n \n // Update session state to established\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[peerID] = .established\n }\n \n // Update connection state to authenticated\n updatePeerConnectionState(peerID, state: .authenticated)\n \n // Clear handshake attempt time on success\n handshakeAttemptTimes.removeValue(forKey: peerID)\n \n // Initialize last successful message time\n lastSuccessfulMessageTime[peerID] = Date()\n SecureLogger.log(\"Initialized lastSuccessfulMessageTime for \\(peerID)\", category: SecureLogger.noise, level: .debug)\n \n // Send identity announcement to this specific peer\n sendNoiseIdentityAnnounce(to: peerID)\n \n // Also broadcast to ensure all peers get it\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n self?.sendNoiseIdentityAnnounce()\n }\n \n // Send regular announce packet after handshake to trigger connect message\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [weak self] in\n self?.sendAnnouncementToPeer(peerID)\n }\n \n // Send any pending private messages\n self.sendPendingPrivateMessages(to: peerID)\n \n // Send any cached store-and-forward messages\n sendCachedMessages(to: peerID)\n }\n } catch NoiseSessionError.alreadyEstablished {\n // Session already established, ignore handshake\n SecureLogger.log(\"Handshake already established with \\(peerID)\", category: SecureLogger.noise, level: .info)\n handshakeCoordinator.recordHandshakeSuccess(peerID: peerID)\n \n // Update session state to established\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[peerID] = .established\n }\n } catch {\n // Handshake failed\n handshakeCoordinator.recordHandshakeFailure(peerID: peerID, reason: error.localizedDescription)\n SecureLogger.logSecurityEvent(.handshakeFailed(peerID: peerID, error: error.localizedDescription))\n SecureLogger.log(\"Handshake failed with \\(peerID): \\(error)\", category: SecureLogger.noise, level: .error)\n \n // Update session state to failed\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[peerID] = .failed(error)\n }\n \n // If handshake failed due to authentication error, clear the session to allow retry\n if case NoiseError.authenticationFailure = error {\n SecureLogger.log(\"Handshake failed with \\(peerID): authenticationFailure - clearing session\", category: SecureLogger.noise, level: .warning)\n cleanupPeerCryptoState(peerID)\n }\n }\n }\n \n private func handleNoiseEncryptedMessage(from peerID: String, encryptedData: Data, originalPacket: BitchatPacket, peripheral: CBPeripheral? = nil) {\n // Use noiseService directly\n \n // For Noise encrypted messages, we need to decrypt first to check the inner packet\n // The outer packet's recipientID might be for routing, not the final recipient\n \n // Create unique identifier for this encrypted message\n let messageHash = encryptedData.prefix(32).hexEncodedString() // Use first 32 bytes as identifier\n let messageKey = \"\\(peerID)-\\(messageHash)\"\n \n // Check if we've already processed this exact encrypted message\n let alreadyProcessed = collectionsQueue.sync(flags: .barrier) {\n if processedNoiseMessages.contains(messageKey) {\n return true\n }\n processedNoiseMessages.insert(messageKey)\n return false\n }\n \n if alreadyProcessed {\n return\n }\n \n do {\n // Decrypt the message\n // Attempting to decrypt\n let decryptedData = try noiseService.decrypt(encryptedData, from: peerID)\n // Successfully decrypted message\n \n // Update last successful message time\n lastSuccessfulMessageTime[peerID] = Date()\n \n // Send protocol ACK after successful decryption (only once per encrypted packet)\n sendProtocolAck(for: originalPacket, to: peerID)\n \n // If we can decrypt messages from this peer, they should be in activePeers\n let wasAdded = collectionsQueue.sync(flags: .barrier) {\n if !self.activePeers.contains(peerID) {\n SecureLogger.log(\"Adding \\(peerID) to activePeers after successful decryption\", category: SecureLogger.noise, level: .info)\n return self.activePeers.insert(peerID).inserted\n }\n return false\n }\n \n if wasAdded {\n // Notify about peer list update\n self.notifyPeerListUpdate()\n }\n \n // Check if this is a special format message (type marker + payload)\n if decryptedData.count > 1 {\n let typeMarker = decryptedData[0]\n \n // Check if this is a delivery ACK with the new format\n if typeMarker == MessageType.deliveryAck.rawValue {\n // Extract the ACK JSON data (skip the type marker)\n let ackData = decryptedData.dropFirst()\n \n // Decode the delivery ACK - try binary first, then JSON\n if let ack = DeliveryAck.fromBinaryData(ackData) {\n SecureLogger.log(\"Received binary delivery ACK via Noise: \\(ack.originalMessageID) from \\(ack.recipientNickname)\", category: SecureLogger.session, level: .debug)\n \n // Process the ACK\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n return\n } else if let ack = DeliveryAck.decode(from: ackData) {\n SecureLogger.log(\"Received JSON delivery ACK via Noise: \\(ack.originalMessageID) from \\(ack.recipientNickname)\", category: SecureLogger.session, level: .debug)\n \n // Process the ACK\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n return\n } else {\n SecureLogger.log(\"Failed to decode delivery ACK via Noise - data size: \\(ackData.count)\", category: SecureLogger.session, level: .warning)\n }\n }\n \n // Check if this is a read receipt with the new format\n else if typeMarker == MessageType.readReceipt.rawValue {\n // Extract the receipt binary data (skip the type marker)\n let receiptData = decryptedData.dropFirst()\n \n // Decode the read receipt from binary\n if let receipt = ReadReceipt.fromBinaryData(receiptData) {\n SecureLogger.log(\"Received binary read receipt via Noise: \\(receipt.originalMessageID) from \\(receipt.readerNickname)\", category: SecureLogger.session, level: .debug)\n \n // Process the read receipt\n DispatchQueue.main.async {\n self.delegate?.didReceiveReadReceipt(receipt)\n }\n return\n } else {\n SecureLogger.log(\"Failed to decode read receipt via Noise - data size: \\(receiptData.count)\", category: SecureLogger.session, level: .warning)\n }\n }\n }\n \n // Try to parse as a full inner packet (for backward compatibility and other message types)\n if let innerPacket = BitchatPacket.from(decryptedData) {\n SecureLogger.log(\"Successfully parsed inner packet - type: \\(MessageType(rawValue: innerPacket.type)?.description ?? \"unknown\"), from: \\(innerPacket.senderID.hexEncodedString()), to: \\(innerPacket.recipientID?.hexEncodedString() ?? \"broadcast\")\", category: SecureLogger.session, level: .debug)\n \n // Process the decrypted inner packet\n // The packet will be handled according to its recipient ID\n // If it's for us, it won't be relayed\n // Pass the peripheral context for proper ACK routing\n handleReceivedPacket(innerPacket, from: peerID, peripheral: peripheral)\n } else {\n SecureLogger.log(\"Failed to parse inner packet from decrypted data\", category: SecureLogger.encryption, level: .warning)\n }\n } catch {\n // Failed to decrypt - might need to re-establish session\n SecureLogger.log(\"Failed to decrypt Noise message from \\(peerID): \\(error)\", category: SecureLogger.encryption, level: .error)\n if !noiseService.hasEstablishedSession(with: peerID) {\n SecureLogger.log(\"No Noise session with \\(peerID), attempting handshake\", category: SecureLogger.noise, level: .info)\n attemptHandshakeIfNeeded(with: peerID, forceIfStale: true)\n } else {\n SecureLogger.log(\"Have session with \\(peerID) but decryption failed\", category: SecureLogger.encryption, level: .warning)\n \n // Send a NACK to inform peer that decryption failed\n sendProtocolNack(for: originalPacket, to: peerID,\n reason: \"Decryption failed\",\n errorCode: .decryptionFailed)\n \n // The NACK handler will take care of clearing sessions and re-establishing\n // Don't initiate anything here to avoid race conditions\n \n // Update UI to show encryption is broken\n DispatchQueue.main.async { [weak self] in\n if let chatVM = self?.delegate as? ChatViewModel {\n chatVM.updateEncryptionStatusForPeer(peerID)\n }\n }\n }\n }\n }\n \n \n // MARK: - Protocol Version Negotiation\n \n private func handleVersionHello(from peerID: String, data: Data, peripheral: CBPeripheral? = nil) {\n // Create a copy to avoid potential race conditions\n let dataCopy = Data(data)\n \n // Safety check for empty data\n guard !dataCopy.isEmpty else {\n SecureLogger.log(\"Received empty version hello data from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n // Check if this peer is reconnecting after disconnect\n if let lastConnected = lastConnectionTime[peerID] {\n let timeSinceLastConnection = Date().timeIntervalSince(lastConnected)\n // Only clear truly stale sessions, not on every reconnect\n if timeSinceLastConnection > 86400.0 { // More than 24 hours since last connection\n // Clear any stale Noise session\n if noiseService.hasEstablishedSession(with: peerID) {\n SecureLogger.log(\"Peer \\(peerID) reconnecting after \\(Int(timeSinceLastConnection))s - clearing stale session\", category: SecureLogger.noise, level: .info)\n cleanupPeerCryptoState(peerID)\n }\n } else if timeSinceLastConnection > 5.0 {\n // Just log the reconnection, don't clear the session\n SecureLogger.log(\"Peer \\(peerID) reconnecting after \\(Int(timeSinceLastConnection))s - keeping existing session\", category: SecureLogger.noise, level: .info)\n }\n }\n \n // Update last connection time\n lastConnectionTime[peerID] = Date()\n \n // Check if we've already negotiated version with this peer\n if let existingVersion = negotiatedVersions[peerID] {\n SecureLogger.log(\"Already negotiated version \\(existingVersion) with \\(peerID), skipping re-negotiation\", \n category: SecureLogger.session, level: .debug)\n // If we have a session, validate it\n if noiseService.hasEstablishedSession(with: peerID) {\n validateNoiseSession(with: peerID)\n }\n return\n }\n \n // Try JSON first if it looks like JSON\n let hello: VersionHello?\n if let firstByte = dataCopy.first, firstByte == 0x7B { // '{' character\n SecureLogger.log(\"Version hello from \\(peerID) appears to be JSON (size: \\(dataCopy.count))\", category: SecureLogger.session, level: .debug)\n hello = VersionHello.decode(from: dataCopy) ?? VersionHello.fromBinaryData(dataCopy)\n } else {\n SecureLogger.log(\"Version hello from \\(peerID) appears to be binary (size: \\(dataCopy.count), first byte: \\(dataCopy.first?.description ?? \"nil\"))\", category: SecureLogger.session, level: .debug)\n hello = VersionHello.fromBinaryData(dataCopy) ?? VersionHello.decode(from: dataCopy)\n }\n \n guard let hello = hello else {\n SecureLogger.log(\"Failed to decode version hello from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n SecureLogger.log(\"Received version hello from \\(peerID): supported versions \\(hello.supportedVersions), preferred \\(hello.preferredVersion)\", \n category: SecureLogger.session, level: .debug)\n \n // Find the best common version\n let ourVersions = Array(ProtocolVersion.supportedVersions)\n if let agreedVersion = ProtocolVersion.negotiateVersion(clientVersions: hello.supportedVersions, serverVersions: ourVersions) {\n // We can communicate! Send ACK\n SecureLogger.log(\"Version negotiation agreed with \\(peerID): v\\(agreedVersion) (client: \\(hello.clientVersion), platform: \\(hello.platform))\", category: SecureLogger.session, level: .info)\n negotiatedVersions[peerID] = agreedVersion\n versionNegotiationState[peerID] = .ackReceived(version: agreedVersion)\n \n let ack = VersionAck(\n agreedVersion: agreedVersion,\n serverVersion: Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String ?? \"1.0\",\n platform: getPlatformString()\n )\n \n sendVersionAck(ack, to: peerID)\n \n // Lazy handshake: No longer initiate handshake after version negotiation\n // Just announce our identity\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in\n guard let self = self else { return }\n \n // Just announce our identity\n self.sendNoiseIdentityAnnounce()\n \n SecureLogger.log(\"Version negotiation complete with \\(peerID) - lazy handshake mode\", \n category: SecureLogger.handshake, level: .info)\n }\n } else {\n // No compatible version\n SecureLogger.log(\"Version negotiation failed with \\(peerID): No compatible version (client supports: \\(hello.supportedVersions))\", category: SecureLogger.session, level: .warning)\n versionNegotiationState[peerID] = .failed(reason: \"No compatible protocol version\")\n \n let ack = VersionAck(\n agreedVersion: 0,\n serverVersion: Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String ?? \"1.0\",\n platform: getPlatformString(),\n rejected: true,\n reason: \"No compatible protocol version. Client supports: \\(hello.supportedVersions), server supports: \\(ourVersions)\"\n )\n \n sendVersionAck(ack, to: peerID)\n \n // Disconnect after a short delay\n if let peripheral = peripheral {\n DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in\n self?.centralManager?.cancelPeripheralConnection(peripheral)\n }\n }\n }\n }\n \n private func handleVersionAck(from peerID: String, data: Data) {\n // Create a copy to avoid potential race conditions\n let dataCopy = Data(data)\n \n // Safety check for empty data\n guard !dataCopy.isEmpty else {\n SecureLogger.log(\"Received empty version ack data from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n // Try JSON first if it looks like JSON\n let ack: VersionAck?\n if let firstByte = dataCopy.first, firstByte == 0x7B { // '{' character\n ack = VersionAck.decode(from: dataCopy) ?? VersionAck.fromBinaryData(dataCopy)\n } else {\n ack = VersionAck.fromBinaryData(dataCopy) ?? VersionAck.decode(from: dataCopy)\n }\n \n guard let ack = ack else {\n SecureLogger.log(\"Failed to decode version ack from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n if ack.rejected {\n SecureLogger.log(\"Version negotiation rejected by \\(peerID): \\(ack.reason ?? \"Unknown reason\")\", \n category: SecureLogger.session, level: .error)\n versionNegotiationState[peerID] = .failed(reason: ack.reason ?? \"Version rejected\")\n \n // Clean up state for incompatible peer\n collectionsQueue.sync(flags: .barrier) {\n _ = self.activePeers.remove(peerID)\n _ = self.peerNicknames.removeValue(forKey: peerID)\n _ = self.lastHeardFromPeer.removeValue(forKey: peerID)\n }\n announcedPeers.remove(peerID)\n \n // Clean up any Noise session\n cleanupPeerCryptoState(peerID)\n \n // Notify delegate about incompatible peer disconnection\n DispatchQueue.main.async { [weak self] in\n self?.delegate?.didDisconnectFromPeer(peerID)\n }\n } else {\n // Version negotiation successful\n negotiatedVersions[peerID] = ack.agreedVersion\n versionNegotiationState[peerID] = .ackReceived(version: ack.agreedVersion)\n \n // If we were the initiator (sent hello first), proceed with Noise handshake\n // Note: Since we're handling their ACK, they initiated, so we should not initiate again\n // The peer who sent hello will initiate the Noise handshake\n }\n }\n \n private func sendVersionHello(to peripheral: CBPeripheral? = nil) {\n let hello = VersionHello(\n clientVersion: Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String ?? \"1.0\",\n platform: getPlatformString()\n )\n \n let helloData = hello.toBinaryData()\n \n let packet = BitchatPacket(\n type: MessageType.versionHello.rawValue,\n ttl: 1, // Version negotiation is direct, no relay\n senderID: myPeerID,\n payload: helloData )\n \n // Mark that we initiated version negotiation\n // We don't know the peer ID yet from peripheral, so we'll track it when we get the response\n \n if let peripheral = peripheral,\n let characteristic = peripheralCharacteristics[peripheral] {\n // Send directly to specific peripheral\n if let data = packet.toBinaryData() {\n writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: nil)\n }\n } else {\n // Broadcast to all\n broadcastPacket(packet)\n }\n }\n \n private func sendVersionAck(_ ack: VersionAck, to peerID: String) {\n let ackData = ack.toBinaryData()\n \n let packet = BitchatPacket(\n type: MessageType.versionAck.rawValue,\n senderID: Data(myPeerID.utf8),\n recipientID: Data(peerID.utf8),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: ackData,\n signature: nil,\n ttl: 1 // Direct response, no relay\n )\n \n // Version ACKs should go directly to the peer when possible\n if !sendDirectToRecipient(packet, recipientPeerID: peerID) {\n // Fall back to selective relay if direct delivery fails\n sendViaSelectiveRelay(packet, recipientPeerID: peerID)\n }\n }\n \n private func getPlatformString() -> String {\n #if os(iOS)\n return \"iOS\"\n #elseif os(macOS)\n return \"macOS\"\n #else\n return \"Unknown\"\n #endif\n }\n \n // MARK: - Protocol ACK/NACK Handling\n \n private func handleProtocolAck(from peerID: String, data: Data) {\n guard let ack = ProtocolAck.fromBinaryData(data) else {\n SecureLogger.log(\"Failed to decode protocol ACK from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n SecureLogger.log(\"Received protocol ACK from \\(peerID) for packet \\(ack.originalPacketID), type: \\(ack.packetType), ackID: \\(ack.ackID)\", \n category: SecureLogger.session, level: .debug)\n \n // Remove from pending ACKs and mark as acknowledged\n // Note: readUUID returns uppercase, but we track with lowercase\n let normalizedPacketID = ack.originalPacketID.lowercased()\n _ = collectionsQueue.sync(flags: .barrier) {\n pendingAcks.removeValue(forKey: normalizedPacketID)\n }\n \n // Track this packet as acknowledged to prevent future retries\n acknowledgedPacketsLock.lock()\n acknowledgedPackets.insert(ack.originalPacketID)\n // Keep only recent acknowledged packets (last 1000)\n if acknowledgedPackets.count > 1000 {\n // Remove oldest entries (this is approximate since Set doesn't maintain order)\n acknowledgedPackets = Set(Array(acknowledgedPackets).suffix(1000))\n }\n acknowledgedPacketsLock.unlock()\n \n // Handle specific packet types that need ACK confirmation\n if let messageType = MessageType(rawValue: ack.packetType) {\n switch messageType {\n case .noiseHandshakeInit, .noiseHandshakeResp:\n SecureLogger.log(\"Handshake confirmed by \\(peerID)\", category: SecureLogger.handshake, level: .info)\n case .noiseEncrypted:\n // Encrypted message confirmed\n break\n default:\n break\n }\n }\n }\n \n private func handleProtocolNack(from peerID: String, data: Data) {\n guard let nack = ProtocolNack.fromBinaryData(data) else {\n SecureLogger.log(\"Failed to decode protocol NACK from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n SecureLogger.log(\"Received protocol NACK from \\(peerID) for packet \\(nack.originalPacketID): \\(nack.reason)\", \n category: SecureLogger.session, level: .warning)\n \n // Remove from pending ACKs\n _ = collectionsQueue.sync(flags: .barrier) {\n pendingAcks.removeValue(forKey: nack.originalPacketID)\n }\n \n // Handle specific error codes\n if let errorCode = ProtocolNack.ErrorCode(rawValue: nack.errorCode) {\n switch errorCode {\n case .decryptionFailed:\n // Session is out of sync - both sides need to clear and re-establish\n SecureLogger.log(\"Decryption failed at \\(peerID), clearing session and re-establishing\", \n category: SecureLogger.encryption, level: .warning)\n \n // Clear our session state and handshake coordinator state\n cleanupPeerCryptoState(peerID)\n handshakeCoordinator.resetHandshakeState(for: peerID)\n \n // Update connection state\n updatePeerConnectionState(peerID, state: .connected)\n \n // Use deterministic role assignment to prevent race conditions\n let shouldInitiate = handshakeCoordinator.determineHandshakeRole(\n myPeerID: myPeerID,\n remotePeerID: peerID\n ) == .initiator\n \n if shouldInitiate {\n // Small delay to ensure both sides have cleared state\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n guard let self = self else { return }\n SecureLogger.log(\"Initiating handshake after decryption failure with \\(peerID)\", \n category: SecureLogger.session, level: .info)\n self.attemptHandshakeIfNeeded(with: peerID, forceIfStale: true)\n }\n } else {\n // Send identity announcement to signal we're ready\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n guard let self = self else { return }\n SecureLogger.log(\"Sending identity announcement after decryption failure to \\(peerID)\", \n category: SecureLogger.session, level: .info)\n self.sendNoiseIdentityAnnounce(to: peerID)\n }\n }\n case .sessionExpired:\n // Clear session and re-handshake\n SecureLogger.log(\"Session expired at \\(peerID), clearing and re-handshaking\", \n category: SecureLogger.session, level: .warning)\n cleanupPeerCryptoState(peerID)\n handshakeCoordinator.resetHandshakeState(for: peerID)\n attemptHandshakeIfNeeded(with: peerID, forceIfStale: true)\n default:\n break\n }\n }\n }\n \n private func handleHandshakeRequest(from peerID: String, data: Data) {\n guard let request = HandshakeRequest.fromBinaryData(data) else {\n SecureLogger.log(\"Failed to decode handshake request from \\(peerID)\", category: SecureLogger.noise, level: .error)\n return\n }\n \n // Verify this request is for us\n guard request.targetID == myPeerID else {\n // This request is not for us, might need to relay\n return\n }\n \n SecureLogger.log(\"Received handshake request from \\(request.requesterID) (\\(request.requesterNickname)) with \\(request.pendingMessageCount) pending messages\", \n category: SecureLogger.noise, level: .info)\n \n // Don't show handshake request notification in UI\n // User requested to remove this notification\n /*\n DispatchQueue.main.async { [weak self] in\n if let chatVM = self?.delegate as? ChatViewModel {\n // Notify the UI that someone wants to send messages\n chatVM.handleHandshakeRequest(from: request.requesterID, \n nickname: request.requesterNickname,\n pendingCount: request.pendingMessageCount)\n }\n }\n */\n \n // Check if we already have a session\n if noiseService.hasEstablishedSession(with: peerID) {\n // We already have a session, no action needed\n SecureLogger.log(\"Already have session with \\(peerID), ignoring handshake request\", category: SecureLogger.noise, level: .debug)\n return\n }\n \n // Apply tie-breaker logic for handshake initiation\n if myPeerID < peerID {\n // We have lower ID, initiate handshake\n SecureLogger.log(\"Initiating handshake with \\(peerID) in response to handshake request\", category: SecureLogger.noise, level: .info)\n initiateNoiseHandshake(with: peerID)\n } else {\n // We have higher ID, send identity announce to prompt them\n SecureLogger.log(\"Sending identity announce to \\(peerID) in response to handshake request\", category: SecureLogger.noise, level: .info)\n sendNoiseIdentityAnnounce(to: peerID)\n }\n }\n \n // Send protocol ACK for important packets\n private func sendProtocolAck(for packet: BitchatPacket, to peerID: String, hopCount: UInt8 = 0) {\n // Generate packet ID from packet content hash\n let packetID = generatePacketID(for: packet)\n \n // Debug: log packet details\n _ = packet.senderID.prefix(4).hexEncodedString()\n _ = packet.recipientID?.prefix(4).hexEncodedString() ?? \"nil\"\n // Send protocol ACK\n \n let ack = ProtocolAck(\n originalPacketID: packetID,\n senderID: packet.senderID.hexEncodedString(),\n receiverID: myPeerID,\n packetType: packet.type,\n hopCount: hopCount\n )\n \n let ackPacket = BitchatPacket(\n type: MessageType.protocolAck.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: peerID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: ack.toBinaryData(),\n signature: nil,\n ttl: 3 // ACKs don't need to travel far\n )\n \n // Protocol ACKs should go directly to the sender when possible\n if !sendDirectToRecipient(ackPacket, recipientPeerID: peerID) {\n // Fall back to selective relay if direct delivery fails\n sendViaSelectiveRelay(ackPacket, recipientPeerID: peerID)\n }\n }\n \n // Send protocol NACK for failed packets\n private func sendProtocolNack(for packet: BitchatPacket, to peerID: String, reason: String, errorCode: ProtocolNack.ErrorCode) {\n let packetID = generatePacketID(for: packet)\n \n let nack = ProtocolNack(\n originalPacketID: packetID,\n senderID: packet.senderID.hexEncodedString(),\n receiverID: myPeerID,\n packetType: packet.type,\n reason: reason,\n errorCode: errorCode\n )\n \n let nackPacket = BitchatPacket(\n type: MessageType.protocolNack.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: peerID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: nack.toBinaryData(),\n signature: nil,\n ttl: 3 // NACKs don't need to travel far\n )\n \n // Protocol NACKs should go directly to the sender when possible\n if !sendDirectToRecipient(nackPacket, recipientPeerID: peerID) {\n // Fall back to selective relay if direct delivery fails\n sendViaSelectiveRelay(nackPacket, recipientPeerID: peerID)\n }\n }\n \n // Generate unique packet ID from immutable packet fields\n private func generatePacketID(for packet: BitchatPacket) -> String {\n // Use only immutable fields for ID generation to ensure consistency\n // across network hops (TTL changes, so can't use full packet data)\n \n // Create a deterministic ID using SHA256 of immutable fields\n var data = Data()\n data.append(packet.senderID)\n data.append(contentsOf: withUnsafeBytes(of: packet.timestamp) { Array($0) })\n data.append(packet.type)\n // Add first 32 bytes of payload for uniqueness\n data.append(packet.payload.prefix(32))\n \n let hash = SHA256.hash(data: data)\n let hashData = Data(hash)\n \n // Take first 16 bytes for UUID format\n let bytes = Array(hashData.prefix(16))\n \n // Format as UUID\n let p1 = String(format: \"%02x%02x%02x%02x\", bytes[0], bytes[1], bytes[2], bytes[3])\n let p2 = String(format: \"%02x%02x\", bytes[4], bytes[5])\n let p3 = String(format: \"%02x%02x\", bytes[6], bytes[7])\n let p4 = String(format: \"%02x%02x\", bytes[8], bytes[9])\n let p5 = String(format: \"%02x%02x%02x%02x%02x%02x\", bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15])\n \n let result = \"\\(p1)-\\(p2)-\\(p3)-\\(p4)-\\(p5)\"\n \n // Generated packet ID for tracking\n \n return result\n }\n \n // Track packets that need ACKs\n private func trackPacketForAck(_ packet: BitchatPacket) {\n let packetID = generatePacketID(for: packet)\n \n // Debug: log packet details\n _ = packet.senderID.prefix(4).hexEncodedString()\n _ = packet.recipientID?.prefix(4).hexEncodedString() ?? \"nil\"\n // Track packet for ACK\n \n collectionsQueue.sync(flags: .barrier) {\n pendingAcks[packetID] = (packet: packet, timestamp: Date(), retries: 0)\n }\n \n // Schedule timeout check with initial delay (using exponential backoff starting at 1s)\n let initialDelay = calculateExponentialBackoff(retry: 1) // 1 second initial delay\n DispatchQueue.main.asyncAfter(deadline: .now() + initialDelay) { [weak self] in\n self?.checkAckTimeout(for: packetID)\n }\n }\n \n // Check for ACK timeout and retry if needed\n private func checkAckTimeout(for packetID: String) {\n // Check if already acknowledged\n acknowledgedPacketsLock.lock()\n let isAcknowledged = acknowledgedPackets.contains(packetID)\n acknowledgedPacketsLock.unlock()\n \n if isAcknowledged {\n // Already acknowledged, remove from pending and don't retry\n _ = collectionsQueue.sync(flags: .barrier) {\n pendingAcks.removeValue(forKey: packetID)\n }\n SecureLogger.log(\"Packet \\(packetID) already acknowledged, cancelling retries\", \n category: SecureLogger.session, level: .debug)\n return\n }\n \n collectionsQueue.sync(flags: .barrier) { [weak self] in\n guard let self = self,\n let pending = self.pendingAcks[packetID] else { return }\n \n // Check if this is a handshake packet and we already have an established session\n if pending.packet.type == MessageType.noiseHandshakeInit.rawValue ||\n pending.packet.type == MessageType.noiseHandshakeResp.rawValue {\n // Extract peer ID from packet\n let peerID = pending.packet.recipientID?.hexEncodedString() ?? \"\"\n if !peerID.isEmpty && self.noiseService.hasEstablishedSession(with: peerID) {\n // We have an established session, don't retry handshake packets\n SecureLogger.log(\"Not retrying handshake packet \\(packetID) - session already established with \\(peerID)\", \n category: SecureLogger.handshake, level: .info)\n self.pendingAcks.removeValue(forKey: packetID)\n return\n }\n }\n \n if pending.retries < self.maxAckRetries {\n // Retry sending the packet\n SecureLogger.log(\"ACK timeout for packet \\(packetID), retrying (attempt \\(pending.retries + 1))\", \n category: SecureLogger.session, level: .warning)\n \n self.pendingAcks[packetID] = (packet: pending.packet, \n timestamp: Date(), \n retries: pending.retries + 1)\n \n // Resend the packet\n SecureLogger.log(\"Resending packet due to ACK timeout (retry \\(pending.retries + 1))\", \n category: SecureLogger.session, level: .debug)\n DispatchQueue.main.async {\n self.broadcastPacket(pending.packet)\n }\n \n // Schedule next timeout check with exponential backoff\n let backoffDelay = self.calculateExponentialBackoff(retry: pending.retries + 1)\n DispatchQueue.main.asyncAfter(deadline: .now() + backoffDelay) {\n self.checkAckTimeout(for: packetID)\n }\n } else {\n // Max retries reached, give up\n SecureLogger.log(\"Max ACK retries reached for packet \\(packetID), giving up\", \n category: SecureLogger.session, level: .error)\n self.pendingAcks.removeValue(forKey: packetID)\n \n // Could notify upper layer about delivery failure here\n }\n }\n }\n \n // Check all pending ACKs for timeouts (called by timer)\n private func checkAckTimeouts() {\n let now = Date()\n var timedOutPackets: [String] = []\n \n collectionsQueue.sync {\n for (packetID, pending) in pendingAcks {\n if now.timeIntervalSince(pending.timestamp) > ackTimeout {\n timedOutPackets.append(packetID)\n }\n }\n }\n \n // Process timeouts outside the sync block\n for packetID in timedOutPackets {\n checkAckTimeout(for: packetID)\n }\n }\n \n // Update RSSI for all connected peripherals\n private func updateAllPeripheralRSSI() {\n \n // Read RSSI for all connected peripherals\n for (_, peripheral) in connectedPeripherals {\n if peripheral.state == .connected {\n peripheral.readRSSI()\n }\n }\n }\n \n // Check peer availability based on last heard time\n private func checkPeerAvailability() {\n let now = Date()\n var stateChanges: [(peerID: String, available: Bool)] = []\n \n collectionsQueue.sync(flags: .barrier) {\n // Check all active peers\n for peerID in activePeers {\n let lastHeard = lastHeardFromPeer[peerID] ?? Date.distantPast\n let timeSinceLastHeard = now.timeIntervalSince(lastHeard)\n let wasAvailable = peerAvailabilityState[peerID] ?? true\n \n // Check connection state\n let connectionState = peerConnectionStates[peerID] ?? .disconnected\n let hasConnection = connectionState == .connected || connectionState == .authenticating || connectionState == .authenticated\n \n // Peer is available if:\n // 1. We have an active connection (regardless of last heard time), OR\n // 2. We're authenticated and heard from them within timeout period\n let isAvailable = hasConnection || \n (connectionState == .authenticated && timeSinceLastHeard < peerAvailabilityTimeout)\n \n if wasAvailable != isAvailable {\n peerAvailabilityState[peerID] = isAvailable\n stateChanges.append((peerID: peerID, available: isAvailable))\n }\n }\n \n // Remove availability state for peers no longer active\n let inactivePeers = peerAvailabilityState.keys.filter { !activePeers.contains($0) }\n for peerID in inactivePeers {\n peerAvailabilityState.removeValue(forKey: peerID)\n }\n }\n \n // Notify about availability changes\n for change in stateChanges {\n SecureLogger.log(\"Peer \\(change.peerID) availability changed to: \\(change.available)\", \n category: SecureLogger.session, level: .info)\n \n // Notify delegate about availability change\n DispatchQueue.main.async { [weak self] in\n self?.delegate?.peerAvailabilityChanged(change.peerID, available: change.available)\n }\n }\n }\n \n // Update peer availability when we hear from them\n private func updatePeerAvailability(_ peerID: String) {\n collectionsQueue.sync(flags: .barrier) {\n lastHeardFromPeer[peerID] = Date()\n \n // If peer wasn't available, mark as available now\n if peerAvailabilityState[peerID] != true {\n peerAvailabilityState[peerID] = true\n \n SecureLogger.log(\"Peer \\(peerID) marked as available after hearing from them\", \n category: SecureLogger.session, level: .info)\n \n DispatchQueue.main.async { [weak self] in\n self?.delegate?.peerAvailabilityChanged(peerID, available: true)\n }\n }\n }\n }\n \n // Check if a peer is currently available\n func isPeerAvailable(_ peerID: String) -> Bool {\n return collectionsQueue.sync {\n return peerAvailabilityState[peerID] ?? false\n }\n }\n \n private func sendNoiseIdentityAnnounce(to specificPeerID: String? = nil) {\n // Rate limit identity announcements\n let now = Date()\n \n // If targeting a specific peer, check rate limit\n if let peerID = specificPeerID {\n if let lastTime = lastIdentityAnnounceTimes[peerID],\n now.timeIntervalSince(lastTime) < identityAnnounceMinInterval {\n // Too soon, skip this announcement\n return\n }\n lastIdentityAnnounceTimes[peerID] = now\n } else {\n // Broadcasting to all - check global rate limit\n if let lastTime = lastIdentityAnnounceTimes[\"*broadcast*\"],\n now.timeIntervalSince(lastTime) < identityAnnounceMinInterval {\n return\n }\n lastIdentityAnnounceTimes[\"*broadcast*\"] = now\n }\n \n // Get our Noise static public key and signing public key\n let staticKey = noiseService.getStaticPublicKeyData()\n let signingKey = noiseService.getSigningPublicKeyData()\n \n // Get nickname from delegate\n let nickname = (delegate as? ChatViewModel)?.nickname ?? \"Anonymous\"\n \n // Create the binding data to sign (peerID + publicKey + timestamp)\n let timestampData = String(Int64(now.timeIntervalSince1970 * 1000)).data(using: .utf8)!\n let bindingData = myPeerID.data(using: .utf8)! + staticKey + timestampData\n \n // Sign the binding with our Ed25519 signing key\n let signature = noiseService.signData(bindingData) ?? Data()\n \n // Create the identity announcement\n let announcement = NoiseIdentityAnnouncement(\n peerID: myPeerID,\n publicKey: staticKey,\n signingPublicKey: signingKey,\n nickname: nickname,\n timestamp: now,\n previousPeerID: previousPeerID,\n signature: signature\n )\n \n // Encode the announcement\n let announcementData = announcement.toBinaryData()\n \n let packet = BitchatPacket(\n type: MessageType.noiseIdentityAnnounce.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: specificPeerID.flatMap { Data(hexString: $0) }, // Targeted or broadcast\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: announcementData,\n signature: nil,\n ttl: adaptiveTTL )\n \n if let targetPeer = specificPeerID {\n SecureLogger.log(\"Sending targeted identity announce to \\(targetPeer)\", \n category: SecureLogger.noise, level: .info)\n \n // Try direct delivery for targeted announces\n if !sendDirectToRecipient(packet, recipientPeerID: targetPeer) {\n // Fall back to selective relay if direct delivery fails\n SecureLogger.log(\"Recipient \\(targetPeer) not directly connected for identity announce, using relay\", \n category: SecureLogger.session, level: .info)\n sendViaSelectiveRelay(packet, recipientPeerID: targetPeer)\n }\n } else {\n SecureLogger.log(\"Broadcasting identity announce to all peers\", \n category: SecureLogger.noise, level: .info)\n broadcastPacket(packet)\n }\n }\n \n // Removed sendPacket method - all packets should use broadcastPacket to ensure mesh delivery\n \n // Send private message using Noise Protocol\n private func sendPrivateMessageViaNoise(_ content: String, to recipientPeerID: String, recipientNickname: String, messageID: String? = nil) {\n SecureLogger.log(\"sendPrivateMessageViaNoise called - content: '\\(content.prefix(50))...', to: \\(recipientPeerID), messageID: \\(messageID ?? \"nil\")\", \n category: SecureLogger.noise, level: .info)\n \n // Use per-peer encryption queue to prevent nonce desynchronization\n let encryptionQueue = getEncryptionQueue(for: recipientPeerID)\n \n encryptionQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Use noiseService directly\n \n // Check if we have a Noise session with this peer\n let hasSession = self.noiseService.hasEstablishedSession(with: recipientPeerID)\n \n // Check if session is stale (no successful communication for a while)\n var sessionIsStale = false\n if hasSession {\n let lastSuccess = lastSuccessfulMessageTime[recipientPeerID] ?? Date.distantPast\n let sessionAge = Date().timeIntervalSince(lastSuccess)\n // Increase session validity to 24 hours - sessions should persist across temporary disconnects\n if sessionAge > 86400.0 { // More than 24 hours since last successful message\n sessionIsStale = true\n SecureLogger.log(\"Session with \\(recipientPeerID) is stale (last success: \\(Int(sessionAge))s ago), will re-establish\", category: SecureLogger.noise, level: .info)\n }\n }\n \n if !hasSession || sessionIsStale {\n if sessionIsStale {\n // Clear stale session first\n cleanupPeerCryptoState(recipientPeerID)\n }\n \n // Update state to handshakeQueued\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[recipientPeerID] = .handshakeQueued\n }\n \n SecureLogger.log(\"No valid Noise session with \\(recipientPeerID), initiating handshake (lazy mode)\", category: SecureLogger.noise, level: .info)\n \n // Notify UI that we're establishing encryption\n DispatchQueue.main.async { [weak self] in\n if let chatVM = self?.delegate as? ChatViewModel {\n // This will update the UI to show \"establishing encryption\" state\n chatVM.updateEncryptionStatusForPeer(recipientPeerID)\n }\n }\n \n // Queue message for sending after handshake completes\n collectionsQueue.sync(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n if self.pendingPrivateMessages[recipientPeerID] == nil {\n self.pendingPrivateMessages[recipientPeerID] = []\n }\n self.pendingPrivateMessages[recipientPeerID]?.append((content, recipientNickname, messageID ?? UUID().uuidString))\n let count = self.pendingPrivateMessages[recipientPeerID]?.count ?? 0\n SecureLogger.log(\"Queued private message for \\(recipientPeerID), \\(count) messages pending\", category: SecureLogger.noise, level: .info)\n }\n \n // Send handshake request to notify recipient of pending messages\n sendHandshakeRequest(to: recipientPeerID, pendingCount: UInt8(pendingPrivateMessages[recipientPeerID]?.count ?? 1))\n \n // Apply tie-breaker logic for handshake initiation\n if myPeerID < recipientPeerID {\n // We have lower ID, initiate handshake\n initiateNoiseHandshake(with: recipientPeerID)\n } else {\n // We have higher ID, send targeted identity announce to prompt them to initiate\n sendNoiseIdentityAnnounce(to: recipientPeerID)\n }\n \n return\n }\n \n // Use provided message ID or generate a new one\n let msgID = messageID ?? UUID().uuidString\n \n // Check if we're already processing this message\n let sendKey = \"\\(msgID)-\\(recipientPeerID)\"\n let alreadySending = self.collectionsQueue.sync(flags: .barrier) {\n if self.recentlySentMessages.contains(sendKey) {\n return true\n }\n self.recentlySentMessages.insert(sendKey)\n // Clean up old entries after 10 seconds\n DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) { [weak self] in\n self?.collectionsQueue.sync(flags: .barrier) {\n _ = self?.recentlySentMessages.remove(sendKey)\n }\n }\n return false\n }\n \n if alreadySending {\n return\n }\n \n \n // Get sender nickname from delegate\n let nickname = self.delegate as? ChatViewModel\n let senderNick = nickname?.nickname ?? self.myPeerID\n \n // Create the inner message\n let message = BitchatMessage(\n id: msgID,\n sender: senderNick,\n content: content,\n timestamp: Date(),\n isRelay: false,\n isPrivate: true,\n recipientNickname: recipientNickname,\n senderPeerID: myPeerID\n )\n \n // Use binary payload format to match the receiver's expectations\n guard let messageData = message.toBinaryPayload() else { \n return \n }\n \n // Create inner packet\n let innerPacket = BitchatPacket(\n type: MessageType.message.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: recipientPeerID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: messageData,\n signature: nil,\n ttl: self.adaptiveTTL // Inner packet needs valid TTL for processing after decryption\n )\n \n guard let innerData = innerPacket.toBinaryData() else { return }\n \n do {\n // Encrypt with Noise\n SecureLogger.log(\"Encrypting private message \\(msgID) for \\(recipientPeerID)\", category: SecureLogger.encryption, level: .debug)\n let encryptedData = try noiseService.encrypt(innerData, for: recipientPeerID)\n SecureLogger.log(\"Successfully encrypted message, size: \\(encryptedData.count)\", category: SecureLogger.encryption, level: .debug)\n \n // Update last successful message time\n lastSuccessfulMessageTime[recipientPeerID] = Date()\n \n // Send as Noise encrypted message\n let outerPacket = BitchatPacket(\n type: MessageType.noiseEncrypted.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: recipientPeerID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: encryptedData,\n signature: nil,\n ttl: adaptiveTTL )\n \n SecureLogger.log(\"Sending encrypted private message \\(msgID) to \\(recipientPeerID)\", category: SecureLogger.session, level: .info)\n \n // Track packet for ACK\n trackPacketForAck(outerPacket)\n \n // Try direct delivery first\n if !sendDirectToRecipient(outerPacket, recipientPeerID: recipientPeerID) {\n // Recipient not directly connected, use selective relay\n SecureLogger.log(\"Recipient \\(recipientPeerID) not directly connected, using relay strategy\", \n category: SecureLogger.session, level: .info)\n sendViaSelectiveRelay(outerPacket, recipientPeerID: recipientPeerID)\n }\n } catch {\n // Failed to encrypt message\n SecureLogger.log(\"Failed to encrypt private message \\(msgID) for \\(recipientPeerID): \\(error)\", category: SecureLogger.encryption, level: .error)\n }\n } // End of encryptionQueue.async\n }\n \n // MARK: - Targeted Message Delivery\n \n private func sendDirectToRecipient(_ packet: BitchatPacket, recipientPeerID: String) -> Bool {\n // Try to send directly to the recipient if they're connected\n if let peripheral = connectedPeripherals[recipientPeerID],\n let characteristic = peripheralCharacteristics[peripheral],\n peripheral.state == .connected {\n \n guard let data = packet.toBinaryData() else { return false }\n \n // Send only to the intended recipient\n writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: recipientPeerID)\n SecureLogger.log(\"Sent private message directly to \\(recipientPeerID)\", category: SecureLogger.session, level: .info)\n return true\n }\n \n // Check if recipient is connected as a central (we're peripheral)\n if !subscribedCentrals.isEmpty {\n // We can't target specific centrals, so return false to trigger relay\n return false\n }\n \n return false\n }\n \n private func sendHandshakeRequest(to targetPeerID: String, pendingCount: UInt8) {\n // Create handshake request\n let request = HandshakeRequest(requesterID: myPeerID,\n requesterNickname: (delegate as? ChatViewModel)?.nickname ?? myPeerID,\n targetID: targetPeerID,\n pendingMessageCount: pendingCount)\n \n let requestData = request.toBinaryData()\n \n // Create packet for handshake request\n let packet = BitchatPacket(type: MessageType.handshakeRequest.rawValue,\n ttl: 6,\n senderID: myPeerID,\n payload: requestData)\n \n // Try direct delivery first\n if sendDirectToRecipient(packet, recipientPeerID: targetPeerID) {\n SecureLogger.log(\"Sent handshake request directly to \\(targetPeerID)\", category: SecureLogger.noise, level: .info)\n } else {\n // Use selective relay if direct delivery fails\n sendViaSelectiveRelay(packet, recipientPeerID: targetPeerID)\n SecureLogger.log(\"Sent handshake request via relay to \\(targetPeerID)\", category: SecureLogger.noise, level: .info)\n }\n }\n \n private func selectBestRelayPeers(excluding: String, maxPeers: Int = 3) -> [String] {\n // Select peers with best RSSI for relay, excluding the target recipient\n var candidates: [(peerID: String, rssi: Int)] = []\n \n for (peerID, _) in connectedPeripherals {\n if peerID != excluding && peerID != myPeerID {\n let rssiValue = peerRSSI[peerID]?.intValue ?? -80\n candidates.append((peerID: peerID, rssi: rssiValue))\n }\n }\n \n // Sort by RSSI (strongest first) and take top N\n candidates.sort { $0.rssi > $1.rssi }\n return candidates.prefix(maxPeers).map { $0.peerID }\n }\n \n private func sendViaSelectiveRelay(_ packet: BitchatPacket, recipientPeerID: String) {\n // Select best relay candidates\n let relayPeers = selectBestRelayPeers(excluding: recipientPeerID)\n \n if relayPeers.isEmpty {\n // No relay candidates, fall back to broadcast\n SecureLogger.log(\"No relay candidates for private message to \\(recipientPeerID), using broadcast\", \n category: SecureLogger.session, level: .warning)\n broadcastPacket(packet)\n return\n }\n \n // Limit TTL for relay\n var relayPacket = packet\n relayPacket.ttl = min(packet.ttl, 2) // Max 2 hops for private message relay\n \n guard let data = relayPacket.toBinaryData() else { return }\n \n // Send to selected relay peers\n var sentCount = 0\n for relayPeerID in relayPeers {\n if let peripheral = connectedPeripherals[relayPeerID],\n let characteristic = peripheralCharacteristics[peripheral],\n peripheral.state == .connected {\n writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: relayPeerID)\n sentCount += 1\n }\n }\n \n SecureLogger.log(\"Sent private message to \\(sentCount) relay peers (targeting \\(recipientPeerID))\", \n category: SecureLogger.session, level: .info)\n \n // If no relays worked, fall back to broadcast\n if sentCount == 0 {\n SecureLogger.log(\"Failed to send to relay peers, falling back to broadcast\", \n category: SecureLogger.session, level: .warning)\n broadcastPacket(packet)\n }\n }\n \n // MARK: - Connection Pool Management\n \n private func findLeastRecentlyUsedPeripheral() -> String? {\n var lruPeripheralID: String?\n var oldestActivityTime = Date()\n \n for (peripheralID, peripheral) in connectionPool {\n // Only consider connected peripherals\n guard peripheral.state == .connected else { continue }\n \n // Skip if this peripheral has an active peer connection\n if let peerID = peerIDByPeripheralID[peripheralID],\n activePeers.contains(peerID) {\n continue\n }\n \n // Find the least recently used peripheral based on last activity\n if let lastActivity = lastActivityByPeripheralID[peripheralID],\n lastActivity < oldestActivityTime {\n oldestActivityTime = lastActivity\n lruPeripheralID = peripheralID\n } else if lastActivityByPeripheralID[peripheralID] == nil {\n // If no activity recorded, it's a candidate for removal\n lruPeripheralID = peripheralID\n break\n }\n }\n \n return lruPeripheralID\n }\n \n // Track activity for peripherals\n private func updatePeripheralActivity(_ peripheralID: String) {\n lastActivityByPeripheralID[peripheralID] = Date()\n }\n}\n"], ["/bitchat/bitchat/Services/NoiseEncryptionService.swift", "//\n// NoiseEncryptionService.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # NoiseEncryptionService\n///\n/// High-level encryption service that manages Noise Protocol sessions for secure\n/// peer-to-peer communication in BitChat. Acts as the bridge between the transport\n/// layer (BluetoothMeshService) and the cryptographic layer (NoiseProtocol).\n///\n/// ## Overview\n/// This service provides a simplified API for establishing and managing encrypted\n/// channels between peers. It handles:\n/// - Static identity key management\n/// - Session lifecycle (creation, maintenance, teardown)\n/// - Message encryption/decryption\n/// - Peer authentication and fingerprint tracking\n/// - Automatic rekeying for forward secrecy\n///\n/// ## Architecture\n/// The service operates at multiple levels:\n/// 1. **Identity Management**: Persistent Curve25519 keys stored in Keychain\n/// 2. **Session Management**: Per-peer Noise sessions with state tracking\n/// 3. **Message Processing**: Encryption/decryption with proper framing\n/// 4. **Security Features**: Rate limiting, fingerprint verification\n///\n/// ## Key Features\n///\n/// ### Identity Keys\n/// - Static Curve25519 key pair for Noise XX pattern\n/// - Ed25519 signing key pair for additional authentication\n/// - Keys persisted securely in iOS/macOS Keychain\n/// - Fingerprints derived from SHA256 of public keys\n///\n/// ### Session Management\n/// - Lazy session creation (on-demand when sending messages)\n/// - Automatic session recovery after disconnections\n/// - Configurable rekey intervals for forward secrecy\n/// - Graceful handling of simultaneous handshakes\n///\n/// ### Security Properties\n/// - Forward secrecy via ephemeral keys in handshakes\n/// - Mutual authentication via static key exchange\n/// - Protection against replay attacks\n/// - Rate limiting to prevent DoS attacks\n///\n/// ## Encryption Flow\n/// ```\n/// 1. Message arrives for encryption\n/// 2. Check if session exists for peer\n/// 3. If not, initiate Noise handshake\n/// 4. Once established, encrypt message\n/// 5. Add message type header for protocol handling\n/// 6. Return encrypted payload for transmission\n/// ```\n///\n/// ## Integration Points\n/// - **BluetoothMeshService**: Calls this service for all private messages\n/// - **ChatViewModel**: Monitors encryption status for UI indicators\n/// - **NoiseHandshakeCoordinator**: Prevents handshake race conditions\n/// - **KeychainManager**: Secure storage for identity keys\n///\n/// ## Thread Safety\n/// - Concurrent read access via reader-writer queue\n/// - Session operations protected by per-peer queues\n/// - Atomic updates for critical state changes\n///\n/// ## Error Handling\n/// - Graceful fallback for encryption failures\n/// - Clear error messages for debugging\n/// - Automatic retry with exponential backoff\n/// - User notification for critical failures\n///\n/// ## Performance Considerations\n/// - Sessions cached in memory for fast access\n/// - Minimal allocations in hot paths\n/// - Efficient binary message format\n/// - Background queue for CPU-intensive operations\n///\n\nimport Foundation\nimport CryptoKit\nimport os.log\n\n// MARK: - Encryption Status\n\n/// Represents the current encryption status of a peer connection.\n/// Used for UI indicators and decision-making about message handling.\nenum EncryptionStatus: Equatable {\n case none // Failed or incompatible\n case noHandshake // No handshake attempted yet\n case noiseHandshaking // Currently establishing\n case noiseSecured // Established but not verified\n case noiseVerified // Established and verified\n \n var icon: String? { // Made optional to hide icon when no handshake\n switch self {\n case .none:\n return \"lock.slash\" // Failed handshake\n case .noHandshake:\n return nil // No icon when no handshake attempted\n case .noiseHandshaking:\n return \"lock.rotation\"\n case .noiseSecured:\n return \"lock.fill\" // Changed from \"lock\" to \"lock.fill\" for filled lock\n case .noiseVerified:\n return \"lock.shield.fill\" // Changed to filled version for consistency\n }\n }\n \n var description: String {\n switch self {\n case .none:\n return \"Encryption failed\"\n case .noHandshake:\n return \"Not encrypted\"\n case .noiseHandshaking:\n return \"Establishing encryption...\"\n case .noiseSecured:\n return \"Encrypted\"\n case .noiseVerified:\n return \"Encrypted & Verified\"\n }\n }\n}\n\n// MARK: - Noise Encryption Service\n\n/// Manages end-to-end encryption for BitChat using the Noise Protocol Framework.\n/// Provides a high-level API for establishing secure channels between peers,\n/// handling all cryptographic operations transparently.\n/// - Important: This service maintains the device's cryptographic identity\nclass NoiseEncryptionService {\n // Static identity key (persistent across sessions)\n private let staticIdentityKey: Curve25519.KeyAgreement.PrivateKey\n public let staticIdentityPublicKey: Curve25519.KeyAgreement.PublicKey\n \n // Ed25519 signing key (persistent across sessions)\n private let signingKey: Curve25519.Signing.PrivateKey\n public let signingPublicKey: Curve25519.Signing.PublicKey\n \n // Session manager\n private let sessionManager: NoiseSessionManager\n \n // Peer fingerprints (SHA256 hash of static public key)\n private var peerFingerprints: [String: String] = [:] // peerID -> fingerprint\n private var fingerprintToPeerID: [String: String] = [:] // fingerprint -> peerID\n \n // Thread safety\n private let serviceQueue = DispatchQueue(label: \"chat.bitchat.noise.service\", attributes: .concurrent)\n \n // Security components\n private let rateLimiter = NoiseRateLimiter()\n \n // Session maintenance\n private var rekeyTimer: Timer?\n private let rekeyCheckInterval: TimeInterval = 60.0 // Check every minute\n \n // Callbacks\n var onPeerAuthenticated: ((String, String) -> Void)? // peerID, fingerprint\n var onHandshakeRequired: ((String) -> Void)? // peerID needs handshake\n \n init() {\n // Load or create static identity key (ONLY from keychain)\n let loadedKey: Curve25519.KeyAgreement.PrivateKey\n \n // Try to load from keychain\n if let identityData = KeychainManager.shared.getIdentityKey(forKey: \"noiseStaticKey\"),\n let key = try? Curve25519.KeyAgreement.PrivateKey(rawRepresentation: identityData) {\n loadedKey = key\n SecureLogger.logKeyOperation(\"load\", keyType: \"noiseStaticKey\", success: true)\n }\n // If no identity exists, create new one\n else {\n loadedKey = Curve25519.KeyAgreement.PrivateKey()\n let keyData = loadedKey.rawRepresentation\n \n // Save to keychain\n let saved = KeychainManager.shared.saveIdentityKey(keyData, forKey: \"noiseStaticKey\")\n SecureLogger.logKeyOperation(\"create\", keyType: \"noiseStaticKey\", success: saved)\n }\n \n // Now assign the final value\n self.staticIdentityKey = loadedKey\n self.staticIdentityPublicKey = staticIdentityKey.publicKey\n \n // Load or create signing key pair\n let loadedSigningKey: Curve25519.Signing.PrivateKey\n \n // Try to load from keychain\n if let signingData = KeychainManager.shared.getIdentityKey(forKey: \"ed25519SigningKey\"),\n let key = try? Curve25519.Signing.PrivateKey(rawRepresentation: signingData) {\n loadedSigningKey = key\n SecureLogger.logKeyOperation(\"load\", keyType: \"ed25519SigningKey\", success: true)\n }\n // If no signing key exists, create new one\n else {\n loadedSigningKey = Curve25519.Signing.PrivateKey()\n let keyData = loadedSigningKey.rawRepresentation\n \n // Save to keychain\n let saved = KeychainManager.shared.saveIdentityKey(keyData, forKey: \"ed25519SigningKey\")\n SecureLogger.logKeyOperation(\"create\", keyType: \"ed25519SigningKey\", success: saved)\n }\n \n // Now assign the signing keys\n self.signingKey = loadedSigningKey\n self.signingPublicKey = signingKey.publicKey\n \n // Initialize session manager\n self.sessionManager = NoiseSessionManager(localStaticKey: staticIdentityKey)\n \n // Set up session callbacks\n sessionManager.onSessionEstablished = { [weak self] peerID, remoteStaticKey in\n self?.handleSessionEstablished(peerID: peerID, remoteStaticKey: remoteStaticKey)\n }\n \n // Start session maintenance timer\n startRekeyTimer()\n }\n \n // MARK: - Public Interface\n \n /// Get our static public key for sharing\n func getStaticPublicKeyData() -> Data {\n return staticIdentityPublicKey.rawRepresentation\n }\n \n /// Get our signing public key for sharing\n func getSigningPublicKeyData() -> Data {\n return signingPublicKey.rawRepresentation\n }\n \n /// Get our identity fingerprint\n func getIdentityFingerprint() -> String {\n let hash = SHA256.hash(data: staticIdentityPublicKey.rawRepresentation)\n return hash.map { String(format: \"%02x\", $0) }.joined()\n }\n \n /// Get peer's public key data\n func getPeerPublicKeyData(_ peerID: String) -> Data? {\n return sessionManager.getRemoteStaticKey(for: peerID)?.rawRepresentation\n }\n \n /// Clear persistent identity (for panic mode)\n func clearPersistentIdentity() {\n // Clear from keychain\n let deletedStatic = KeychainManager.shared.deleteIdentityKey(forKey: \"noiseStaticKey\")\n let deletedSigning = KeychainManager.shared.deleteIdentityKey(forKey: \"ed25519SigningKey\")\n SecureLogger.logKeyOperation(\"delete\", keyType: \"identity keys\", success: deletedStatic && deletedSigning)\n SecureLogger.log(\"Panic mode activated - identity cleared\", category: SecureLogger.security, level: .warning)\n // Stop rekey timer\n stopRekeyTimer()\n }\n \n /// Sign data with our Ed25519 signing key\n func signData(_ data: Data) -> Data? {\n do {\n let signature = try signingKey.signature(for: data)\n return signature\n } catch {\n SecureLogger.logError(error, context: \"Failed to sign data\", category: SecureLogger.noise)\n return nil\n }\n }\n \n /// Verify signature with a peer's Ed25519 public key\n func verifySignature(_ signature: Data, for data: Data, publicKey: Data) -> Bool {\n do {\n let signingPublicKey = try Curve25519.Signing.PublicKey(rawRepresentation: publicKey)\n return signingPublicKey.isValidSignature(signature, for: data)\n } catch {\n SecureLogger.logError(error, context: \"Failed to verify signature\", category: SecureLogger.noise)\n return false\n }\n }\n \n // MARK: - Handshake Management\n \n /// Initiate a Noise handshake with a peer\n func initiateHandshake(with peerID: String) throws -> Data {\n \n // Validate peer ID\n guard NoiseSecurityValidator.validatePeerID(peerID) else {\n SecureLogger.logSecurityEvent(.authenticationFailed(peerID: peerID), level: .warning)\n throw NoiseSecurityError.invalidPeerID\n }\n \n // Check rate limit\n guard rateLimiter.allowHandshake(from: peerID) else {\n SecureLogger.logSecurityEvent(.authenticationFailed(peerID: \"Rate limited: \\(peerID)\"), level: .warning)\n throw NoiseSecurityError.rateLimitExceeded\n }\n \n SecureLogger.logSecurityEvent(.handshakeStarted(peerID: peerID))\n \n // Return raw handshake data without wrapper\n // The Noise protocol handles its own message format\n let handshakeData = try sessionManager.initiateHandshake(with: peerID)\n return handshakeData\n }\n \n /// Process an incoming handshake message\n func processHandshakeMessage(from peerID: String, message: Data) throws -> Data? {\n \n // Validate peer ID\n guard NoiseSecurityValidator.validatePeerID(peerID) else {\n SecureLogger.logSecurityEvent(.authenticationFailed(peerID: peerID), level: .warning)\n throw NoiseSecurityError.invalidPeerID\n }\n \n // Validate message size\n guard NoiseSecurityValidator.validateHandshakeMessageSize(message) else {\n SecureLogger.logSecurityEvent(.handshakeFailed(peerID: peerID, error: \"Message too large\"), level: .warning)\n throw NoiseSecurityError.messageTooLarge\n }\n \n // Check rate limit\n guard rateLimiter.allowHandshake(from: peerID) else {\n SecureLogger.logSecurityEvent(.authenticationFailed(peerID: \"Rate limited: \\(peerID)\"), level: .warning)\n throw NoiseSecurityError.rateLimitExceeded\n }\n \n // For handshakes, we process the raw data directly without NoiseMessage wrapper\n // The Noise protocol handles its own message format\n let responsePayload = try sessionManager.handleIncomingHandshake(from: peerID, message: message)\n \n \n // Return raw response without wrapper\n return responsePayload\n }\n \n /// Check if we have an established session with a peer\n func hasEstablishedSession(with peerID: String) -> Bool {\n return sessionManager.getSession(for: peerID)?.isEstablished() ?? false\n }\n \n /// Check if we have a session (established or handshaking) with a peer\n func hasSession(with peerID: String) -> Bool {\n return sessionManager.getSession(for: peerID) != nil\n }\n \n // MARK: - Encryption/Decryption\n \n /// Encrypt data for a specific peer\n func encrypt(_ data: Data, for peerID: String) throws -> Data {\n // Validate message size\n guard NoiseSecurityValidator.validateMessageSize(data) else {\n throw NoiseSecurityError.messageTooLarge\n }\n \n // Check rate limit\n guard rateLimiter.allowMessage(from: peerID) else {\n throw NoiseSecurityError.rateLimitExceeded\n }\n \n // Check if we have an established session\n guard hasEstablishedSession(with: peerID) else {\n // Signal that handshake is needed\n onHandshakeRequired?(peerID)\n throw NoiseEncryptionError.handshakeRequired\n }\n \n return try sessionManager.encrypt(data, for: peerID)\n }\n \n /// Decrypt data from a specific peer\n func decrypt(_ data: Data, from peerID: String) throws -> Data {\n // Validate message size\n guard NoiseSecurityValidator.validateMessageSize(data) else {\n throw NoiseSecurityError.messageTooLarge\n }\n \n // Check rate limit\n guard rateLimiter.allowMessage(from: peerID) else {\n throw NoiseSecurityError.rateLimitExceeded\n }\n \n // Check if we have an established session\n guard hasEstablishedSession(with: peerID) else {\n throw NoiseEncryptionError.sessionNotEstablished\n }\n \n return try sessionManager.decrypt(data, from: peerID)\n }\n \n // MARK: - Peer Management\n \n /// Get fingerprint for a peer\n func getPeerFingerprint(_ peerID: String) -> String? {\n return serviceQueue.sync {\n return peerFingerprints[peerID]\n }\n }\n \n /// Get peer ID for a fingerprint\n func getPeerID(for fingerprint: String) -> String? {\n return serviceQueue.sync {\n return fingerprintToPeerID[fingerprint]\n }\n }\n \n /// Remove a peer session\n func removePeer(_ peerID: String) {\n sessionManager.removeSession(for: peerID)\n \n serviceQueue.sync(flags: .barrier) {\n if let fingerprint = peerFingerprints[peerID] {\n fingerprintToPeerID.removeValue(forKey: fingerprint)\n }\n peerFingerprints.removeValue(forKey: peerID)\n }\n \n SecureLogger.logSecurityEvent(.sessionExpired(peerID: peerID))\n }\n \n /// Migrate session when peer ID changes\n func migratePeerSession(from oldPeerID: String, to newPeerID: String, fingerprint: String) {\n // First update the fingerprint mappings\n serviceQueue.sync(flags: .barrier) {\n // Remove old mapping\n if let oldFingerprint = peerFingerprints[oldPeerID], oldFingerprint == fingerprint {\n peerFingerprints.removeValue(forKey: oldPeerID)\n }\n \n // Add new mapping\n peerFingerprints[newPeerID] = fingerprint\n fingerprintToPeerID[fingerprint] = newPeerID\n }\n \n // Migrate the session in session manager\n sessionManager.migrateSession(from: oldPeerID, to: newPeerID)\n }\n \n // MARK: - Private Helpers\n \n private func handleSessionEstablished(peerID: String, remoteStaticKey: Curve25519.KeyAgreement.PublicKey) {\n // Calculate fingerprint\n let fingerprint = calculateFingerprint(for: remoteStaticKey)\n \n // Store fingerprint mapping\n serviceQueue.sync(flags: .barrier) {\n peerFingerprints[peerID] = fingerprint\n fingerprintToPeerID[fingerprint] = peerID\n }\n \n // Log security event\n SecureLogger.logSecurityEvent(.handshakeCompleted(peerID: peerID))\n \n // Notify about authentication\n onPeerAuthenticated?(peerID, fingerprint)\n }\n \n private func calculateFingerprint(for publicKey: Curve25519.KeyAgreement.PublicKey) -> String {\n let hash = SHA256.hash(data: publicKey.rawRepresentation)\n return hash.map { String(format: \"%02x\", $0) }.joined()\n }\n \n // MARK: - Session Maintenance\n \n private func startRekeyTimer() {\n rekeyTimer = Timer.scheduledTimer(withTimeInterval: rekeyCheckInterval, repeats: true) { [weak self] _ in\n self?.checkSessionsForRekey()\n }\n }\n \n private func stopRekeyTimer() {\n rekeyTimer?.invalidate()\n rekeyTimer = nil\n }\n \n private func checkSessionsForRekey() {\n let sessionsNeedingRekey = sessionManager.getSessionsNeedingRekey()\n \n for (peerID, needsRekey) in sessionsNeedingRekey where needsRekey {\n \n // Attempt to rekey the session\n do {\n try sessionManager.initiateRekey(for: peerID)\n SecureLogger.log(\"Key rotation initiated for peer: \\(peerID)\", category: SecureLogger.security, level: .info)\n \n // Signal that handshake is needed\n onHandshakeRequired?(peerID)\n } catch {\n SecureLogger.logError(error, context: \"Failed to initiate rekey for peer: \\(peerID)\", category: SecureLogger.session)\n }\n }\n }\n \n deinit {\n stopRekeyTimer()\n }\n}\n\n// MARK: - Protocol Message Types for Noise\n\n/// Message types for the Noise encryption protocol layer.\n/// These types wrap the underlying BitChat protocol messages with encryption metadata.\nenum NoiseMessageType: UInt8 {\n case handshakeInitiation = 0x10\n case handshakeResponse = 0x11\n case handshakeFinal = 0x12\n case encryptedMessage = 0x13\n case sessionRenegotiation = 0x14\n}\n\n// MARK: - Noise Message Wrapper\n\n/// Container for encrypted messages in the Noise protocol.\n/// Provides versioning and type information for proper message handling.\n/// The actual message content is encrypted in the payload field.\nstruct NoiseMessage: Codable {\n let type: UInt8\n let sessionID: String // Random ID for this handshake session\n let payload: Data\n \n init(type: NoiseMessageType, sessionID: String, payload: Data) {\n self.type = type.rawValue\n self.sessionID = sessionID\n self.payload = payload\n }\n \n func encode() -> Data? {\n do {\n let encoded = try JSONEncoder().encode(self)\n return encoded\n } catch {\n return nil\n }\n }\n \n static func decode(from data: Data) -> NoiseMessage? {\n return try? JSONDecoder().decode(NoiseMessage.self, from: data)\n }\n \n static func decodeWithError(from data: Data) -> NoiseMessage? {\n do {\n let decoded = try JSONDecoder().decode(NoiseMessage.self, from: data)\n return decoded\n } catch {\n return nil\n }\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUInt8(type)\n data.appendUUID(sessionID)\n data.appendData(payload)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> NoiseMessage? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n var offset = 0\n \n guard let type = dataCopy.readUInt8(at: &offset),\n let sessionID = dataCopy.readUUID(at: &offset),\n let payload = dataCopy.readData(at: &offset) else { return nil }\n \n guard let messageType = NoiseMessageType(rawValue: type) else { return nil }\n \n return NoiseMessage(type: messageType, sessionID: sessionID, payload: payload)\n }\n}\n\n// MARK: - Errors\n\nenum NoiseEncryptionError: Error {\n case handshakeRequired\n case sessionNotEstablished\n}\n"], ["/bitchat/bitchat/Utils/SecureLogger.swift", "//\n// SecureLogger.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport os.log\n\n/// Centralized security-aware logging framework\n/// Provides safe logging that filters sensitive data and security events\nclass SecureLogger {\n \n // MARK: - Log Categories\n \n private static let subsystem = \"chat.bitchat\"\n \n static let noise = OSLog(subsystem: subsystem, category: \"noise\")\n static let encryption = OSLog(subsystem: subsystem, category: \"encryption\")\n static let keychain = OSLog(subsystem: subsystem, category: \"keychain\")\n static let session = OSLog(subsystem: subsystem, category: \"session\")\n static let security = OSLog(subsystem: subsystem, category: \"security\")\n static let handshake = OSLog(subsystem: subsystem, category: \"handshake\")\n \n // MARK: - Timestamp Formatter\n \n private static let timestampFormatter: DateFormatter = {\n let formatter = DateFormatter()\n formatter.dateFormat = \"HH:mm:ss.SSS\"\n formatter.timeZone = TimeZone.current\n return formatter\n }()\n \n // MARK: - Cached Regex Patterns\n \n private static let fingerprintPattern = #/[a-fA-F0-9]{64}/#\n private static let base64Pattern = #/[A-Za-z0-9+/]{40,}={0,2}/#\n private static let passwordPattern = #/password[\"\\s:=]+[\"']?[^\"'\\s]+[\"']?/#\n private static let peerIDPattern = #/peerID: ([a-zA-Z0-9]{8})[a-zA-Z0-9]+/#\n \n // MARK: - Sanitization Cache\n \n private static let sanitizationCache: NSCache = {\n let cache = NSCache()\n cache.countLimit = 100 // Keep last 100 sanitized strings\n return cache\n }()\n private static let cacheQueue = DispatchQueue(label: \"chat.bitchat.securelogger.cache\", attributes: .concurrent)\n \n // MARK: - Log Levels\n \n enum LogLevel {\n case debug\n case info\n case warning\n case error\n case fault\n \n var osLogType: OSLogType {\n switch self {\n case .debug: return .debug\n case .info: return .info\n case .warning: return .default\n case .error: return .error\n case .fault: return .fault\n }\n }\n }\n \n // MARK: - Security Event Types\n \n enum SecurityEvent {\n case handshakeStarted(peerID: String)\n case handshakeCompleted(peerID: String)\n case handshakeFailed(peerID: String, error: String)\n case sessionExpired(peerID: String)\n case authenticationFailed(peerID: String)\n \n var message: String {\n switch self {\n case .handshakeStarted(let peerID):\n return \"Handshake started with peer: \\(sanitize(peerID))\"\n case .handshakeCompleted(let peerID):\n return \"Handshake completed with peer: \\(sanitize(peerID))\"\n case .handshakeFailed(let peerID, let error):\n return \"Handshake failed with peer: \\(sanitize(peerID)), error: \\(error)\"\n case .sessionExpired(let peerID):\n return \"Session expired for peer: \\(sanitize(peerID))\"\n case .authenticationFailed(let peerID):\n return \"Authentication failed for peer: \\(sanitize(peerID))\"\n }\n }\n }\n \n // MARK: - Public Logging Methods\n \n /// Log a security event\n static func logSecurityEvent(_ event: SecurityEvent, level: LogLevel = .info, \n file: String = #file, line: Int = #line, function: String = #function) {\n let location = formatLocation(file: file, line: line, function: function)\n let message = \"\\(location) \\(event.message)\"\n \n #if DEBUG\n os_log(\"%{public}@\", log: security, type: level.osLogType, message)\n #else\n // In release, use private logging to prevent sensitive data exposure\n os_log(\"%{private}@\", log: security, type: level.osLogType, message)\n #endif\n }\n \n /// Log general messages with automatic sensitive data filtering\n static func log(_ message: String, category: OSLog = noise, level: LogLevel = .debug,\n file: String = #file, line: Int = #line, function: String = #function) {\n let location = formatLocation(file: file, line: line, function: function)\n let sanitized = sanitize(\"\\(location) \\(message)\")\n \n #if DEBUG\n os_log(\"%{public}@\", log: category, type: level.osLogType, sanitized)\n #else\n // In release builds, only log non-debug messages\n if level != .debug {\n os_log(\"%{private}@\", log: category, type: level.osLogType, sanitized)\n }\n #endif\n }\n \n /// Log errors with context\n static func logError(_ error: Error, context: String, category: OSLog = noise,\n file: String = #file, line: Int = #line, function: String = #function) {\n let location = formatLocation(file: file, line: line, function: function)\n let sanitized = sanitize(context)\n let errorDesc = sanitize(error.localizedDescription)\n \n #if DEBUG\n os_log(\"%{public}@ Error in %{public}@: %{public}@\", log: category, type: .error, location, sanitized, errorDesc)\n #else\n os_log(\"%{private}@ Error in %{private}@: %{private}@\", log: category, type: .error, location, sanitized, errorDesc)\n #endif\n }\n \n // MARK: - Private Helpers\n \n /// Format location information for logging\n private static func formatLocation(file: String, line: Int, function: String) -> String {\n let fileName = (file as NSString).lastPathComponent\n let timestamp = timestampFormatter.string(from: Date())\n return \"[\\(timestamp)] [\\(fileName):\\(line) \\(function)]\"\n }\n \n /// Sanitize strings to remove potentially sensitive data\n private static func sanitize(_ input: String) -> String {\n let key = input as NSString\n \n // Check cache first\n var cachedValue: String?\n cacheQueue.sync {\n cachedValue = sanitizationCache.object(forKey: key) as String?\n }\n \n if let cached = cachedValue {\n return cached\n }\n \n // Perform sanitization\n var sanitized = input\n \n // Remove full fingerprints (keep first 8 chars for debugging)\n sanitized = sanitized.replacing(fingerprintPattern) { match in\n let fingerprint = String(match.output)\n return String(fingerprint.prefix(8)) + \"...\"\n }\n \n // Remove base64 encoded data that might be keys\n sanitized = sanitized.replacing(base64Pattern) { _ in\n \"\"\n }\n \n // Remove potential passwords (assuming they're in quotes or after \"password:\")\n sanitized = sanitized.replacing(passwordPattern) { _ in\n \"password: \"\n }\n \n // Truncate peer IDs to first 8 characters\n sanitized = sanitized.replacing(peerIDPattern) { match in\n \"peerID: \\(match.1)...\"\n }\n \n // Cache the result\n cacheQueue.async(flags: .barrier) {\n sanitizationCache.setObject(sanitized as NSString, forKey: key)\n }\n \n return sanitized\n }\n \n /// Sanitize individual values\n private static func sanitize(_ value: T) -> String {\n let stringValue = String(describing: value)\n return sanitize(stringValue)\n }\n}\n\n// MARK: - Convenience Extensions\n\nextension SecureLogger {\n \n /// Log handshake events\n static func logHandshake(_ phase: String, peerID: String, success: Bool = true,\n file: String = #file, line: Int = #line, function: String = #function) {\n if success {\n log(\"Handshake \\(phase) with peer: \\(peerID)\", category: session, level: .info,\n file: file, line: line, function: function)\n } else {\n log(\"Handshake \\(phase) failed with peer: \\(peerID)\", category: session, level: .warning,\n file: file, line: line, function: function)\n }\n }\n \n /// Log encryption operations\n static func logEncryption(_ operation: String, success: Bool = true,\n file: String = #file, line: Int = #line, function: String = #function) {\n let level: LogLevel = success ? .debug : .error\n log(\"Encryption operation '\\(operation)' \\(success ? \"succeeded\" : \"failed\")\", \n category: encryption, level: level, file: file, line: line, function: function)\n }\n \n /// Log key management operations\n static func logKeyOperation(_ operation: String, keyType: String, success: Bool = true,\n file: String = #file, line: Int = #line, function: String = #function) {\n let level: LogLevel = success ? .info : .error\n log(\"Key operation '\\(operation)' for \\(keyType) \\(success ? \"succeeded\" : \"failed\")\", \n category: keychain, level: level, file: file, line: line, function: function)\n }\n}\n\n// MARK: - Migration Helper\n\n/// Helper to migrate from print statements to SecureLogger\n/// Usage: Replace print(...) with secureLog(...)\nfunc secureLog(_ items: Any..., separator: String = \" \", terminator: String = \"\\n\",\n file: String = #file, line: Int = #line, function: String = #function) {\n #if DEBUG\n let message = items.map { String(describing: $0) }.joined(separator: separator)\n SecureLogger.log(message, level: .debug, file: file, line: line, function: function)\n #endif\n}\n"], ["/bitchat/bitchat/Identity/SecureIdentityStateManager.swift", "//\n// SecureIdentityStateManager.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # SecureIdentityStateManager\n///\n/// Manages the persistent storage and retrieval of identity mappings with\n/// encryption at rest. This singleton service maintains the relationship between\n/// ephemeral peer IDs, cryptographic fingerprints, and social identities.\n///\n/// ## Overview\n/// The SecureIdentityStateManager provides a secure, privacy-preserving way to\n/// maintain identity relationships across app launches. It implements:\n/// - Encrypted storage of identity mappings\n/// - In-memory caching for performance\n/// - Thread-safe access patterns\n/// - Automatic debounced persistence\n///\n/// ## Architecture\n/// The manager operates at three levels:\n/// 1. **In-Memory State**: Fast access to active identities\n/// 2. **Encrypted Cache**: Persistent storage in Keychain\n/// 3. **Privacy Controls**: User-configurable persistence settings\n///\n/// ## Security Features\n///\n/// ### Encryption at Rest\n/// - Identity cache encrypted with AES-GCM\n/// - Unique 256-bit encryption key per device\n/// - Key stored separately in Keychain\n/// - No plaintext identity data on disk\n///\n/// ### Privacy by Design\n/// - Persistence is optional (user-controlled)\n/// - Minimal data retention\n/// - No cloud sync or backup\n/// - Automatic cleanup of stale entries\n///\n/// ### Thread Safety\n/// - Concurrent read access via GCD barriers\n/// - Write operations serialized\n/// - Atomic state updates\n/// - No data races or corruption\n///\n/// ## Data Model\n/// Manages three types of identity data:\n/// 1. **Ephemeral Sessions**: Current peer connections\n/// 2. **Cryptographic Identities**: Public keys and fingerprints\n/// 3. **Social Identities**: User-assigned names and trust\n///\n/// ## Persistence Strategy\n/// - Changes batched and debounced (2-second window)\n/// - Automatic save on app termination\n/// - Crash-resistant with atomic writes\n/// - Migration support for schema changes\n///\n/// ## Usage Patterns\n/// ```swift\n/// // Register a new peer identity\n/// manager.registerPeerIdentity(peerID, publicKey, fingerprint)\n/// \n/// // Update social identity\n/// manager.updateSocialIdentity(fingerprint, nickname, trustLevel)\n/// \n/// // Query identity\n/// let identity = manager.resolvePeerIdentity(peerID)\n/// ```\n///\n/// ## Performance Optimizations\n/// - In-memory cache eliminates Keychain roundtrips\n/// - Debounced saves reduce I/O operations\n/// - Efficient data structures for lookups\n/// - Background queue for expensive operations\n///\n/// ## Privacy Considerations\n/// - Users can disable all persistence\n/// - Identity cache can be wiped instantly\n/// - No analytics or telemetry\n/// - Ephemeral mode for high-risk users\n///\n/// ## Future Enhancements\n/// - Selective identity export\n/// - Cross-device identity sync (optional)\n/// - Identity attestation support\n/// - Advanced conflict resolution\n///\n\nimport Foundation\nimport CryptoKit\n\n/// Singleton manager for secure identity state persistence and retrieval.\n/// Provides thread-safe access to identity mappings with encryption at rest.\n/// All identity data is stored encrypted in the device Keychain for security.\nclass SecureIdentityStateManager {\n static let shared = SecureIdentityStateManager()\n \n private let keychain = KeychainManager.shared\n private let cacheKey = \"bitchat.identityCache.v2\"\n private let encryptionKeyName = \"identityCacheEncryptionKey\"\n \n // In-memory state\n private var ephemeralSessions: [String: EphemeralIdentity] = [:]\n private var cryptographicIdentities: [String: CryptographicIdentity] = [:]\n private var cache: IdentityCache = IdentityCache()\n \n // Pending actions before handshake\n private var pendingActions: [String: PendingActions] = [:]\n \n // Thread safety\n private let queue = DispatchQueue(label: \"bitchat.identity.state\", attributes: .concurrent)\n \n // Debouncing for keychain saves\n private var saveTimer: Timer?\n private let saveDebounceInterval: TimeInterval = 2.0 // Save at most once every 2 seconds\n private var pendingSave = false\n \n // Encryption key\n private let encryptionKey: SymmetricKey\n \n private init() {\n // Generate or retrieve encryption key from keychain\n let loadedKey: SymmetricKey\n \n // Try to load from keychain\n if let keyData = keychain.getIdentityKey(forKey: encryptionKeyName) {\n loadedKey = SymmetricKey(data: keyData)\n SecureLogger.logKeyOperation(\"load\", keyType: \"identity cache encryption key\", success: true)\n }\n // Generate new key if needed\n else {\n loadedKey = SymmetricKey(size: .bits256)\n let keyData = loadedKey.withUnsafeBytes { Data($0) }\n // Save to keychain\n let saved = keychain.saveIdentityKey(keyData, forKey: encryptionKeyName)\n SecureLogger.logKeyOperation(\"generate\", keyType: \"identity cache encryption key\", success: saved)\n }\n \n self.encryptionKey = loadedKey\n \n // Load identity cache on init\n loadIdentityCache()\n }\n \n // MARK: - Secure Loading/Saving\n \n func loadIdentityCache() {\n guard let encryptedData = keychain.getIdentityKey(forKey: cacheKey) else {\n // No existing cache, start fresh\n return\n }\n \n do {\n let sealedBox = try AES.GCM.SealedBox(combined: encryptedData)\n let decryptedData = try AES.GCM.open(sealedBox, using: encryptionKey)\n cache = try JSONDecoder().decode(IdentityCache.self, from: decryptedData)\n } catch {\n // Log error but continue with empty cache\n SecureLogger.logError(error, context: \"Failed to load identity cache\", category: SecureLogger.security)\n }\n }\n \n deinit {\n // Force save any pending changes\n forceSave()\n }\n \n func saveIdentityCache() {\n // Mark that we need to save\n pendingSave = true\n \n // Cancel any existing timer\n saveTimer?.invalidate()\n \n // Schedule a new save after the debounce interval\n saveTimer = Timer.scheduledTimer(withTimeInterval: saveDebounceInterval, repeats: false) { [weak self] _ in\n self?.performSave()\n }\n }\n \n private func performSave() {\n guard pendingSave else { return }\n pendingSave = false\n \n do {\n let data = try JSONEncoder().encode(cache)\n let sealedBox = try AES.GCM.seal(data, using: encryptionKey)\n let saved = keychain.saveIdentityKey(sealedBox.combined!, forKey: cacheKey)\n if saved {\n SecureLogger.log(\"Identity cache saved to keychain\", category: SecureLogger.security, level: .debug)\n }\n } catch {\n SecureLogger.logError(error, context: \"Failed to save identity cache\", category: SecureLogger.security)\n }\n }\n \n // Force immediate save (for app termination)\n func forceSave() {\n saveTimer?.invalidate()\n if pendingSave {\n performSave()\n }\n }\n \n // MARK: - Identity Resolution\n \n func resolveIdentity(peerID: String, claimedNickname: String) -> IdentityHint {\n queue.sync {\n // Check if we have candidates based on nickname\n if let fingerprints = cache.nicknameIndex[claimedNickname] {\n if fingerprints.count == 1 {\n return .likelyKnown(fingerprint: fingerprints.first!)\n } else {\n return .ambiguous(candidates: fingerprints)\n }\n }\n return .unknown\n }\n }\n \n // MARK: - Social Identity Management\n \n func getSocialIdentity(for fingerprint: String) -> SocialIdentity? {\n queue.sync {\n return cache.socialIdentities[fingerprint]\n }\n }\n \n func getAllSocialIdentities() -> [SocialIdentity] {\n queue.sync {\n return Array(cache.socialIdentities.values)\n }\n }\n \n func updateSocialIdentity(_ identity: SocialIdentity) {\n queue.async(flags: .barrier) {\n self.cache.socialIdentities[identity.fingerprint] = identity\n \n // Update nickname index\n if let existingIdentity = self.cache.socialIdentities[identity.fingerprint] {\n // Remove old nickname from index if changed\n if existingIdentity.claimedNickname != identity.claimedNickname {\n self.cache.nicknameIndex[existingIdentity.claimedNickname]?.remove(identity.fingerprint)\n if self.cache.nicknameIndex[existingIdentity.claimedNickname]?.isEmpty == true {\n self.cache.nicknameIndex.removeValue(forKey: existingIdentity.claimedNickname)\n }\n }\n }\n \n // Add new nickname to index\n if self.cache.nicknameIndex[identity.claimedNickname] == nil {\n self.cache.nicknameIndex[identity.claimedNickname] = Set()\n }\n self.cache.nicknameIndex[identity.claimedNickname]?.insert(identity.fingerprint)\n \n // Save to keychain\n self.saveIdentityCache()\n }\n }\n \n // MARK: - Favorites Management\n \n func getFavorites() -> Set {\n queue.sync {\n let favorites = cache.socialIdentities.values\n .filter { $0.isFavorite }\n .map { $0.fingerprint }\n return Set(favorites)\n }\n }\n \n func setFavorite(_ fingerprint: String, isFavorite: Bool) {\n queue.async(flags: .barrier) {\n if var identity = self.cache.socialIdentities[fingerprint] {\n identity.isFavorite = isFavorite\n self.cache.socialIdentities[fingerprint] = identity\n } else {\n // Create new social identity for this fingerprint\n let newIdentity = SocialIdentity(\n fingerprint: fingerprint,\n localPetname: nil,\n claimedNickname: \"Unknown\",\n trustLevel: .unknown,\n isFavorite: isFavorite,\n isBlocked: false,\n notes: nil\n )\n self.cache.socialIdentities[fingerprint] = newIdentity\n }\n self.saveIdentityCache()\n }\n }\n \n func isFavorite(fingerprint: String) -> Bool {\n queue.sync {\n return cache.socialIdentities[fingerprint]?.isFavorite ?? false\n }\n }\n \n // MARK: - Blocked Users Management\n \n func isBlocked(fingerprint: String) -> Bool {\n queue.sync {\n return cache.socialIdentities[fingerprint]?.isBlocked ?? false\n }\n }\n \n func setBlocked(_ fingerprint: String, isBlocked: Bool) {\n SecureLogger.log(\"User \\(isBlocked ? \"blocked\" : \"unblocked\"): \\(fingerprint)\", category: SecureLogger.security, level: .info)\n \n queue.async(flags: .barrier) {\n if var identity = self.cache.socialIdentities[fingerprint] {\n identity.isBlocked = isBlocked\n if isBlocked {\n identity.isFavorite = false // Can't be both favorite and blocked\n }\n self.cache.socialIdentities[fingerprint] = identity\n } else {\n // Create new social identity for this fingerprint\n let newIdentity = SocialIdentity(\n fingerprint: fingerprint,\n localPetname: nil,\n claimedNickname: \"Unknown\",\n trustLevel: .unknown,\n isFavorite: false,\n isBlocked: isBlocked,\n notes: nil\n )\n self.cache.socialIdentities[fingerprint] = newIdentity\n }\n self.saveIdentityCache()\n }\n }\n \n // MARK: - Ephemeral Session Management\n \n func registerEphemeralSession(peerID: String, handshakeState: HandshakeState = .none) {\n queue.async(flags: .barrier) {\n self.ephemeralSessions[peerID] = EphemeralIdentity(\n peerID: peerID,\n sessionStart: Date(),\n handshakeState: handshakeState\n )\n }\n }\n \n func updateHandshakeState(peerID: String, state: HandshakeState) {\n queue.async(flags: .barrier) {\n self.ephemeralSessions[peerID]?.handshakeState = state\n \n // If handshake completed, update last interaction\n if case .completed(let fingerprint) = state {\n self.cache.lastInteractions[fingerprint] = Date()\n self.saveIdentityCache()\n }\n }\n }\n \n func getHandshakeState(peerID: String) -> HandshakeState? {\n queue.sync {\n return ephemeralSessions[peerID]?.handshakeState\n }\n }\n \n // MARK: - Pending Actions\n \n func setPendingAction(peerID: String, action: PendingActions) {\n queue.async(flags: .barrier) {\n self.pendingActions[peerID] = action\n }\n }\n \n func applyPendingActions(peerID: String, fingerprint: String) {\n queue.async(flags: .barrier) {\n guard let actions = self.pendingActions[peerID] else { return }\n \n // Get or create social identity\n var identity = self.cache.socialIdentities[fingerprint] ?? SocialIdentity(\n fingerprint: fingerprint,\n localPetname: nil,\n claimedNickname: \"Unknown\",\n trustLevel: .unknown,\n isFavorite: false,\n isBlocked: false,\n notes: nil\n )\n \n // Apply pending actions\n if let toggleFavorite = actions.toggleFavorite {\n identity.isFavorite = toggleFavorite\n }\n if let trustLevel = actions.setTrustLevel {\n identity.trustLevel = trustLevel\n }\n if let petname = actions.setPetname {\n identity.localPetname = petname\n }\n \n // Save updated identity\n self.cache.socialIdentities[fingerprint] = identity\n self.pendingActions.removeValue(forKey: peerID)\n self.saveIdentityCache()\n }\n }\n \n // MARK: - Cleanup\n \n func clearAllIdentityData() {\n SecureLogger.log(\"Clearing all identity data\", category: SecureLogger.security, level: .warning)\n \n queue.async(flags: .barrier) {\n self.cache = IdentityCache()\n self.ephemeralSessions.removeAll()\n self.cryptographicIdentities.removeAll()\n self.pendingActions.removeAll()\n \n // Delete from keychain\n let deleted = self.keychain.deleteIdentityKey(forKey: self.cacheKey)\n SecureLogger.logKeyOperation(\"delete\", keyType: \"identity cache\", success: deleted)\n }\n }\n \n func removeEphemeralSession(peerID: String) {\n queue.async(flags: .barrier) {\n self.ephemeralSessions.removeValue(forKey: peerID)\n self.pendingActions.removeValue(forKey: peerID)\n }\n }\n \n // MARK: - Verification\n \n func setVerified(fingerprint: String, verified: Bool) {\n SecureLogger.log(\"Fingerprint \\(verified ? \"verified\" : \"unverified\"): \\(fingerprint)\", category: SecureLogger.security, level: .info)\n \n queue.async(flags: .barrier) {\n if verified {\n self.cache.verifiedFingerprints.insert(fingerprint)\n } else {\n self.cache.verifiedFingerprints.remove(fingerprint)\n }\n \n // Update trust level if social identity exists\n if var identity = self.cache.socialIdentities[fingerprint] {\n identity.trustLevel = verified ? .verified : .casual\n self.cache.socialIdentities[fingerprint] = identity\n }\n \n self.saveIdentityCache()\n }\n }\n \n func isVerified(fingerprint: String) -> Bool {\n queue.sync {\n return cache.verifiedFingerprints.contains(fingerprint)\n }\n }\n \n func getVerifiedFingerprints() -> Set {\n queue.sync {\n return cache.verifiedFingerprints\n }\n }\n}"], ["/bitchat/bitchat/BitchatApp.swift", "//\n// BitchatApp.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport SwiftUI\nimport UserNotifications\n\n@main\nstruct BitchatApp: App {\n @StateObject private var chatViewModel = ChatViewModel()\n #if os(iOS)\n @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate\n #elseif os(macOS)\n @NSApplicationDelegateAdaptor(MacAppDelegate.self) var appDelegate\n #endif\n \n init() {\n UNUserNotificationCenter.current().delegate = NotificationDelegate.shared\n }\n \n var body: some Scene {\n WindowGroup {\n ContentView()\n .environmentObject(chatViewModel)\n .onAppear {\n NotificationDelegate.shared.chatViewModel = chatViewModel\n #if os(iOS)\n appDelegate.chatViewModel = chatViewModel\n #elseif os(macOS)\n appDelegate.chatViewModel = chatViewModel\n #endif\n // Check for shared content\n checkForSharedContent()\n }\n .onOpenURL { url in\n handleURL(url)\n }\n #if os(iOS)\n .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in\n // Check for shared content when app becomes active\n checkForSharedContent()\n }\n #endif\n }\n #if os(macOS)\n .windowStyle(.hiddenTitleBar)\n .windowResizability(.contentSize)\n #endif\n }\n \n private func handleURL(_ url: URL) {\n if url.scheme == \"bitchat\" && url.host == \"share\" {\n // Handle shared content\n checkForSharedContent()\n }\n }\n \n private func checkForSharedContent() {\n // Check app group for shared content from extension\n guard let userDefaults = UserDefaults(suiteName: \"group.chat.bitchat\") else {\n return\n }\n \n guard let sharedContent = userDefaults.string(forKey: \"sharedContent\"),\n let sharedDate = userDefaults.object(forKey: \"sharedContentDate\") as? Date else {\n return\n }\n \n // Only process if shared within last 30 seconds\n if Date().timeIntervalSince(sharedDate) < 30 {\n let contentType = userDefaults.string(forKey: \"sharedContentType\") ?? \"text\"\n \n // Clear the shared content\n userDefaults.removeObject(forKey: \"sharedContent\")\n userDefaults.removeObject(forKey: \"sharedContentType\")\n userDefaults.removeObject(forKey: \"sharedContentDate\")\n userDefaults.synchronize()\n \n // Show notification about shared content\n DispatchQueue.main.async {\n // Add system message about sharing\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"preparing to share \\(contentType)...\",\n timestamp: Date(),\n isRelay: false\n )\n self.chatViewModel.messages.append(systemMessage)\n }\n \n // Send the shared content after a short delay\n DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {\n if contentType == \"url\" {\n // Try to parse as JSON first\n if let data = sharedContent.data(using: .utf8),\n let urlData = try? JSONSerialization.jsonObject(with: data) as? [String: String],\n let url = urlData[\"url\"] {\n // Send plain URL\n self.chatViewModel.sendMessage(url)\n } else {\n // Fallback to simple URL\n self.chatViewModel.sendMessage(sharedContent)\n }\n } else {\n self.chatViewModel.sendMessage(sharedContent)\n }\n }\n }\n }\n}\n\n#if os(iOS)\nclass AppDelegate: NSObject, UIApplicationDelegate {\n weak var chatViewModel: ChatViewModel?\n \n func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {\n return true\n }\n}\n#endif\n\n#if os(macOS)\nimport AppKit\n\nclass MacAppDelegate: NSObject, NSApplicationDelegate {\n weak var chatViewModel: ChatViewModel?\n \n func applicationWillTerminate(_ notification: Notification) {\n chatViewModel?.applicationWillTerminate()\n }\n \n func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {\n return true\n }\n}\n#endif\n\nclass NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {\n static let shared = NotificationDelegate()\n weak var chatViewModel: ChatViewModel?\n \n func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {\n let identifier = response.notification.request.identifier\n let userInfo = response.notification.request.content.userInfo\n \n // Check if this is a private message notification\n if identifier.hasPrefix(\"private-\") {\n // Get peer ID from userInfo\n if let peerID = userInfo[\"peerID\"] as? String {\n DispatchQueue.main.async {\n self.chatViewModel?.startPrivateChat(with: peerID)\n }\n }\n }\n \n completionHandler()\n }\n \n func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {\n let identifier = notification.request.identifier\n let userInfo = notification.request.content.userInfo\n \n // Check if this is a private message notification\n if identifier.hasPrefix(\"private-\") {\n // Get peer ID from userInfo\n if let peerID = userInfo[\"peerID\"] as? String {\n // Don't show notification if the private chat is already open\n if chatViewModel?.selectedPrivateChatPeer == peerID {\n completionHandler([])\n return\n }\n }\n }\n \n // Show notification in all other cases\n completionHandler([.banner, .sound])\n }\n}\n\nextension String {\n var nilIfEmpty: String? {\n self.isEmpty ? nil : self\n }\n}"], ["/bitchat/bitchat/Protocols/BitchatProtocol.swift", "//\n// BitchatProtocol.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # BitchatProtocol\n///\n/// Defines the application-layer protocol for BitChat mesh networking, including\n/// message types, packet structures, and encoding/decoding logic.\n///\n/// ## Overview\n/// BitchatProtocol implements a binary protocol optimized for Bluetooth LE's\n/// constrained bandwidth and MTU limitations. It provides:\n/// - Efficient binary message encoding\n/// - Message fragmentation for large payloads\n/// - TTL-based routing for mesh networks\n/// - Privacy features like padding and timing obfuscation\n/// - Integration points for end-to-end encryption\n///\n/// ## Protocol Design\n/// The protocol uses a compact binary format to minimize overhead:\n/// - 1-byte message type identifier\n/// - Variable-length fields with length prefixes\n/// - Network byte order (big-endian) for multi-byte values\n/// - PKCS#7-style padding for privacy\n///\n/// ## Message Flow\n/// 1. **Creation**: Messages are created with type, content, and metadata\n/// 2. **Encoding**: Converted to binary format with proper field ordering\n/// 3. **Fragmentation**: Split if larger than BLE MTU (512 bytes)\n/// 4. **Transmission**: Sent via BluetoothMeshService\n/// 5. **Routing**: Relayed by intermediate nodes (TTL decrements)\n/// 6. **Reassembly**: Fragments collected and reassembled\n/// 7. **Decoding**: Binary data parsed back to message objects\n///\n/// ## Security Considerations\n/// - Message padding obscures actual content length\n/// - Timing obfuscation prevents traffic analysis\n/// - Integration with Noise Protocol for E2E encryption\n/// - No persistent identifiers in protocol headers\n///\n/// ## Message Types\n/// - **Announce/Leave**: Peer presence notifications\n/// - **Message**: User chat messages (broadcast or directed)\n/// - **Fragment**: Multi-part message handling\n/// - **Delivery/Read**: Message acknowledgments\n/// - **Noise**: Encrypted channel establishment\n/// - **Version**: Protocol compatibility negotiation\n///\n/// ## Future Extensions\n/// The protocol is designed to be extensible:\n/// - Reserved message type ranges for future use\n/// - Version negotiation for backward compatibility\n/// - Optional fields for new features\n///\n\nimport Foundation\nimport CryptoKit\n\n// MARK: - Message Padding\n\n/// Provides privacy-preserving message padding to obscure actual content length.\n/// Uses PKCS#7-style padding with random bytes to prevent traffic analysis.\nstruct MessagePadding {\n // Standard block sizes for padding\n static let blockSizes = [256, 512, 1024, 2048]\n \n // Add PKCS#7-style padding to reach target size\n static func pad(_ data: Data, toSize targetSize: Int) -> Data {\n guard data.count < targetSize else { return data }\n \n let paddingNeeded = targetSize - data.count\n \n // PKCS#7 only supports padding up to 255 bytes\n // If we need more padding than that, don't pad - return original data\n guard paddingNeeded <= 255 else { return data }\n \n var padded = data\n \n // Standard PKCS#7 padding\n var randomBytes = [UInt8](repeating: 0, count: paddingNeeded - 1)\n _ = SecRandomCopyBytes(kSecRandomDefault, paddingNeeded - 1, &randomBytes)\n padded.append(contentsOf: randomBytes)\n padded.append(UInt8(paddingNeeded))\n \n return padded\n }\n \n // Remove padding from data\n static func unpad(_ data: Data) -> Data {\n guard !data.isEmpty else { return data }\n \n // Last byte tells us how much padding to remove\n let paddingLength = Int(data[data.count - 1])\n guard paddingLength > 0 && paddingLength <= data.count else { \n // Debug logging for 243-byte packets\n if data.count == 243 {\n }\n return data \n }\n \n let result = data.prefix(data.count - paddingLength)\n \n // Debug logging for 243-byte packets\n if data.count == 243 {\n }\n \n return result\n }\n \n // Find optimal block size for data\n static func optimalBlockSize(for dataSize: Int) -> Int {\n // Account for encryption overhead (~16 bytes for AES-GCM tag)\n let totalSize = dataSize + 16\n \n // Find smallest block that fits\n for blockSize in blockSizes {\n if totalSize <= blockSize {\n return blockSize\n }\n }\n \n // For very large messages, just use the original size\n // (will be fragmented anyway)\n return dataSize\n }\n}\n\n// MARK: - Message Types\n\n/// Defines all message types in the BitChat protocol.\n/// Each type has a unique identifier for efficient binary encoding.\n/// Types are grouped by function: user messages, protocol control, encryption, etc.\nenum MessageType: UInt8 {\n case announce = 0x01\n case leave = 0x03\n case message = 0x04 // All user messages (private and broadcast)\n case fragmentStart = 0x05\n case fragmentContinue = 0x06\n case fragmentEnd = 0x07\n case deliveryAck = 0x0A // Acknowledge message received\n case deliveryStatusRequest = 0x0B // Request delivery status update\n case readReceipt = 0x0C // Message has been read/viewed\n \n // Noise Protocol messages\n case noiseHandshakeInit = 0x10 // Noise handshake initiation\n case noiseHandshakeResp = 0x11 // Noise handshake response\n case noiseEncrypted = 0x12 // Noise encrypted transport message\n case noiseIdentityAnnounce = 0x13 // Announce static public key for discovery\n \n // Protocol version negotiation\n case versionHello = 0x20 // Initial version announcement\n case versionAck = 0x21 // Version acknowledgment\n \n // Protocol-level acknowledgments\n case protocolAck = 0x22 // Generic protocol acknowledgment\n case protocolNack = 0x23 // Negative acknowledgment (failure)\n case systemValidation = 0x24 // Session validation ping\n case handshakeRequest = 0x25 // Request handshake for pending messages\n \n var description: String {\n switch self {\n case .announce: return \"announce\"\n case .leave: return \"leave\"\n case .message: return \"message\"\n case .fragmentStart: return \"fragmentStart\"\n case .fragmentContinue: return \"fragmentContinue\"\n case .fragmentEnd: return \"fragmentEnd\"\n case .deliveryAck: return \"deliveryAck\"\n case .deliveryStatusRequest: return \"deliveryStatusRequest\"\n case .readReceipt: return \"readReceipt\"\n case .noiseHandshakeInit: return \"noiseHandshakeInit\"\n case .noiseHandshakeResp: return \"noiseHandshakeResp\"\n case .noiseEncrypted: return \"noiseEncrypted\"\n case .noiseIdentityAnnounce: return \"noiseIdentityAnnounce\"\n case .versionHello: return \"versionHello\"\n case .versionAck: return \"versionAck\"\n case .protocolAck: return \"protocolAck\"\n case .protocolNack: return \"protocolNack\"\n case .systemValidation: return \"systemValidation\"\n case .handshakeRequest: return \"handshakeRequest\"\n }\n }\n}\n\n// MARK: - Handshake State\n\n// Lazy handshake state tracking\nenum LazyHandshakeState {\n case none // No session, no handshake attempted\n case handshakeQueued // User action requires handshake\n case handshaking // Currently in handshake process\n case established // Session ready for use\n case failed(Error) // Handshake failed\n}\n\n// MARK: - Special Recipients\n\n/// Defines special recipient identifiers used in the protocol.\n/// These magic values indicate broadcast or system-level recipients\n/// rather than specific peer IDs.\nstruct SpecialRecipients {\n static let broadcast = Data(repeating: 0xFF, count: 8) // All 0xFF = broadcast\n}\n\n// MARK: - Core Protocol Structures\n\n/// The core packet structure for all BitChat protocol messages.\n/// Encapsulates all data needed for routing through the mesh network,\n/// including TTL for hop limiting and optional encryption.\n/// - Note: Packets larger than BLE MTU (512 bytes) are automatically fragmented\nstruct BitchatPacket: Codable {\n let version: UInt8\n let type: UInt8\n let senderID: Data\n let recipientID: Data?\n let timestamp: UInt64\n let payload: Data\n let signature: Data?\n var ttl: UInt8\n \n init(type: UInt8, senderID: Data, recipientID: Data?, timestamp: UInt64, payload: Data, signature: Data?, ttl: UInt8) {\n self.version = 1\n self.type = type\n self.senderID = senderID\n self.recipientID = recipientID\n self.timestamp = timestamp\n self.payload = payload\n self.signature = signature\n self.ttl = ttl\n }\n \n // Convenience initializer for new binary format\n init(type: UInt8, ttl: UInt8, senderID: String, payload: Data) {\n self.version = 1\n self.type = type\n // Convert hex string peer ID to binary data (8 bytes)\n var senderData = Data()\n var tempID = senderID\n while tempID.count >= 2 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n senderData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n self.senderID = senderData\n self.recipientID = nil\n self.timestamp = UInt64(Date().timeIntervalSince1970 * 1000) // milliseconds\n self.payload = payload\n self.signature = nil\n self.ttl = ttl\n }\n \n var data: Data? {\n BinaryProtocol.encode(self)\n }\n \n func toBinaryData() -> Data? {\n BinaryProtocol.encode(self)\n }\n \n static func from(_ data: Data) -> BitchatPacket? {\n BinaryProtocol.decode(data)\n }\n}\n\n// MARK: - Delivery Acknowledgments\n\n/// Acknowledgment sent when a message is successfully delivered to a recipient.\n/// Provides delivery confirmation for reliable messaging and UI feedback.\n/// - Note: Only sent for direct messages, not broadcasts\nstruct DeliveryAck: Codable {\n let originalMessageID: String\n let ackID: String\n let recipientID: String // Who received it\n let recipientNickname: String\n let timestamp: Date\n let hopCount: UInt8 // How many hops to reach recipient\n \n init(originalMessageID: String, recipientID: String, recipientNickname: String, hopCount: UInt8) {\n self.originalMessageID = originalMessageID\n self.ackID = UUID().uuidString\n self.recipientID = recipientID\n self.recipientNickname = recipientNickname\n self.timestamp = Date()\n self.hopCount = hopCount\n }\n \n // For binary decoding\n private init(originalMessageID: String, ackID: String, recipientID: String, recipientNickname: String, timestamp: Date, hopCount: UInt8) {\n self.originalMessageID = originalMessageID\n self.ackID = ackID\n self.recipientID = recipientID\n self.recipientNickname = recipientNickname\n self.timestamp = timestamp\n self.hopCount = hopCount\n }\n \n func encode() -> Data? {\n try? JSONEncoder().encode(self)\n }\n \n static func decode(from data: Data) -> DeliveryAck? {\n try? JSONDecoder().decode(DeliveryAck.self, from: data)\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUUID(originalMessageID)\n data.appendUUID(ackID)\n // RecipientID as 8-byte hex string\n var recipientData = Data()\n var tempID = recipientID\n while tempID.count >= 2 && recipientData.count < 8 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n recipientData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n while recipientData.count < 8 {\n recipientData.append(0)\n }\n data.append(recipientData)\n data.appendUInt8(hopCount)\n data.appendDate(timestamp)\n data.appendString(recipientNickname)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> DeliveryAck? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size: 2 UUIDs (32) + recipientID (8) + hopCount (1) + timestamp (8) + min nickname\n guard dataCopy.count >= 50 else { return nil }\n \n var offset = 0\n \n guard let originalMessageID = dataCopy.readUUID(at: &offset),\n let ackID = dataCopy.readUUID(at: &offset) else { return nil }\n \n guard let recipientIDData = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n let recipientID = recipientIDData.hexEncodedString()\n \n guard let hopCount = dataCopy.readUInt8(at: &offset),\n let timestamp = dataCopy.readDate(at: &offset),\n let recipientNickname = dataCopy.readString(at: &offset) else { return nil }\n \n return DeliveryAck(originalMessageID: originalMessageID,\n ackID: ackID,\n recipientID: recipientID,\n recipientNickname: recipientNickname,\n timestamp: timestamp,\n hopCount: hopCount)\n }\n}\n\n// MARK: - Read Receipts\n\n// Read receipt structure\nstruct ReadReceipt: Codable {\n let originalMessageID: String\n let receiptID: String\n let readerID: String // Who read it\n let readerNickname: String\n let timestamp: Date\n \n init(originalMessageID: String, readerID: String, readerNickname: String) {\n self.originalMessageID = originalMessageID\n self.receiptID = UUID().uuidString\n self.readerID = readerID\n self.readerNickname = readerNickname\n self.timestamp = Date()\n }\n \n // For binary decoding\n private init(originalMessageID: String, receiptID: String, readerID: String, readerNickname: String, timestamp: Date) {\n self.originalMessageID = originalMessageID\n self.receiptID = receiptID\n self.readerID = readerID\n self.readerNickname = readerNickname\n self.timestamp = timestamp\n }\n \n func encode() -> Data? {\n try? JSONEncoder().encode(self)\n }\n \n static func decode(from data: Data) -> ReadReceipt? {\n try? JSONDecoder().decode(ReadReceipt.self, from: data)\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUUID(originalMessageID)\n data.appendUUID(receiptID)\n // ReaderID as 8-byte hex string\n var readerData = Data()\n var tempID = readerID\n while tempID.count >= 2 && readerData.count < 8 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n readerData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n while readerData.count < 8 {\n readerData.append(0)\n }\n data.append(readerData)\n data.appendDate(timestamp)\n data.appendString(readerNickname)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> ReadReceipt? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size: 2 UUIDs (32) + readerID (8) + timestamp (8) + min nickname\n guard dataCopy.count >= 49 else { return nil }\n \n var offset = 0\n \n guard let originalMessageID = dataCopy.readUUID(at: &offset),\n let receiptID = dataCopy.readUUID(at: &offset) else { return nil }\n \n guard let readerIDData = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n let readerID = readerIDData.hexEncodedString()\n \n guard let timestamp = dataCopy.readDate(at: &offset),\n let readerNickname = dataCopy.readString(at: &offset) else { return nil }\n \n return ReadReceipt(originalMessageID: originalMessageID,\n receiptID: receiptID,\n readerID: readerID,\n readerNickname: readerNickname,\n timestamp: timestamp)\n }\n}\n\n// MARK: - Handshake Requests\n\n// Handshake request for pending messages\nstruct HandshakeRequest: Codable {\n let requestID: String\n let requesterID: String // Who needs the handshake\n let requesterNickname: String // Nickname of requester\n let targetID: String // Who should initiate handshake\n let pendingMessageCount: UInt8 // Number of messages queued\n let timestamp: Date\n \n init(requesterID: String, requesterNickname: String, targetID: String, pendingMessageCount: UInt8) {\n self.requestID = UUID().uuidString\n self.requesterID = requesterID\n self.requesterNickname = requesterNickname\n self.targetID = targetID\n self.pendingMessageCount = pendingMessageCount\n self.timestamp = Date()\n }\n \n // For binary decoding\n private init(requestID: String, requesterID: String, requesterNickname: String, targetID: String, pendingMessageCount: UInt8, timestamp: Date) {\n self.requestID = requestID\n self.requesterID = requesterID\n self.requesterNickname = requesterNickname\n self.targetID = targetID\n self.pendingMessageCount = pendingMessageCount\n self.timestamp = timestamp\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUUID(requestID)\n \n // RequesterID as 8-byte hex string\n var requesterData = Data()\n var tempID = requesterID\n while tempID.count >= 2 && requesterData.count < 8 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n requesterData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n while requesterData.count < 8 {\n requesterData.append(0)\n }\n data.append(requesterData)\n \n // TargetID as 8-byte hex string\n var targetData = Data()\n tempID = targetID\n while tempID.count >= 2 && targetData.count < 8 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n targetData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n while targetData.count < 8 {\n targetData.append(0)\n }\n data.append(targetData)\n \n data.appendUInt8(pendingMessageCount)\n data.appendDate(timestamp)\n data.appendString(requesterNickname)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> HandshakeRequest? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size: UUID (16) + requesterID (8) + targetID (8) + count (1) + timestamp (8) + min nickname\n guard dataCopy.count >= 42 else { return nil }\n \n var offset = 0\n \n guard let requestID = dataCopy.readUUID(at: &offset) else { return nil }\n \n guard let requesterIDData = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n let requesterID = requesterIDData.hexEncodedString()\n \n guard let targetIDData = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n let targetID = targetIDData.hexEncodedString()\n \n guard let pendingMessageCount = dataCopy.readUInt8(at: &offset),\n let timestamp = dataCopy.readDate(at: &offset),\n let requesterNickname = dataCopy.readString(at: &offset) else { return nil }\n \n return HandshakeRequest(requestID: requestID,\n requesterID: requesterID,\n requesterNickname: requesterNickname,\n targetID: targetID,\n pendingMessageCount: pendingMessageCount,\n timestamp: timestamp)\n }\n}\n\n// MARK: - Protocol Acknowledgments\n\n// Protocol-level acknowledgment for reliable delivery\nstruct ProtocolAck: Codable {\n let originalPacketID: String // ID of the packet being acknowledged\n let ackID: String // Unique ID for this ACK\n let senderID: String // Who sent the original packet\n let receiverID: String // Who received and is acknowledging\n let packetType: UInt8 // Type of packet being acknowledged\n let timestamp: Date // When ACK was generated\n let hopCount: UInt8 // Hops taken to reach receiver\n \n init(originalPacketID: String, senderID: String, receiverID: String, packetType: UInt8, hopCount: UInt8) {\n self.originalPacketID = originalPacketID\n self.ackID = UUID().uuidString\n self.senderID = senderID\n self.receiverID = receiverID\n self.packetType = packetType\n self.timestamp = Date()\n self.hopCount = hopCount\n }\n \n // Private init for binary decoding\n private init(originalPacketID: String, ackID: String, senderID: String, receiverID: String, \n packetType: UInt8, timestamp: Date, hopCount: UInt8) {\n self.originalPacketID = originalPacketID\n self.ackID = ackID\n self.senderID = senderID\n self.receiverID = receiverID\n self.packetType = packetType\n self.timestamp = timestamp\n self.hopCount = hopCount\n }\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUUID(originalPacketID)\n data.appendUUID(ackID)\n \n // Sender and receiver IDs as 8-byte hex strings\n data.append(Data(hexString: senderID) ?? Data(repeating: 0, count: 8))\n data.append(Data(hexString: receiverID) ?? Data(repeating: 0, count: 8))\n \n data.appendUInt8(packetType)\n data.appendUInt8(hopCount)\n data.appendDate(timestamp)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> ProtocolAck? {\n let dataCopy = Data(data)\n guard dataCopy.count >= 50 else { return nil } // 2 UUIDs + 2 IDs + type + hop + timestamp\n \n var offset = 0\n guard let originalPacketID = dataCopy.readUUID(at: &offset),\n let ackID = dataCopy.readUUID(at: &offset),\n let senderIDData = dataCopy.readFixedBytes(at: &offset, count: 8),\n let receiverIDData = dataCopy.readFixedBytes(at: &offset, count: 8),\n let packetType = dataCopy.readUInt8(at: &offset),\n let hopCount = dataCopy.readUInt8(at: &offset),\n let timestamp = dataCopy.readDate(at: &offset) else { return nil }\n \n let senderID = senderIDData.hexEncodedString()\n let receiverID = receiverIDData.hexEncodedString()\n \n return ProtocolAck(originalPacketID: originalPacketID,\n ackID: ackID,\n senderID: senderID,\n receiverID: receiverID,\n packetType: packetType,\n timestamp: timestamp,\n hopCount: hopCount)\n }\n}\n\n// Protocol-level negative acknowledgment\nstruct ProtocolNack: Codable {\n let originalPacketID: String // ID of the packet that failed\n let nackID: String // Unique ID for this NACK\n let senderID: String // Who sent the original packet\n let receiverID: String // Who is reporting the failure\n let packetType: UInt8 // Type of packet that failed\n let timestamp: Date // When NACK was generated\n let reason: String // Reason for failure\n let errorCode: UInt8 // Numeric error code\n \n // Error codes\n enum ErrorCode: UInt8 {\n case unknown = 0\n case checksumFailed = 1\n case decryptionFailed = 2\n case malformedPacket = 3\n case unsupportedVersion = 4\n case resourceExhausted = 5\n case routingFailed = 6\n case sessionExpired = 7\n }\n \n init(originalPacketID: String, senderID: String, receiverID: String, \n packetType: UInt8, reason: String, errorCode: ErrorCode = .unknown) {\n self.originalPacketID = originalPacketID\n self.nackID = UUID().uuidString\n self.senderID = senderID\n self.receiverID = receiverID\n self.packetType = packetType\n self.timestamp = Date()\n self.reason = reason\n self.errorCode = errorCode.rawValue\n }\n \n // Private init for binary decoding\n private init(originalPacketID: String, nackID: String, senderID: String, receiverID: String,\n packetType: UInt8, timestamp: Date, reason: String, errorCode: UInt8) {\n self.originalPacketID = originalPacketID\n self.nackID = nackID\n self.senderID = senderID\n self.receiverID = receiverID\n self.packetType = packetType\n self.timestamp = timestamp\n self.reason = reason\n self.errorCode = errorCode\n }\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUUID(originalPacketID)\n data.appendUUID(nackID)\n \n // Sender and receiver IDs as 8-byte hex strings\n data.append(Data(hexString: senderID) ?? Data(repeating: 0, count: 8))\n data.append(Data(hexString: receiverID) ?? Data(repeating: 0, count: 8))\n \n data.appendUInt8(packetType)\n data.appendUInt8(errorCode)\n data.appendDate(timestamp)\n data.appendString(reason)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> ProtocolNack? {\n let dataCopy = Data(data)\n guard dataCopy.count >= 52 else { return nil } // Minimum size\n \n var offset = 0\n guard let originalPacketID = dataCopy.readUUID(at: &offset),\n let nackID = dataCopy.readUUID(at: &offset),\n let senderIDData = dataCopy.readFixedBytes(at: &offset, count: 8),\n let receiverIDData = dataCopy.readFixedBytes(at: &offset, count: 8),\n let packetType = dataCopy.readUInt8(at: &offset),\n let errorCode = dataCopy.readUInt8(at: &offset),\n let timestamp = dataCopy.readDate(at: &offset),\n let reason = dataCopy.readString(at: &offset) else { return nil }\n \n let senderID = senderIDData.hexEncodedString()\n let receiverID = receiverIDData.hexEncodedString()\n \n return ProtocolNack(originalPacketID: originalPacketID,\n nackID: nackID,\n senderID: senderID,\n receiverID: receiverID,\n packetType: packetType,\n timestamp: timestamp,\n reason: reason,\n errorCode: errorCode)\n }\n}\n\n// MARK: - Peer Identity Rotation\n\n/// Announces a peer's cryptographic identity to enable secure communication.\n/// Contains the peer's Noise static public key and supports identity rotation\n/// by binding ephemeral peer IDs to stable cryptographic fingerprints.\n/// - Note: Critical for establishing end-to-end encrypted channels\nstruct NoiseIdentityAnnouncement: Codable {\n let peerID: String // Current ephemeral peer ID\n let publicKey: Data // Noise static public key\n let signingPublicKey: Data // Ed25519 signing public key\n let nickname: String // Current nickname\n let timestamp: Date // When this binding was created\n let previousPeerID: String? // Previous peer ID (for smooth transition)\n let signature: Data // Signature proving ownership\n \n init(peerID: String, publicKey: Data, signingPublicKey: Data, nickname: String, timestamp: Date, previousPeerID: String? = nil, signature: Data) {\n self.peerID = peerID\n self.publicKey = publicKey\n self.signingPublicKey = signingPublicKey\n // Trim whitespace from nickname\n self.nickname = nickname.trimmingCharacters(in: .whitespacesAndNewlines)\n self.timestamp = timestamp\n self.previousPeerID = previousPeerID\n self.signature = signature\n }\n \n // Custom decoder to ensure nickname is trimmed\n init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n self.peerID = try container.decode(String.self, forKey: .peerID)\n self.publicKey = try container.decode(Data.self, forKey: .publicKey)\n self.signingPublicKey = try container.decode(Data.self, forKey: .signingPublicKey)\n // Trim whitespace from decoded nickname\n let rawNickname = try container.decode(String.self, forKey: .nickname)\n self.nickname = rawNickname.trimmingCharacters(in: .whitespacesAndNewlines)\n self.timestamp = try container.decode(Date.self, forKey: .timestamp)\n self.previousPeerID = try container.decodeIfPresent(String.self, forKey: .previousPeerID)\n self.signature = try container.decode(Data.self, forKey: .signature)\n }\n \n func encode() -> Data? {\n return try? JSONEncoder().encode(self)\n }\n \n static func decode(from data: Data) -> NoiseIdentityAnnouncement? {\n return try? JSONDecoder().decode(NoiseIdentityAnnouncement.self, from: data)\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n \n // Flags byte: bit 0 = hasPreviousPeerID\n var flags: UInt8 = 0\n if previousPeerID != nil { flags |= 0x01 }\n data.appendUInt8(flags)\n \n // PeerID as 8-byte hex string\n var peerData = Data()\n var tempID = peerID\n while tempID.count >= 2 && peerData.count < 8 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n peerData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n while peerData.count < 8 {\n peerData.append(0)\n }\n data.append(peerData)\n \n data.appendData(publicKey)\n data.appendData(signingPublicKey)\n data.appendString(nickname)\n data.appendDate(timestamp)\n \n if let previousPeerID = previousPeerID {\n // Previous PeerID as 8-byte hex string\n var prevData = Data()\n var tempPrevID = previousPeerID\n while tempPrevID.count >= 2 && prevData.count < 8 {\n let hexByte = String(tempPrevID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n prevData.append(byte)\n }\n tempPrevID = String(tempPrevID.dropFirst(2))\n }\n while prevData.count < 8 {\n prevData.append(0)\n }\n data.append(prevData)\n }\n \n data.appendData(signature)\n \n return data\n }\n \n static func fromBinaryData(_ data: Data) -> NoiseIdentityAnnouncement? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size check: flags(1) + peerID(8) + min data lengths\n guard dataCopy.count >= 20 else { return nil }\n \n var offset = 0\n \n guard let flags = dataCopy.readUInt8(at: &offset) else { return nil }\n let hasPreviousPeerID = (flags & 0x01) != 0\n \n // Read peerID using safe method\n guard let peerIDBytes = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n let peerID = peerIDBytes.hexEncodedString()\n \n guard let publicKey = dataCopy.readData(at: &offset),\n let signingPublicKey = dataCopy.readData(at: &offset),\n let rawNickname = dataCopy.readString(at: &offset),\n let timestamp = dataCopy.readDate(at: &offset) else { return nil }\n \n // Trim whitespace from nickname\n let nickname = rawNickname.trimmingCharacters(in: .whitespacesAndNewlines)\n \n var previousPeerID: String? = nil\n if hasPreviousPeerID {\n // Read previousPeerID using safe method\n guard let prevIDBytes = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n previousPeerID = prevIDBytes.hexEncodedString()\n }\n \n guard let signature = dataCopy.readData(at: &offset) else { return nil }\n \n return NoiseIdentityAnnouncement(peerID: peerID,\n publicKey: publicKey,\n signingPublicKey: signingPublicKey,\n nickname: nickname,\n timestamp: timestamp,\n previousPeerID: previousPeerID,\n signature: signature)\n }\n}\n\n// Binding between ephemeral peer ID and cryptographic identity\nstruct PeerIdentityBinding {\n let currentPeerID: String // Current ephemeral ID\n let fingerprint: String // Permanent cryptographic identity\n let publicKey: Data // Noise static public key\n let signingPublicKey: Data // Ed25519 signing public key\n let nickname: String // Last known nickname\n let bindingTimestamp: Date // When this binding was created\n let signature: Data // Cryptographic proof of binding\n \n // Verify the binding signature\n func verify() -> Bool {\n let bindingData = currentPeerID.data(using: .utf8)! + publicKey + \n String(Int64(bindingTimestamp.timeIntervalSince1970 * 1000)).data(using: .utf8)!\n \n do {\n let signingKey = try Curve25519.Signing.PublicKey(rawRepresentation: signingPublicKey)\n return signingKey.isValidSignature(signature, for: bindingData)\n } catch {\n return false\n }\n }\n}\n\n// MARK: - Protocol Version Negotiation\n\n// Protocol version constants\nstruct ProtocolVersion {\n static let current: UInt8 = 1\n static let minimum: UInt8 = 1\n static let maximum: UInt8 = 1\n \n // Future versions can be added here\n static let supportedVersions: Set = [1]\n \n static func isSupported(_ version: UInt8) -> Bool {\n return supportedVersions.contains(version)\n }\n \n static func negotiateVersion(clientVersions: [UInt8], serverVersions: [UInt8]) -> UInt8? {\n // Find the highest common version\n let clientSet = Set(clientVersions)\n let serverSet = Set(serverVersions)\n let common = clientSet.intersection(serverSet)\n \n return common.max()\n }\n}\n\n// Version negotiation hello message\nstruct VersionHello: Codable {\n let supportedVersions: [UInt8] // List of supported protocol versions\n let preferredVersion: UInt8 // Preferred version (usually the latest)\n let clientVersion: String // App version string (e.g., \"1.0.0\")\n let platform: String // Platform identifier (e.g., \"iOS\", \"macOS\")\n let capabilities: [String]? // Optional capability flags for future extensions\n \n init(supportedVersions: [UInt8] = Array(ProtocolVersion.supportedVersions), \n preferredVersion: UInt8 = ProtocolVersion.current,\n clientVersion: String,\n platform: String,\n capabilities: [String]? = nil) {\n self.supportedVersions = supportedVersions\n self.preferredVersion = preferredVersion\n self.clientVersion = clientVersion\n self.platform = platform\n self.capabilities = capabilities\n }\n \n func encode() -> Data? {\n return try? JSONEncoder().encode(self)\n }\n \n static func decode(from data: Data) -> VersionHello? {\n try? JSONDecoder().decode(VersionHello.self, from: data)\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n \n // Flags byte: bit 0 = hasCapabilities\n var flags: UInt8 = 0\n if capabilities != nil { flags |= 0x01 }\n data.appendUInt8(flags)\n \n // Supported versions array\n data.appendUInt8(UInt8(supportedVersions.count))\n for version in supportedVersions {\n data.appendUInt8(version)\n }\n \n data.appendUInt8(preferredVersion)\n data.appendString(clientVersion)\n data.appendString(platform)\n \n if let capabilities = capabilities {\n data.appendUInt8(UInt8(capabilities.count))\n for capability in capabilities {\n data.appendString(capability)\n }\n }\n \n return data\n }\n \n static func fromBinaryData(_ data: Data) -> VersionHello? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size check: flags(1) + versionCount(1) + at least one version(1) + preferredVersion(1) + min strings\n guard dataCopy.count >= 4 else { return nil }\n \n var offset = 0\n \n guard let flags = dataCopy.readUInt8(at: &offset) else { return nil }\n let hasCapabilities = (flags & 0x01) != 0\n \n guard let versionCount = dataCopy.readUInt8(at: &offset) else { return nil }\n var supportedVersions: [UInt8] = []\n for _ in 0.. Data? {\n return try? JSONEncoder().encode(self)\n }\n \n static func decode(from data: Data) -> VersionAck? {\n try? JSONDecoder().decode(VersionAck.self, from: data)\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n \n // Flags byte: bit 0 = hasCapabilities, bit 1 = hasReason\n var flags: UInt8 = 0\n if capabilities != nil { flags |= 0x01 }\n if reason != nil { flags |= 0x02 }\n data.appendUInt8(flags)\n \n data.appendUInt8(agreedVersion)\n data.appendString(serverVersion)\n data.appendString(platform)\n data.appendUInt8(rejected ? 1 : 0)\n \n if let capabilities = capabilities {\n data.appendUInt8(UInt8(capabilities.count))\n for capability in capabilities {\n data.appendString(capability)\n }\n }\n \n if let reason = reason {\n data.appendString(reason)\n }\n \n return data\n }\n \n static func fromBinaryData(_ data: Data) -> VersionAck? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size: flags(1) + version(1) + rejected(1) + min strings\n guard dataCopy.count >= 5 else { return nil }\n \n var offset = 0\n \n guard let flags = dataCopy.readUInt8(at: &offset) else { return nil }\n let hasCapabilities = (flags & 0x01) != 0\n let hasReason = (flags & 0x02) != 0\n \n guard let agreedVersion = dataCopy.readUInt8(at: &offset),\n let serverVersion = dataCopy.readString(at: &offset),\n let platform = dataCopy.readString(at: &offset),\n let rejectedByte = dataCopy.readUInt8(at: &offset) else { return nil }\n \n let rejected = rejectedByte != 0\n \n var capabilities: [String]? = nil\n if hasCapabilities {\n guard let capCount = dataCopy.readUInt8(at: &offset) else { return nil }\n capabilities = []\n for _ in 0.. AttributedString? {\n return _cachedFormattedText[\"\\(isDark)\"]\n }\n \n func setCachedFormattedText(_ text: AttributedString, isDark: Bool) {\n _cachedFormattedText[\"\\(isDark)\"] = text\n }\n \n // Codable implementation\n enum CodingKeys: String, CodingKey {\n case id, sender, content, timestamp, isRelay, originalSender\n case isPrivate, recipientNickname, senderPeerID, mentions, deliveryStatus\n }\n \n init(id: String? = nil, sender: String, content: String, timestamp: Date, isRelay: Bool, originalSender: String? = nil, isPrivate: Bool = false, recipientNickname: String? = nil, senderPeerID: String? = nil, mentions: [String]? = nil, deliveryStatus: DeliveryStatus? = nil) {\n self.id = id ?? UUID().uuidString\n self.sender = sender\n self.content = content\n self.timestamp = timestamp\n self.isRelay = isRelay\n self.originalSender = originalSender\n self.isPrivate = isPrivate\n self.recipientNickname = recipientNickname\n self.senderPeerID = senderPeerID\n self.mentions = mentions\n self.deliveryStatus = deliveryStatus ?? (isPrivate ? .sending : nil)\n }\n}\n\n// Equatable conformance for BitchatMessage\nextension BitchatMessage: Equatable {\n static func == (lhs: BitchatMessage, rhs: BitchatMessage) -> Bool {\n return lhs.id == rhs.id &&\n lhs.sender == rhs.sender &&\n lhs.content == rhs.content &&\n lhs.timestamp == rhs.timestamp &&\n lhs.isRelay == rhs.isRelay &&\n lhs.originalSender == rhs.originalSender &&\n lhs.isPrivate == rhs.isPrivate &&\n lhs.recipientNickname == rhs.recipientNickname &&\n lhs.senderPeerID == rhs.senderPeerID &&\n lhs.mentions == rhs.mentions &&\n lhs.deliveryStatus == rhs.deliveryStatus\n }\n}\n\n// MARK: - Delegate Protocol\n\nprotocol BitchatDelegate: AnyObject {\n func didReceiveMessage(_ message: BitchatMessage)\n func didConnectToPeer(_ peerID: String)\n func didDisconnectFromPeer(_ peerID: String)\n func didUpdatePeerList(_ peers: [String])\n \n // Optional method to check if a fingerprint belongs to a favorite peer\n func isFavorite(fingerprint: String) -> Bool\n \n // Delivery confirmation methods\n func didReceiveDeliveryAck(_ ack: DeliveryAck)\n func didReceiveReadReceipt(_ receipt: ReadReceipt)\n func didUpdateMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus)\n \n // Peer availability tracking\n func peerAvailabilityChanged(_ peerID: String, available: Bool)\n}\n\n// Provide default implementation to make it effectively optional\nextension BitchatDelegate {\n func isFavorite(fingerprint: String) -> Bool {\n return false\n }\n \n func didReceiveDeliveryAck(_ ack: DeliveryAck) {\n // Default empty implementation\n }\n \n func didReceiveReadReceipt(_ receipt: ReadReceipt) {\n // Default empty implementation\n }\n \n func didUpdateMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) {\n // Default empty implementation\n }\n \n func peerAvailabilityChanged(_ peerID: String, available: Bool) {\n // Default empty implementation\n }\n}\n"], ["/bitchat/bitchatShareExtension/ShareViewController.swift", "//\n// ShareViewController.swift\n// bitchatShareExtension\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport UIKit\nimport Social\nimport UniformTypeIdentifiers\n\nclass ShareViewController: SLComposeServiceViewController {\n \n override func viewDidLoad() {\n super.viewDidLoad()\n // Set placeholder text\n placeholder = \"Share to bitchat...\"\n // Set character limit (optional)\n charactersRemaining = 500\n }\n \n override func isContentValid() -> Bool {\n // Validate that we have text content or attachments\n if let text = contentText, !text.isEmpty {\n return true\n }\n // Check if we have attachments\n if let item = extensionContext?.inputItems.first as? NSExtensionItem,\n let attachments = item.attachments,\n !attachments.isEmpty {\n return true\n }\n return false\n }\n \n override func didSelectPost() {\n guard let extensionItem = extensionContext?.inputItems.first as? NSExtensionItem else {\n self.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)\n return\n }\n \n \n // Get the page title from the compose view or extension item\n let pageTitle = self.contentText ?? extensionItem.attributedContentText?.string ?? extensionItem.attributedTitle?.string\n \n var foundURL: URL? = nil\n let group = DispatchGroup()\n \n // IMPORTANT: Check if the NSExtensionItem itself has a URL\n // Safari often provides the URL as an attributedString with a link\n if let attributedText = extensionItem.attributedContentText {\n let text = attributedText.string\n let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)\n let matches = detector?.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count))\n if let firstMatch = matches?.first, let url = firstMatch.url {\n foundURL = url\n }\n }\n \n // Only check attachments if we haven't found a URL yet\n if foundURL == nil {\n for (_, itemProvider) in (extensionItem.attachments ?? []).enumerated() {\n \n // Try multiple URL type identifiers that Safari might use\n let urlTypes = [\n UTType.url.identifier,\n \"public.url\",\n \"public.file-url\"\n ]\n \n for urlType in urlTypes {\n if itemProvider.hasItemConformingToTypeIdentifier(urlType) {\n group.enter()\n itemProvider.loadItem(forTypeIdentifier: urlType, options: nil) { (item, error) in\n defer { group.leave() }\n \n if let url = item as? URL {\n foundURL = url\n } else if let data = item as? Data,\n let urlString = String(data: data, encoding: .utf8),\n let url = URL(string: urlString) {\n foundURL = url\n } else if let string = item as? String,\n let url = URL(string: string) {\n foundURL = url\n }\n }\n break // Found a URL type, no need to check other types\n }\n }\n \n // Also check for plain text that might be a URL\n if foundURL == nil && itemProvider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) {\n group.enter()\n itemProvider.loadItem(forTypeIdentifier: UTType.plainText.identifier, options: nil) { (item, error) in\n defer { group.leave() }\n \n if let text = item as? String {\n // Check if the text is actually a URL\n if let url = URL(string: text),\n (url.scheme == \"http\" || url.scheme == \"https\") {\n foundURL = url\n }\n }\n }\n }\n }\n } // End of if foundURL == nil\n \n // Process after all checks complete\n group.notify(queue: .main) { [weak self] in\n if let url = foundURL {\n // We have a URL! Create the JSON data\n let urlData: [String: String] = [\n \"url\": url.absoluteString,\n \"title\": pageTitle ?? url.host ?? \"Shared Link\"\n ]\n \n \n if let jsonData = try? JSONSerialization.data(withJSONObject: urlData),\n let jsonString = String(data: jsonData, encoding: .utf8) {\n self?.saveToSharedDefaults(content: jsonString, type: \"url\")\n }\n } else if let title = pageTitle, !title.isEmpty {\n // No URL found, just share the text\n self?.saveToSharedDefaults(content: title, type: \"text\")\n }\n \n self?.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)\n }\n }\n \n override func configurationItems() -> [Any]! {\n // No configuration items needed\n return []\n }\n \n // MARK: - Helper Methods\n \n private func handleSharedText(_ text: String) {\n // Save to shared user defaults to pass to main app\n saveToSharedDefaults(content: text, type: \"text\")\n openMainApp()\n }\n \n private func handleSharedURL(_ url: URL) {\n // Get the page title if available from the extension context\n var pageTitle: String? = nil\n if let item = extensionContext?.inputItems.first as? NSExtensionItem {\n pageTitle = item.attributedContentText?.string ?? item.attributedTitle?.string\n }\n \n // Create a structured format for URL sharing\n let urlData: [String: String] = [\n \"url\": url.absoluteString,\n \"title\": pageTitle ?? url.host ?? \"Shared Link\"\n ]\n \n // Convert to JSON string\n if let jsonData = try? JSONSerialization.data(withJSONObject: urlData),\n let jsonString = String(data: jsonData, encoding: .utf8) {\n saveToSharedDefaults(content: jsonString, type: \"url\")\n } else {\n // Fallback to simple URL\n saveToSharedDefaults(content: url.absoluteString, type: \"url\")\n }\n \n openMainApp()\n }\n \n private func handleSharedImage(_ image: UIImage) {\n // For now, we'll just notify that image sharing isn't supported\n // In the future, we could implement image sharing via the mesh\n saveToSharedDefaults(content: \"Image sharing coming soon!\", type: \"image\")\n openMainApp()\n }\n \n private func saveToSharedDefaults(content: String, type: String) {\n // Use app groups to share data between extension and main app\n guard let userDefaults = UserDefaults(suiteName: \"group.chat.bitchat\") else {\n return\n }\n \n userDefaults.set(content, forKey: \"sharedContent\")\n userDefaults.set(type, forKey: \"sharedContentType\")\n userDefaults.set(Date(), forKey: \"sharedContentDate\")\n userDefaults.synchronize()\n \n \n // Force open the main app\n self.openMainApp()\n }\n \n private func openMainApp() {\n // Share extensions cannot directly open the containing app\n // The app will check for shared content when it becomes active\n // Show success feedback to user\n DispatchQueue.main.async {\n self.textView.text = \"✓ Shared to bitchat\"\n self.textView.isEditable = false\n }\n }\n}"], ["/bitchat/bitchat/Noise/NoiseProtocol.swift", "//\n// NoiseProtocol.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # NoiseProtocol\n///\n/// A complete implementation of the Noise Protocol Framework for end-to-end\n/// encryption in BitChat. This file contains the core cryptographic primitives\n/// and handshake logic that enable secure communication between peers.\n///\n/// ## Overview\n/// The Noise Protocol Framework is a modern cryptographic framework designed\n/// for building secure protocols. BitChat uses Noise to provide:\n/// - Mutual authentication between peers\n/// - Forward secrecy for all messages\n/// - Protection against replay attacks\n/// - Minimal round trips for connection establishment\n///\n/// ## Implementation Details\n/// This implementation follows the Noise specification exactly, using:\n/// - **Pattern**: XX (most versatile, provides mutual authentication)\n/// - **DH**: Curve25519 (X25519 key exchange)\n/// - **Cipher**: ChaCha20-Poly1305 (AEAD encryption)\n/// - **Hash**: SHA-256 (for key derivation and authentication)\n///\n/// ## Security Properties\n/// The XX handshake pattern provides:\n/// 1. **Identity Hiding**: Both parties' identities are encrypted\n/// 2. **Forward Secrecy**: Past sessions remain secure if keys are compromised\n/// 3. **Key Compromise Impersonation Resistance**: Compromised static key doesn't allow impersonation to that party\n/// 4. **Mutual Authentication**: Both parties verify each other's identity\n///\n/// ## Handshake Flow (XX Pattern)\n/// ```\n/// Initiator Responder\n/// --------- ---------\n/// -> e (ephemeral key)\n/// <- e, ee, s, es (ephemeral, DH, static encrypted, DH)\n/// -> s, se (static encrypted, DH)\n/// ```\n///\n/// ## Key Components\n/// - **NoiseCipherState**: Manages symmetric encryption with nonce tracking\n/// - **NoiseSymmetricState**: Handles key derivation and handshake hashing\n/// - **NoiseHandshakeState**: Orchestrates the complete handshake process\n///\n/// ## Replay Protection\n/// Implements sliding window replay protection to prevent message replay attacks:\n/// - Tracks nonces within a 1024-message window\n/// - Rejects duplicate or too-old nonces\n/// - Handles out-of-order message delivery\n///\n/// ## Usage Example\n/// ```swift\n/// let handshake = NoiseHandshakeState(\n/// pattern: .XX,\n/// role: .initiator,\n/// localStatic: staticKeyPair\n/// )\n/// let messageBuffer = handshake.writeMessage(payload: Data())\n/// // Send messageBuffer to peer...\n/// ```\n///\n/// ## Security Considerations\n/// - Static keys must be generated using secure random sources\n/// - Keys should be stored securely (e.g., in Keychain)\n/// - Handshake state must not be reused after completion\n/// - Transport messages have a nonce limit (2^64-1)\n///\n/// ## References\n/// - Noise Protocol Framework: http://www.noiseprotocol.org/\n/// - Noise Specification: http://www.noiseprotocol.org/noise.html\n///\n\nimport Foundation\nimport CryptoKit\nimport os.log\n\n// Core Noise Protocol implementation\n// Based on the Noise Protocol Framework specification\n\n// MARK: - Constants and Types\n\n/// Supported Noise handshake patterns.\n/// Each pattern provides different security properties and authentication guarantees.\nenum NoisePattern {\n case XX // Most versatile, mutual authentication\n case IK // Initiator knows responder's static key\n case NK // Anonymous initiator\n}\n\nenum NoiseRole {\n case initiator\n case responder\n}\n\nenum NoiseMessagePattern {\n case e // Ephemeral key\n case s // Static key\n case ee // DH(ephemeral, ephemeral)\n case es // DH(ephemeral, static)\n case se // DH(static, ephemeral)\n case ss // DH(static, static)\n}\n\n// MARK: - Noise Protocol Configuration\n\nstruct NoiseProtocolName {\n let pattern: String\n let dh: String = \"25519\" // Curve25519\n let cipher: String = \"ChaChaPoly\" // ChaCha20-Poly1305\n let hash: String = \"SHA256\" // SHA-256\n \n var fullName: String {\n \"Noise_\\(pattern)_\\(dh)_\\(cipher)_\\(hash)\"\n }\n}\n\n// MARK: - Cipher State\n\n/// Manages symmetric encryption state for Noise protocol sessions.\n/// Handles ChaCha20-Poly1305 AEAD encryption with automatic nonce management\n/// and replay protection using a sliding window algorithm.\n/// - Warning: Nonce reuse would be catastrophic for security\nclass NoiseCipherState {\n // Constants for replay protection\n private static let NONCE_SIZE_BYTES = 4\n private static let REPLAY_WINDOW_SIZE = 1024\n private static let REPLAY_WINDOW_BYTES = REPLAY_WINDOW_SIZE / 8 // 128 bytes\n private static let HIGH_NONCE_WARNING_THRESHOLD: UInt64 = 1_000_000_000\n \n private var key: SymmetricKey?\n private var nonce: UInt64 = 0\n private var useExtractedNonce: Bool = false\n \n // Sliding window replay protection (only used when useExtractedNonce = true)\n private var highestReceivedNonce: UInt64 = 0\n private var replayWindow: [UInt8] = Array(repeating: 0, count: REPLAY_WINDOW_BYTES)\n \n init() {}\n \n init(key: SymmetricKey, useExtractedNonce: Bool = false) {\n self.key = key\n self.useExtractedNonce = useExtractedNonce\n }\n \n func initializeKey(_ key: SymmetricKey) {\n self.key = key\n self.nonce = 0\n }\n \n func hasKey() -> Bool {\n return key != nil\n }\n \n // MARK: - Sliding Window Replay Protection\n \n /// Check if nonce is valid for replay protection\n private func isValidNonce(_ receivedNonce: UInt64) -> Bool {\n if receivedNonce + UInt64(Self.REPLAY_WINDOW_SIZE) <= highestReceivedNonce {\n return false // Too old, outside window\n }\n \n if receivedNonce > highestReceivedNonce {\n return true // Always accept newer nonces\n }\n \n let offset = Int(highestReceivedNonce - receivedNonce)\n let byteIndex = offset / 8\n let bitIndex = offset % 8\n \n return (replayWindow[byteIndex] & (1 << bitIndex)) == 0 // Not yet seen\n }\n \n /// Mark nonce as seen in replay window\n private func markNonceAsSeen(_ receivedNonce: UInt64) {\n if receivedNonce > highestReceivedNonce {\n let shift = Int(receivedNonce - highestReceivedNonce)\n \n if shift >= Self.REPLAY_WINDOW_SIZE {\n // Clear entire window - shift is too large\n replayWindow = Array(repeating: 0, count: Self.REPLAY_WINDOW_BYTES)\n } else {\n // Shift window right by `shift` bits\n for i in stride(from: Self.REPLAY_WINDOW_BYTES - 1, through: 0, by: -1) {\n let sourceByteIndex = i - shift / 8\n var newByte: UInt8 = 0\n \n if sourceByteIndex >= 0 {\n newByte = replayWindow[sourceByteIndex] >> (shift % 8)\n if sourceByteIndex > 0 && shift % 8 != 0 {\n newByte |= replayWindow[sourceByteIndex - 1] << (8 - shift % 8)\n }\n }\n \n replayWindow[i] = newByte\n }\n }\n \n highestReceivedNonce = receivedNonce\n replayWindow[0] |= 1 // Mark most recent bit as seen\n } else {\n let offset = Int(highestReceivedNonce - receivedNonce)\n let byteIndex = offset / 8\n let bitIndex = offset % 8\n replayWindow[byteIndex] |= (1 << bitIndex)\n }\n }\n \n /// Extract nonce from combined payload \n /// Returns tuple of (nonce, ciphertext) or nil if invalid\n private func extractNonceFromCiphertextPayload(_ combinedPayload: Data) throws -> (nonce: UInt64, ciphertext: Data)? {\n guard combinedPayload.count >= Self.NONCE_SIZE_BYTES else {\n return nil\n }\n\n // Extract 4-byte nonce (big-endian)\n let nonceData = combinedPayload.prefix(Self.NONCE_SIZE_BYTES)\n let extractedNonce = nonceData.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> UInt64 in\n let byteArray = bytes.bindMemory(to: UInt8.self)\n var result: UInt64 = 0\n for i in 0.. Data {\n var bytes = Data(count: Self.NONCE_SIZE_BYTES)\n withUnsafeBytes(of: nonce.bigEndian) { ptr in\n // Copy only the last 4 bytes from the 8-byte UInt64 \n let sourceBytes = ptr.bindMemory(to: UInt8.self)\n bytes.replaceSubrange(0.. Data {\n guard let key = self.key else {\n throw NoiseError.uninitializedCipher\n }\n \n // Debug logging for nonce tracking\n let currentNonce = nonce\n \n // Check if nonce exceeds 4-byte limit (UInt32 max value)\n guard nonce <= UInt64(UInt32.max) - 1 else {\n throw NoiseError.nonceExceeded\n }\n \n // Create nonce from counter\n var nonceData = Data(count: 12)\n withUnsafeBytes(of: currentNonce.littleEndian) { bytes in\n nonceData.replaceSubrange(4..<12, with: bytes)\n }\n \n let sealedBox = try ChaChaPoly.seal(plaintext, using: key, nonce: ChaChaPoly.Nonce(data: nonceData), authenticating: associatedData)\n // increment local nonce\n nonce += 1\n \n // Create combined payload: \n let combinedPayload: Data\n if (useExtractedNonce) {\n let nonceBytes = nonceToBytes(currentNonce)\n combinedPayload = nonceBytes + sealedBox.ciphertext + sealedBox.tag\n } else {\n combinedPayload = sealedBox.ciphertext + sealedBox.tag\n }\n \n // Log high nonce values that might indicate issues\n if currentNonce > Self.HIGH_NONCE_WARNING_THRESHOLD {\n SecureLogger.log(\"High nonce value detected: \\(currentNonce) - consider rekeying\", category: SecureLogger.encryption, level: .warning)\n }\n \n return combinedPayload\n }\n \n func decrypt(ciphertext: Data, associatedData: Data = Data()) throws -> Data {\n guard let key = self.key else {\n throw NoiseError.uninitializedCipher\n }\n \n guard ciphertext.count >= 16 else {\n throw NoiseError.invalidCiphertext\n }\n \n let encryptedData: Data\n let tag: Data\n let decryptionNonce: UInt64\n \n if useExtractedNonce {\n // Extract nonce and ciphertext from combined payload\n guard let (extractedNonce, actualCiphertext) = try extractNonceFromCiphertextPayload(ciphertext) else {\n SecureLogger.log(\"Decrypt failed: Could not extract nonce from payload\")\n throw NoiseError.invalidCiphertext\n }\n \n // Validate nonce with sliding window replay protection\n guard isValidNonce(extractedNonce) else {\n SecureLogger.log(\"Replay attack detected: nonce \\(extractedNonce) rejected\")\n throw NoiseError.replayDetected\n }\n\n // Split ciphertext and tag\n encryptedData = actualCiphertext.prefix(actualCiphertext.count - 16)\n tag = actualCiphertext.suffix(16)\n decryptionNonce = extractedNonce\n } else {\n // Split ciphertext and tag\n encryptedData = ciphertext.prefix(ciphertext.count - 16)\n tag = ciphertext.suffix(16)\n decryptionNonce = nonce\n }\n \n // Create nonce from counter\n var nonceData = Data(count: 12)\n withUnsafeBytes(of: decryptionNonce.littleEndian) { bytes in\n nonceData.replaceSubrange(4..<12, with: bytes)\n }\n \n let sealedBox = try ChaChaPoly.SealedBox(\n nonce: ChaChaPoly.Nonce(data: nonceData),\n ciphertext: encryptedData,\n tag: tag\n )\n \n // Log high nonce values that might indicate issues\n if decryptionNonce > Self.HIGH_NONCE_WARNING_THRESHOLD {\n SecureLogger.log(\"High nonce value detected: \\(decryptionNonce) - consider rekeying\", category: SecureLogger.encryption, level: .warning)\n }\n \n do {\n let plaintext = try ChaChaPoly.open(sealedBox, using: key, authenticating: associatedData)\n \n if useExtractedNonce {\n // Mark nonce as seen after successful decryption\n markNonceAsSeen(decryptionNonce)\n }\n nonce += 1\n return plaintext\n } catch {\n SecureLogger.log(\"Decrypt failed: \\(error) for nonce \\(decryptionNonce)\")\n // Log authentication failures with nonce info\n SecureLogger.log(\"Decryption failed at nonce \\(decryptionNonce)\", category: SecureLogger.encryption, level: .error)\n throw error\n }\n }\n}\n\n// MARK: - Symmetric State\n\n/// Manages the symmetric cryptographic state during Noise handshakes.\n/// Responsible for key derivation, protocol name hashing, and maintaining\n/// the chaining key that provides key separation between handshake messages.\n/// - Note: This class implements the SymmetricState object from the Noise spec\nclass NoiseSymmetricState {\n private var cipherState: NoiseCipherState\n private var chainingKey: Data\n private var hash: Data\n \n init(protocolName: String) {\n self.cipherState = NoiseCipherState()\n \n // Initialize with protocol name\n let nameData = protocolName.data(using: .utf8)!\n if nameData.count <= 32 {\n self.hash = nameData + Data(repeating: 0, count: 32 - nameData.count)\n } else {\n self.hash = Data(SHA256.hash(data: nameData))\n }\n self.chainingKey = self.hash\n }\n \n func mixKey(_ inputKeyMaterial: Data) {\n let output = hkdf(chainingKey: chainingKey, inputKeyMaterial: inputKeyMaterial, numOutputs: 2)\n chainingKey = output[0]\n let tempKey = SymmetricKey(data: output[1])\n cipherState.initializeKey(tempKey)\n }\n \n func mixHash(_ data: Data) {\n hash = Data(SHA256.hash(data: hash + data))\n }\n \n func mixKeyAndHash(_ inputKeyMaterial: Data) {\n let output = hkdf(chainingKey: chainingKey, inputKeyMaterial: inputKeyMaterial, numOutputs: 3)\n chainingKey = output[0]\n mixHash(output[1])\n let tempKey = SymmetricKey(data: output[2])\n cipherState.initializeKey(tempKey)\n }\n \n func getHandshakeHash() -> Data {\n return hash\n }\n \n func hasCipherKey() -> Bool {\n return cipherState.hasKey()\n }\n \n func encryptAndHash(_ plaintext: Data) throws -> Data {\n if cipherState.hasKey() {\n let ciphertext = try cipherState.encrypt(plaintext: plaintext, associatedData: hash)\n mixHash(ciphertext)\n return ciphertext\n } else {\n mixHash(plaintext)\n return plaintext\n }\n }\n \n func decryptAndHash(_ ciphertext: Data) throws -> Data {\n if cipherState.hasKey() {\n let plaintext = try cipherState.decrypt(ciphertext: ciphertext, associatedData: hash)\n mixHash(ciphertext)\n return plaintext\n } else {\n mixHash(ciphertext)\n return ciphertext\n }\n }\n \n func split() -> (NoiseCipherState, NoiseCipherState) {\n let output = hkdf(chainingKey: chainingKey, inputKeyMaterial: Data(), numOutputs: 2)\n let tempKey1 = SymmetricKey(data: output[0])\n let tempKey2 = SymmetricKey(data: output[1])\n \n let c1 = NoiseCipherState(key: tempKey1, useExtractedNonce: true)\n let c2 = NoiseCipherState(key: tempKey2, useExtractedNonce: true)\n \n return (c1, c2)\n }\n \n // HKDF implementation\n private func hkdf(chainingKey: Data, inputKeyMaterial: Data, numOutputs: Int) -> [Data] {\n let tempKey = HMAC.authenticationCode(for: inputKeyMaterial, using: SymmetricKey(data: chainingKey))\n let tempKeyData = Data(tempKey)\n \n var outputs: [Data] = []\n var currentOutput = Data()\n \n for i in 1...numOutputs {\n currentOutput = Data(HMAC.authenticationCode(\n for: currentOutput + Data([UInt8(i)]),\n using: SymmetricKey(data: tempKeyData)\n ))\n outputs.append(currentOutput)\n }\n \n return outputs\n }\n}\n\n// MARK: - Handshake State\n\n/// Orchestrates the complete Noise handshake process.\n/// This is the main interface for establishing encrypted sessions between peers.\n/// Manages the handshake state machine, message patterns, and key derivation.\n/// - Important: Each handshake instance should only be used once\nclass NoiseHandshakeState {\n private let role: NoiseRole\n private let pattern: NoisePattern\n private var symmetricState: NoiseSymmetricState\n \n // Keys\n private var localStaticPrivate: Curve25519.KeyAgreement.PrivateKey?\n private var localStaticPublic: Curve25519.KeyAgreement.PublicKey?\n private var localEphemeralPrivate: Curve25519.KeyAgreement.PrivateKey?\n private var localEphemeralPublic: Curve25519.KeyAgreement.PublicKey?\n \n private var remoteStaticPublic: Curve25519.KeyAgreement.PublicKey?\n private var remoteEphemeralPublic: Curve25519.KeyAgreement.PublicKey?\n \n // Message patterns\n private var messagePatterns: [[NoiseMessagePattern]] = []\n private var currentPattern = 0\n \n init(role: NoiseRole, pattern: NoisePattern, localStaticKey: Curve25519.KeyAgreement.PrivateKey? = nil, remoteStaticKey: Curve25519.KeyAgreement.PublicKey? = nil) {\n self.role = role\n self.pattern = pattern\n \n // Initialize static keys\n if let localKey = localStaticKey {\n self.localStaticPrivate = localKey\n self.localStaticPublic = localKey.publicKey\n }\n self.remoteStaticPublic = remoteStaticKey\n \n // Initialize protocol name\n let protocolName = NoiseProtocolName(pattern: pattern.patternName)\n self.symmetricState = NoiseSymmetricState(protocolName: protocolName.fullName)\n \n // Initialize message patterns\n self.messagePatterns = pattern.messagePatterns\n \n // Mix pre-message keys according to pattern\n mixPreMessageKeys()\n }\n \n private func mixPreMessageKeys() {\n // Mix prologue (empty for XX pattern normally)\n symmetricState.mixHash(Data()) // Empty prologue for XX pattern\n // For XX pattern, no pre-message keys\n // For IK/NK patterns, we'd mix the responder's static key here\n switch pattern {\n case .XX:\n break // No pre-message keys\n case .IK, .NK:\n if role == .initiator, let remoteStatic = remoteStaticPublic {\n _ = symmetricState.getHandshakeHash()\n symmetricState.mixHash(remoteStatic.rawRepresentation)\n }\n }\n }\n \n func writeMessage(payload: Data = Data()) throws -> Data {\n guard currentPattern < messagePatterns.count else {\n throw NoiseError.handshakeComplete\n }\n \n var messageBuffer = Data()\n let patterns = messagePatterns[currentPattern]\n \n for pattern in patterns {\n switch pattern {\n case .e:\n // Generate ephemeral key\n localEphemeralPrivate = Curve25519.KeyAgreement.PrivateKey()\n localEphemeralPublic = localEphemeralPrivate!.publicKey\n messageBuffer.append(localEphemeralPublic!.rawRepresentation)\n symmetricState.mixHash(localEphemeralPublic!.rawRepresentation)\n \n case .s:\n // Send static key (encrypted if cipher is initialized)\n guard let staticPublic = localStaticPublic else {\n throw NoiseError.missingLocalStaticKey\n }\n let encrypted = try symmetricState.encryptAndHash(staticPublic.rawRepresentation)\n messageBuffer.append(encrypted)\n \n case .ee:\n // DH(local ephemeral, remote ephemeral)\n guard let localEphemeral = localEphemeralPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n \n case .es:\n // DH(ephemeral, static) - direction depends on role\n if role == .initiator {\n guard let localEphemeral = localEphemeralPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n } else {\n guard let localStatic = localStaticPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n }\n \n case .se:\n // DH(static, ephemeral) - direction depends on role\n if role == .initiator {\n guard let localStatic = localStaticPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n } else {\n guard let localEphemeral = localEphemeralPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n }\n \n case .ss:\n // DH(static, static)\n guard let localStatic = localStaticPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n }\n }\n \n // Encrypt payload\n let encryptedPayload = try symmetricState.encryptAndHash(payload)\n messageBuffer.append(encryptedPayload)\n \n currentPattern += 1\n return messageBuffer\n }\n \n func readMessage(_ message: Data, expectedPayloadLength: Int = 0) throws -> Data {\n \n guard currentPattern < messagePatterns.count else {\n throw NoiseError.handshakeComplete\n }\n \n var buffer = message\n let patterns = messagePatterns[currentPattern]\n \n for pattern in patterns {\n switch pattern {\n case .e:\n // Read ephemeral key\n guard buffer.count >= 32 else {\n throw NoiseError.invalidMessage\n }\n let ephemeralData = buffer.prefix(32)\n buffer = buffer.dropFirst(32)\n \n do {\n remoteEphemeralPublic = try NoiseHandshakeState.validatePublicKey(ephemeralData)\n } catch {\n SecureLogger.log(\"Invalid ephemeral public key received\", category: SecureLogger.security, level: .warning)\n throw NoiseError.invalidMessage\n }\n symmetricState.mixHash(ephemeralData)\n \n case .s:\n // Read static key (may be encrypted)\n let keyLength = symmetricState.hasCipherKey() ? 48 : 32 // 32 + 16 byte tag if encrypted\n guard buffer.count >= keyLength else {\n throw NoiseError.invalidMessage\n }\n let staticData = buffer.prefix(keyLength)\n buffer = buffer.dropFirst(keyLength)\n do {\n let decrypted = try symmetricState.decryptAndHash(staticData)\n remoteStaticPublic = try NoiseHandshakeState.validatePublicKey(decrypted)\n } catch {\n SecureLogger.logSecurityEvent(.authenticationFailed(peerID: \"Unknown - handshake\"), level: .error)\n throw NoiseError.authenticationFailure\n }\n \n case .ee, .es, .se, .ss:\n // Same DH operations as in writeMessage\n try performDHOperation(pattern)\n }\n }\n \n // Decrypt payload\n let payload = try symmetricState.decryptAndHash(buffer)\n currentPattern += 1\n \n return payload\n }\n \n private func performDHOperation(_ pattern: NoiseMessagePattern) throws {\n switch pattern {\n case .ee:\n guard let localEphemeral = localEphemeralPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n \n case .es:\n if role == .initiator {\n guard let localEphemeral = localEphemeralPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n } else {\n guard let localStatic = localStaticPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n }\n \n case .se:\n if role == .initiator {\n guard let localStatic = localStaticPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n } else {\n guard let localEphemeral = localEphemeralPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n }\n \n case .ss:\n guard let localStatic = localStaticPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n \n default:\n break\n }\n }\n \n func isHandshakeComplete() -> Bool {\n return currentPattern >= messagePatterns.count\n }\n \n func getTransportCiphers() throws -> (send: NoiseCipherState, receive: NoiseCipherState) {\n guard isHandshakeComplete() else {\n throw NoiseError.handshakeNotComplete\n }\n \n let (c1, c2) = symmetricState.split()\n \n // Initiator uses c1 for sending, c2 for receiving\n // Responder uses c2 for sending, c1 for receiving\n return role == .initiator ? (c1, c2) : (c2, c1)\n }\n \n func getRemoteStaticPublicKey() -> Curve25519.KeyAgreement.PublicKey? {\n return remoteStaticPublic\n }\n \n func getHandshakeHash() -> Data {\n return symmetricState.getHandshakeHash()\n }\n}\n\n// MARK: - Pattern Extensions\n\nextension NoisePattern {\n var patternName: String {\n switch self {\n case .XX: return \"XX\"\n case .IK: return \"IK\"\n case .NK: return \"NK\"\n }\n }\n \n var messagePatterns: [[NoiseMessagePattern]] {\n switch self {\n case .XX:\n return [\n [.e], // -> e\n [.e, .ee, .s, .es], // <- e, ee, s, es\n [.s, .se] // -> s, se\n ]\n case .IK:\n return [\n [.e, .es, .s, .ss], // -> e, es, s, ss\n [.e, .ee, .se] // <- e, ee, se\n ]\n case .NK:\n return [\n [.e, .es], // -> e, es\n [.e, .ee] // <- e, ee\n ]\n }\n }\n}\n\n// MARK: - Errors\n\nenum NoiseError: Error {\n case uninitializedCipher\n case invalidCiphertext\n case handshakeComplete\n case handshakeNotComplete\n case missingLocalStaticKey\n case missingKeys\n case invalidMessage\n case authenticationFailure\n case invalidPublicKey\n case replayDetected\n case nonceExceeded\n}\n\n// MARK: - Key Validation\n\nextension NoiseHandshakeState {\n /// Validate a Curve25519 public key\n /// Checks for weak/invalid keys that could compromise security\n static func validatePublicKey(_ keyData: Data) throws -> Curve25519.KeyAgreement.PublicKey {\n // Check key length\n guard keyData.count == 32 else {\n throw NoiseError.invalidPublicKey\n }\n \n // Check for all-zero key (point at infinity)\n if keyData.allSatisfy({ $0 == 0 }) {\n throw NoiseError.invalidPublicKey\n }\n \n // Check for low-order points that could enable small subgroup attacks\n // These are the known bad points for Curve25519\n let lowOrderPoints: [Data] = [\n Data(repeating: 0x00, count: 32), // Already checked above\n Data([0x01] + Data(repeating: 0x00, count: 31)), // Point of order 1\n Data([0x00] + Data(repeating: 0x00, count: 30) + [0x01]), // Another low-order point\n Data([0xe0, 0xeb, 0x7a, 0x7c, 0x3b, 0x41, 0xb8, 0xae, 0x16, 0x56, 0xe3,\n 0xfa, 0xf1, 0x9f, 0xc4, 0x6a, 0xda, 0x09, 0x8d, 0xeb, 0x9c, 0x32,\n 0xb1, 0xfd, 0x86, 0x62, 0x05, 0x16, 0x5f, 0x49, 0xb8, 0x00]), // Low order point\n Data([0x5f, 0x9c, 0x95, 0xbc, 0xa3, 0x50, 0x8c, 0x24, 0xb1, 0xd0, 0xb1,\n 0x55, 0x9c, 0x83, 0xef, 0x5b, 0x04, 0x44, 0x5c, 0xc4, 0x58, 0x1c,\n 0x8e, 0x86, 0xd8, 0x22, 0x4e, 0xdd, 0xd0, 0x9f, 0x11, 0x57]), // Low order point\n Data(repeating: 0xFF, count: 32), // All ones\n Data([0xda, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), // Another bad point\n Data([0xdb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]) // Another bad point\n ]\n \n // Check against known bad points\n if lowOrderPoints.contains(keyData) {\n SecureLogger.log(\"Low-order point detected\", category: SecureLogger.security, level: .warning)\n throw NoiseError.invalidPublicKey\n }\n \n // Try to create the key - CryptoKit will validate curve points internally\n do {\n let publicKey = try Curve25519.KeyAgreement.PublicKey(rawRepresentation: keyData)\n return publicKey\n } catch {\n // If CryptoKit rejects it, it's invalid\n SecureLogger.log(\"CryptoKit validation failed\", category: SecureLogger.security, level: .warning)\n throw NoiseError.invalidPublicKey\n }\n }\n}\n"], ["/bitchat/bitchat/Noise/NoiseSession.swift", "//\n// NoiseSession.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport CryptoKit\nimport os.log\n\n// MARK: - Noise Session State\n\nenum NoiseSessionState: Equatable {\n case uninitialized\n case handshaking\n case established\n case failed(Error)\n \n static func == (lhs: NoiseSessionState, rhs: NoiseSessionState) -> Bool {\n switch (lhs, rhs) {\n case (.uninitialized, .uninitialized),\n (.handshaking, .handshaking),\n (.established, .established):\n return true\n case (.failed, .failed):\n return true // We don't compare the errors\n default:\n return false\n }\n }\n}\n\n// MARK: - Noise Session\n\nclass NoiseSession {\n let peerID: String\n let role: NoiseRole\n private var state: NoiseSessionState = .uninitialized\n private var handshakeState: NoiseHandshakeState?\n private var sendCipher: NoiseCipherState?\n private var receiveCipher: NoiseCipherState?\n \n // Keys\n private let localStaticKey: Curve25519.KeyAgreement.PrivateKey\n private var remoteStaticPublicKey: Curve25519.KeyAgreement.PublicKey?\n \n // Handshake messages for retransmission\n private var sentHandshakeMessages: [Data] = []\n private var handshakeHash: Data?\n \n // Thread safety\n private let sessionQueue = DispatchQueue(label: \"chat.bitchat.noise.session\", attributes: .concurrent)\n \n init(peerID: String, role: NoiseRole, localStaticKey: Curve25519.KeyAgreement.PrivateKey, remoteStaticKey: Curve25519.KeyAgreement.PublicKey? = nil) {\n self.peerID = peerID\n self.role = role\n self.localStaticKey = localStaticKey\n self.remoteStaticPublicKey = remoteStaticKey\n }\n \n // MARK: - Handshake\n \n func startHandshake() throws -> Data {\n return try sessionQueue.sync(flags: .barrier) {\n guard case .uninitialized = state else {\n throw NoiseSessionError.invalidState\n }\n \n // For XX pattern, we don't need remote static key upfront\n handshakeState = NoiseHandshakeState(\n role: role,\n pattern: .XX,\n localStaticKey: localStaticKey,\n remoteStaticKey: nil\n )\n \n state = .handshaking\n \n // Only initiator writes the first message\n if role == .initiator {\n let message = try handshakeState!.writeMessage()\n sentHandshakeMessages.append(message)\n return message\n } else {\n // Responder doesn't send first message in XX pattern\n return Data()\n }\n }\n }\n \n func processHandshakeMessage(_ message: Data) throws -> Data? {\n return try sessionQueue.sync(flags: .barrier) {\n SecureLogger.log(\"NoiseSession[\\(peerID)]: Processing handshake message, current state: \\(state), role: \\(role)\", category: SecureLogger.noise, level: .info)\n \n // Initialize handshake state if needed (for responders)\n if state == .uninitialized && role == .responder {\n handshakeState = NoiseHandshakeState(\n role: role,\n pattern: .XX,\n localStaticKey: localStaticKey,\n remoteStaticKey: nil\n )\n state = .handshaking\n SecureLogger.log(\"NoiseSession[\\(peerID)]: Initialized handshake state for responder\", category: SecureLogger.noise, level: .info)\n }\n \n guard case .handshaking = state, let handshake = handshakeState else {\n throw NoiseSessionError.invalidState\n }\n \n // Process incoming message\n _ = try handshake.readMessage(message)\n SecureLogger.log(\"NoiseSession[\\(peerID)]: Read handshake message, checking if complete\", category: SecureLogger.noise, level: .info)\n \n // Check if handshake is complete\n if handshake.isHandshakeComplete() {\n // Get transport ciphers\n let (send, receive) = try handshake.getTransportCiphers()\n sendCipher = send\n receiveCipher = receive\n \n // Store remote static key\n remoteStaticPublicKey = handshake.getRemoteStaticPublicKey()\n \n // Store handshake hash for channel binding\n handshakeHash = handshake.getHandshakeHash()\n \n state = .established\n handshakeState = nil // Clear handshake state\n \n SecureLogger.log(\"NoiseSession[\\(peerID)]: Handshake complete (no response needed), transitioning to established\", category: SecureLogger.noise, level: .info)\n SecureLogger.logSecurityEvent(.handshakeCompleted(peerID: peerID))\n \n return nil\n } else {\n // Generate response\n let response = try handshake.writeMessage()\n sentHandshakeMessages.append(response)\n SecureLogger.log(\"NoiseSession[\\(peerID)]: Generated handshake response of size \\(response.count)\", category: SecureLogger.noise, level: .info)\n \n // Check if handshake is complete after writing\n if handshake.isHandshakeComplete() {\n // Get transport ciphers\n let (send, receive) = try handshake.getTransportCiphers()\n sendCipher = send\n receiveCipher = receive\n \n // Store remote static key\n remoteStaticPublicKey = handshake.getRemoteStaticPublicKey()\n \n // Store handshake hash for channel binding\n handshakeHash = handshake.getHandshakeHash()\n \n state = .established\n handshakeState = nil // Clear handshake state\n \n SecureLogger.log(\"NoiseSession[\\(peerID)]: Handshake complete after writing response, transitioning to established\", category: SecureLogger.noise, level: .info)\n SecureLogger.logSecurityEvent(.handshakeCompleted(peerID: peerID))\n }\n \n return response\n }\n }\n }\n \n // MARK: - Transport\n \n func encrypt(_ plaintext: Data) throws -> Data {\n return try sessionQueue.sync(flags: .barrier) {\n guard case .established = state, let cipher = sendCipher else {\n throw NoiseSessionError.notEstablished\n }\n \n return try cipher.encrypt(plaintext: plaintext)\n }\n }\n \n func decrypt(_ ciphertext: Data) throws -> Data {\n return try sessionQueue.sync(flags: .barrier) {\n guard case .established = state, let cipher = receiveCipher else {\n throw NoiseSessionError.notEstablished\n }\n \n return try cipher.decrypt(ciphertext: ciphertext)\n }\n }\n \n // MARK: - State Management\n \n func getState() -> NoiseSessionState {\n return sessionQueue.sync {\n return state\n }\n }\n \n func isEstablished() -> Bool {\n return sessionQueue.sync {\n if case .established = state {\n return true\n }\n return false\n }\n }\n \n func getRemoteStaticPublicKey() -> Curve25519.KeyAgreement.PublicKey? {\n return sessionQueue.sync {\n return remoteStaticPublicKey\n }\n }\n \n func getHandshakeHash() -> Data? {\n return sessionQueue.sync {\n return handshakeHash\n }\n }\n \n func reset() {\n sessionQueue.sync(flags: .barrier) {\n let wasEstablished = state == .established\n state = .uninitialized\n handshakeState = nil\n sendCipher = nil\n receiveCipher = nil\n sentHandshakeMessages.removeAll()\n handshakeHash = nil\n \n if wasEstablished {\n SecureLogger.logSecurityEvent(.sessionExpired(peerID: peerID))\n }\n }\n }\n}\n\n// MARK: - Session Manager\n\nclass NoiseSessionManager {\n private var sessions: [String: NoiseSession] = [:]\n private let localStaticKey: Curve25519.KeyAgreement.PrivateKey\n private let managerQueue = DispatchQueue(label: \"chat.bitchat.noise.manager\", attributes: .concurrent)\n \n // Callbacks\n var onSessionEstablished: ((String, Curve25519.KeyAgreement.PublicKey) -> Void)?\n var onSessionFailed: ((String, Error) -> Void)?\n \n init(localStaticKey: Curve25519.KeyAgreement.PrivateKey) {\n self.localStaticKey = localStaticKey\n }\n \n // MARK: - Session Management\n \n func createSession(for peerID: String, role: NoiseRole) -> NoiseSession {\n return managerQueue.sync(flags: .barrier) {\n let session = SecureNoiseSession(\n peerID: peerID,\n role: role,\n localStaticKey: localStaticKey\n )\n sessions[peerID] = session\n return session\n }\n }\n \n func getSession(for peerID: String) -> NoiseSession? {\n return managerQueue.sync {\n return sessions[peerID]\n }\n }\n \n func removeSession(for peerID: String) {\n managerQueue.sync(flags: .barrier) {\n if let session = sessions[peerID], session.isEstablished() {\n SecureLogger.logSecurityEvent(.sessionExpired(peerID: peerID))\n }\n _ = sessions.removeValue(forKey: peerID)\n }\n }\n \n func migrateSession(from oldPeerID: String, to newPeerID: String) {\n managerQueue.sync(flags: .barrier) {\n // Check if we have a session for the old peer ID\n if let session = sessions[oldPeerID] {\n // Move the session to the new peer ID\n sessions[newPeerID] = session\n _ = sessions.removeValue(forKey: oldPeerID)\n \n SecureLogger.log(\"Migrated Noise session from \\(oldPeerID) to \\(newPeerID)\", category: SecureLogger.noise, level: .info)\n }\n }\n }\n \n func getEstablishedSessions() -> [String: NoiseSession] {\n return managerQueue.sync {\n return sessions.filter { $0.value.isEstablished() }\n }\n }\n \n // MARK: - Handshake Helpers\n \n func initiateHandshake(with peerID: String) throws -> Data {\n return try managerQueue.sync(flags: .barrier) {\n // Check if we already have an established session\n if let existingSession = sessions[peerID], existingSession.isEstablished() {\n // Session already established, don't recreate\n throw NoiseSessionError.alreadyEstablished\n }\n \n // Remove any existing non-established session\n if let existingSession = sessions[peerID], !existingSession.isEstablished() {\n _ = sessions.removeValue(forKey: peerID)\n }\n \n // Create new initiator session\n let session = SecureNoiseSession(\n peerID: peerID,\n role: .initiator,\n localStaticKey: localStaticKey\n )\n sessions[peerID] = session\n \n do {\n let handshakeData = try session.startHandshake()\n return handshakeData\n } catch {\n // Clean up failed session\n _ = sessions.removeValue(forKey: peerID)\n SecureLogger.logSecurityEvent(.handshakeFailed(peerID: peerID, error: error.localizedDescription), level: .error)\n throw error\n }\n }\n }\n \n func handleIncomingHandshake(from peerID: String, message: Data) throws -> Data? {\n // Process everything within the synchronized block to prevent race conditions\n return try managerQueue.sync(flags: .barrier) {\n var shouldCreateNew = false\n var existingSession: NoiseSession? = nil\n \n if let existing = sessions[peerID] {\n // If we have an established session, the peer must have cleared their session\n // for a good reason (e.g., decryption failure, restart, etc.)\n // We should accept the new handshake to re-establish encryption\n if existing.isEstablished() {\n SecureLogger.log(\"Accepting handshake from \\(peerID) despite existing session - peer likely cleared their session\", \n category: SecureLogger.session, level: .info)\n _ = sessions.removeValue(forKey: peerID)\n shouldCreateNew = true\n } else {\n // If we're in the middle of a handshake and receive a new initiation,\n // reset and start fresh (the other side may have restarted)\n if existing.getState() == .handshaking && message.count == 32 {\n _ = sessions.removeValue(forKey: peerID)\n shouldCreateNew = true\n } else {\n existingSession = existing\n }\n }\n } else {\n shouldCreateNew = true\n }\n \n // Get or create session\n let session: NoiseSession\n if shouldCreateNew {\n let newSession = SecureNoiseSession(\n peerID: peerID,\n role: .responder,\n localStaticKey: localStaticKey\n )\n sessions[peerID] = newSession\n session = newSession\n } else {\n session = existingSession!\n }\n \n // Process the handshake message within the synchronized block\n do {\n let response = try session.processHandshakeMessage(message)\n \n // Check if session is established after processing\n if session.isEstablished() {\n if let remoteKey = session.getRemoteStaticPublicKey() {\n // Schedule callback outside the synchronized block to prevent deadlock\n DispatchQueue.global().async { [weak self] in\n self?.onSessionEstablished?(peerID, remoteKey)\n }\n }\n }\n \n return response\n } catch {\n // Reset the session on handshake failure so next attempt can start fresh\n _ = sessions.removeValue(forKey: peerID)\n \n // Schedule callback outside the synchronized block to prevent deadlock\n DispatchQueue.global().async { [weak self] in\n self?.onSessionFailed?(peerID, error)\n }\n \n SecureLogger.logSecurityEvent(.handshakeFailed(peerID: peerID, error: error.localizedDescription), level: .error)\n throw error\n }\n }\n }\n \n // MARK: - Encryption/Decryption\n \n func encrypt(_ plaintext: Data, for peerID: String) throws -> Data {\n guard let session = getSession(for: peerID) else {\n throw NoiseSessionError.sessionNotFound\n }\n \n return try session.encrypt(plaintext)\n }\n \n func decrypt(_ ciphertext: Data, from peerID: String) throws -> Data {\n guard let session = getSession(for: peerID) else {\n throw NoiseSessionError.sessionNotFound\n }\n \n return try session.decrypt(ciphertext)\n }\n \n // MARK: - Key Management\n \n func getRemoteStaticKey(for peerID: String) -> Curve25519.KeyAgreement.PublicKey? {\n return getSession(for: peerID)?.getRemoteStaticPublicKey()\n }\n \n func getHandshakeHash(for peerID: String) -> Data? {\n return getSession(for: peerID)?.getHandshakeHash()\n }\n \n // MARK: - Session Rekeying\n \n func getSessionsNeedingRekey() -> [(peerID: String, needsRekey: Bool)] {\n return managerQueue.sync {\n var needingRekey: [(peerID: String, needsRekey: Bool)] = []\n \n for (peerID, session) in sessions {\n if let secureSession = session as? SecureNoiseSession,\n secureSession.isEstablished(),\n secureSession.needsRenegotiation() {\n needingRekey.append((peerID: peerID, needsRekey: true))\n }\n }\n \n return needingRekey\n }\n }\n \n func initiateRekey(for peerID: String) throws {\n // Remove old session\n removeSession(for: peerID)\n \n // Initiate new handshake\n _ = try initiateHandshake(with: peerID)\n \n }\n}\n\n// MARK: - Errors\n\nenum NoiseSessionError: Error {\n case invalidState\n case notEstablished\n case sessionNotFound\n case handshakeFailed(Error)\n case alreadyEstablished\n}"], ["/bitchat/bitchat/Protocols/BinaryProtocol.swift", "//\n// BinaryProtocol.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # BinaryProtocol\n///\n/// Low-level binary encoding and decoding for BitChat protocol messages.\n/// Optimized for Bluetooth LE's limited bandwidth and MTU constraints.\n///\n/// ## Overview\n/// BinaryProtocol implements an efficient binary wire format that minimizes\n/// overhead while maintaining extensibility. It handles:\n/// - Compact binary encoding with fixed headers\n/// - Optional field support via flags\n/// - Automatic compression for large payloads\n/// - Endianness handling for cross-platform compatibility\n///\n/// ## Wire Format\n/// ```\n/// Header (Fixed 13 bytes):\n/// +--------+------+-----+-----------+-------+----------------+\n/// |Version | Type | TTL | Timestamp | Flags | PayloadLength |\n/// |1 byte |1 byte|1byte| 8 bytes | 1 byte| 2 bytes |\n/// +--------+------+-----+-----------+-------+----------------+\n///\n/// Variable sections:\n/// +----------+-------------+---------+------------+\n/// | SenderID | RecipientID | Payload | Signature |\n/// | 8 bytes | 8 bytes* | Variable| 64 bytes* |\n/// +----------+-------------+---------+------------+\n/// * Optional fields based on flags\n/// ```\n///\n/// ## Design Rationale\n/// The protocol is designed for:\n/// - **Efficiency**: Minimal overhead for small messages\n/// - **Flexibility**: Optional fields via flag bits\n/// - **Compatibility**: Network byte order (big-endian)\n/// - **Performance**: Zero-copy where possible\n///\n/// ## Compression Strategy\n/// - Automatic compression for payloads > 256 bytes\n/// - LZ4 algorithm for speed over ratio\n/// - Original size stored for decompression\n/// - Flag bit indicates compressed payload\n///\n/// ## Flag Bits\n/// - Bit 0: Has recipient ID (directed message)\n/// - Bit 1: Has signature (authenticated message)\n/// - Bit 2: Is compressed (LZ4 compression applied)\n/// - Bits 3-7: Reserved for future use\n///\n/// ## Size Constraints\n/// - Maximum packet size: 65,535 bytes (16-bit length field)\n/// - Typical packet size: < 512 bytes (BLE MTU)\n/// - Minimum packet size: 21 bytes (header + sender ID)\n///\n/// ## Encoding Process\n/// 1. Construct header with fixed fields\n/// 2. Set appropriate flags\n/// 3. Compress payload if beneficial\n/// 4. Append variable-length fields\n/// 5. Calculate and append signature if needed\n///\n/// ## Decoding Process\n/// 1. Validate minimum packet size\n/// 2. Parse fixed header\n/// 3. Extract flags and determine field presence\n/// 4. Parse variable fields based on flags\n/// 5. Decompress payload if compressed\n/// 6. Verify signature if present\n///\n/// ## Error Handling\n/// - Graceful handling of malformed packets\n/// - Clear error messages for debugging\n/// - No crashes on invalid input\n/// - Logging of protocol violations\n///\n/// ## Performance Notes\n/// - Allocation-free for small messages\n/// - Streaming support for large payloads\n/// - Efficient bit manipulation\n/// - Platform-optimized byte swapping\n///\n\nimport Foundation\n\nextension Data {\n func trimmingNullBytes() -> Data {\n // Find the first null byte\n if let nullIndex = self.firstIndex(of: 0) {\n return self.prefix(nullIndex)\n }\n return self\n }\n}\n\n/// Implements binary encoding and decoding for BitChat protocol messages.\n/// Provides static methods for converting between BitchatPacket objects and\n/// their binary wire format representation.\n/// - Note: All multi-byte values use network byte order (big-endian)\nstruct BinaryProtocol {\n static let headerSize = 13\n static let senderIDSize = 8\n static let recipientIDSize = 8\n static let signatureSize = 64\n \n struct Flags {\n static let hasRecipient: UInt8 = 0x01\n static let hasSignature: UInt8 = 0x02\n static let isCompressed: UInt8 = 0x04\n }\n \n // Encode BitchatPacket to binary format\n static func encode(_ packet: BitchatPacket) -> Data? {\n var data = Data()\n \n \n // Try to compress payload if beneficial\n var payload = packet.payload\n var originalPayloadSize: UInt16? = nil\n var isCompressed = false\n \n if CompressionUtil.shouldCompress(payload) {\n if let compressedPayload = CompressionUtil.compress(payload) {\n // Store original size for decompression (2 bytes after payload)\n originalPayloadSize = UInt16(payload.count)\n payload = compressedPayload\n isCompressed = true\n \n } else {\n }\n } else {\n }\n \n // Header\n data.append(packet.version)\n data.append(packet.type)\n data.append(packet.ttl)\n \n // Timestamp (8 bytes, big-endian)\n for i in (0..<8).reversed() {\n data.append(UInt8((packet.timestamp >> (i * 8)) & 0xFF))\n }\n \n // Flags\n var flags: UInt8 = 0\n if packet.recipientID != nil {\n flags |= Flags.hasRecipient\n }\n if packet.signature != nil {\n flags |= Flags.hasSignature\n }\n if isCompressed {\n flags |= Flags.isCompressed\n }\n data.append(flags)\n \n // Payload length (2 bytes, big-endian) - includes original size if compressed\n let payloadDataSize = payload.count + (isCompressed ? 2 : 0)\n let payloadLength = UInt16(payloadDataSize)\n \n \n data.append(UInt8((payloadLength >> 8) & 0xFF))\n data.append(UInt8(payloadLength & 0xFF))\n \n // SenderID (exactly 8 bytes)\n let senderBytes = packet.senderID.prefix(senderIDSize)\n data.append(senderBytes)\n if senderBytes.count < senderIDSize {\n data.append(Data(repeating: 0, count: senderIDSize - senderBytes.count))\n }\n \n // RecipientID (if present)\n if let recipientID = packet.recipientID {\n let recipientBytes = recipientID.prefix(recipientIDSize)\n data.append(recipientBytes)\n if recipientBytes.count < recipientIDSize {\n data.append(Data(repeating: 0, count: recipientIDSize - recipientBytes.count))\n }\n }\n \n // Payload (with original size prepended if compressed)\n if isCompressed, let originalSize = originalPayloadSize {\n // Prepend original size (2 bytes, big-endian)\n data.append(UInt8((originalSize >> 8) & 0xFF))\n data.append(UInt8(originalSize & 0xFF))\n }\n data.append(payload)\n \n // Signature (if present)\n if let signature = packet.signature {\n data.append(signature.prefix(signatureSize))\n }\n \n \n // Apply padding to standard block sizes for traffic analysis resistance\n let optimalSize = MessagePadding.optimalBlockSize(for: data.count)\n let paddedData = MessagePadding.pad(data, toSize: optimalSize)\n \n \n return paddedData\n }\n \n // Decode binary data to BitchatPacket\n static func decode(_ data: Data) -> BitchatPacket? {\n // Remove padding first\n let unpaddedData = MessagePadding.unpad(data)\n \n \n guard unpaddedData.count >= headerSize + senderIDSize else { \n return nil \n }\n \n var offset = 0\n \n // Header\n let version = unpaddedData[offset]; offset += 1\n // Check if version is supported\n guard ProtocolVersion.isSupported(version) else { \n // Log unsupported version for debugging\n return nil \n }\n let type = unpaddedData[offset]; offset += 1\n let ttl = unpaddedData[offset]; offset += 1\n \n // Timestamp\n let timestampData = unpaddedData[offset..= expectedSize else { \n return nil \n }\n \n // SenderID\n let senderID = unpaddedData[offset..= 2 else { return nil }\n let originalSizeData = unpaddedData[offset.. Data? {\n var data = Data()\n \n // Message format:\n // - Flags: 1 byte (bit 0: isRelay, bit 1: isPrivate, bit 2: hasOriginalSender, bit 3: hasRecipientNickname, bit 4: hasSenderPeerID, bit 5: hasMentions)\n // - Timestamp: 8 bytes (seconds since epoch)\n // - ID length: 1 byte\n // - ID: variable\n // - Sender length: 1 byte\n // - Sender: variable\n // - Content length: 2 bytes\n // - Content: variable\n // Optional fields based on flags:\n // - Original sender length + data\n // - Recipient nickname length + data\n // - Sender peer ID length + data\n // - Mentions array\n \n var flags: UInt8 = 0\n if isRelay { flags |= 0x01 }\n if isPrivate { flags |= 0x02 }\n if originalSender != nil { flags |= 0x04 }\n if recipientNickname != nil { flags |= 0x08 }\n if senderPeerID != nil { flags |= 0x10 }\n if mentions != nil && !mentions!.isEmpty { flags |= 0x20 }\n \n data.append(flags)\n \n // Timestamp (in milliseconds)\n let timestampMillis = UInt64(timestamp.timeIntervalSince1970 * 1000)\n // Encode as 8 bytes, big-endian\n for i in (0..<8).reversed() {\n data.append(UInt8((timestampMillis >> (i * 8)) & 0xFF))\n }\n \n // ID\n if let idData = id.data(using: .utf8) {\n data.append(UInt8(min(idData.count, 255)))\n data.append(idData.prefix(255))\n } else {\n data.append(0)\n }\n \n // Sender\n if let senderData = sender.data(using: .utf8) {\n data.append(UInt8(min(senderData.count, 255)))\n data.append(senderData.prefix(255))\n } else {\n data.append(0)\n }\n \n // Content\n if let contentData = content.data(using: .utf8) {\n let length = UInt16(min(contentData.count, 65535))\n // Encode length as 2 bytes, big-endian\n data.append(UInt8((length >> 8) & 0xFF))\n data.append(UInt8(length & 0xFF))\n data.append(contentData.prefix(Int(length)))\n } else {\n data.append(contentsOf: [0, 0])\n }\n \n // Optional fields\n if let originalSender = originalSender, let origData = originalSender.data(using: .utf8) {\n data.append(UInt8(min(origData.count, 255)))\n data.append(origData.prefix(255))\n }\n \n if let recipientNickname = recipientNickname, let recipData = recipientNickname.data(using: .utf8) {\n data.append(UInt8(min(recipData.count, 255)))\n data.append(recipData.prefix(255))\n }\n \n if let senderPeerID = senderPeerID, let peerData = senderPeerID.data(using: .utf8) {\n data.append(UInt8(min(peerData.count, 255)))\n data.append(peerData.prefix(255))\n }\n \n // Mentions array\n if let mentions = mentions {\n data.append(UInt8(min(mentions.count, 255))) // Number of mentions\n for mention in mentions.prefix(255) {\n if let mentionData = mention.data(using: .utf8) {\n data.append(UInt8(min(mentionData.count, 255)))\n data.append(mentionData.prefix(255))\n } else {\n data.append(0)\n }\n }\n }\n \n \n return data\n }\n \n static func fromBinaryPayload(_ data: Data) -> BitchatMessage? {\n // Create an immutable copy to prevent threading issues\n let dataCopy = Data(data)\n \n \n guard dataCopy.count >= 13 else { \n return nil \n }\n \n var offset = 0\n \n // Flags\n guard offset < dataCopy.count else { \n return nil \n }\n let flags = dataCopy[offset]; offset += 1\n let isRelay = (flags & 0x01) != 0\n let isPrivate = (flags & 0x02) != 0\n let hasOriginalSender = (flags & 0x04) != 0\n let hasRecipientNickname = (flags & 0x08) != 0\n let hasSenderPeerID = (flags & 0x10) != 0\n let hasMentions = (flags & 0x20) != 0\n \n // Timestamp\n guard offset + 8 <= dataCopy.count else { \n return nil \n }\n let timestampData = dataCopy[offset.. 0 {\n mentions = []\n for _ in 0..\n//\n\nimport Foundation\nimport Combine\nimport CryptoKit\n\nstruct RetryableMessage {\n let id: String\n let originalMessageID: String? \n let originalTimestamp: Date?\n let content: String\n let mentions: [String]?\n let isPrivate: Bool\n let recipientPeerID: String?\n let recipientNickname: String?\n let retryCount: Int\n let maxRetries: Int = 3\n let nextRetryTime: Date\n}\n\nclass MessageRetryService {\n static let shared = MessageRetryService()\n \n private var retryQueue: [RetryableMessage] = []\n private var retryTimer: Timer?\n private let retryInterval: TimeInterval = 2.0 // Retry every 2 seconds for faster sync\n private let maxQueueSize = 50\n \n weak var meshService: BluetoothMeshService?\n \n private init() {\n startRetryTimer()\n }\n \n deinit {\n retryTimer?.invalidate()\n }\n \n private func startRetryTimer() {\n retryTimer = Timer.scheduledTimer(withTimeInterval: retryInterval, repeats: true) { [weak self] _ in\n self?.processRetryQueue()\n }\n }\n \n func addMessageForRetry(\n content: String,\n mentions: [String]? = nil,\n isPrivate: Bool = false,\n recipientPeerID: String? = nil,\n recipientNickname: String? = nil,\n originalMessageID: String? = nil,\n originalTimestamp: Date? = nil\n ) {\n // Don't queue empty or whitespace-only messages\n guard !content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {\n return\n }\n \n // Don't queue if we're at capacity\n guard retryQueue.count < maxQueueSize else {\n return\n }\n \n // Check if this message is already in the queue\n if let messageID = originalMessageID {\n let alreadyQueued = retryQueue.contains { msg in\n msg.originalMessageID == messageID\n }\n if alreadyQueued {\n return // Don't add duplicate\n }\n }\n \n let retryMessage = RetryableMessage(\n id: UUID().uuidString,\n originalMessageID: originalMessageID,\n originalTimestamp: originalTimestamp,\n content: content,\n mentions: mentions,\n isPrivate: isPrivate,\n recipientPeerID: recipientPeerID,\n recipientNickname: recipientNickname,\n retryCount: 0,\n nextRetryTime: Date().addingTimeInterval(retryInterval)\n )\n \n retryQueue.append(retryMessage)\n \n // Sort the queue by original timestamp to maintain message order\n retryQueue.sort { (msg1, msg2) in\n let time1 = msg1.originalTimestamp ?? Date.distantPast\n let time2 = msg2.originalTimestamp ?? Date.distantPast\n return time1 < time2\n }\n }\n \n private func processRetryQueue() {\n guard meshService != nil else { return }\n \n let now = Date()\n var messagesToRetry: [RetryableMessage] = []\n var updatedQueue: [RetryableMessage] = []\n \n for message in retryQueue {\n if message.nextRetryTime <= now {\n messagesToRetry.append(message)\n } else {\n updatedQueue.append(message)\n }\n }\n \n retryQueue = updatedQueue\n \n // Sort messages by original timestamp to maintain order\n messagesToRetry.sort { (msg1, msg2) in\n let time1 = msg1.originalTimestamp ?? Date.distantPast\n let time2 = msg2.originalTimestamp ?? Date.distantPast\n return time1 < time2\n }\n \n // Send messages with delay to maintain order\n for (index, message) in messagesToRetry.enumerated() {\n // Check if we should still retry\n if message.retryCount >= message.maxRetries {\n continue\n }\n \n // Add delay between messages to ensure proper ordering\n let delay = Double(index) * 0.05 // 50ms between messages\n \n DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in\n guard let self = self,\n let meshService = self.meshService else { return }\n \n // Check connectivity before retrying\n let viewModel = meshService.delegate as? ChatViewModel\n let connectedPeers = viewModel?.connectedPeers ?? []\n \n if message.isPrivate {\n // For private messages, check if recipient is connected\n if let recipientID = message.recipientPeerID,\n connectedPeers.contains(recipientID) {\n // Retry private message\n meshService.sendPrivateMessage(\n message.content,\n to: recipientID,\n recipientNickname: message.recipientNickname ?? \"unknown\",\n messageID: message.originalMessageID\n )\n } else {\n // Recipient not connected, keep in queue with updated retry time\n var updatedMessage = message\n updatedMessage = RetryableMessage(\n id: message.id,\n originalMessageID: message.originalMessageID,\n originalTimestamp: message.originalTimestamp,\n content: message.content,\n mentions: message.mentions,\n isPrivate: message.isPrivate,\n recipientPeerID: message.recipientPeerID,\n recipientNickname: message.recipientNickname,\n retryCount: message.retryCount + 1,\n nextRetryTime: Date().addingTimeInterval(self.retryInterval * Double(message.retryCount + 2))\n )\n self.retryQueue.append(updatedMessage)\n }\n } else {\n // Regular message\n if !connectedPeers.isEmpty {\n meshService.sendMessage(\n message.content,\n mentions: message.mentions ?? [],\n to: nil,\n messageID: message.originalMessageID,\n timestamp: message.originalTimestamp\n )\n } else {\n // No peers connected, keep in queue\n var updatedMessage = message\n updatedMessage = RetryableMessage(\n id: message.id,\n originalMessageID: message.originalMessageID,\n originalTimestamp: message.originalTimestamp,\n content: message.content,\n mentions: message.mentions,\n isPrivate: message.isPrivate,\n recipientPeerID: message.recipientPeerID,\n recipientNickname: message.recipientNickname,\n retryCount: message.retryCount + 1,\n nextRetryTime: Date().addingTimeInterval(self.retryInterval * Double(message.retryCount + 2))\n )\n self.retryQueue.append(updatedMessage)\n }\n }\n }\n }\n }\n \n func clearRetryQueue() {\n retryQueue.removeAll()\n }\n \n func getRetryQueueCount() -> Int {\n return retryQueue.count\n }\n}\n"], ["/bitchat/bitchat/Services/KeychainManager.swift", "//\n// KeychainManager.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport Security\nimport os.log\n\nclass KeychainManager {\n static let shared = KeychainManager()\n \n // Use consistent service name for all keychain items\n private let service = \"chat.bitchat\"\n private let appGroup = \"group.chat.bitchat\"\n \n private init() {\n // Clean up legacy keychain items on first run\n cleanupLegacyKeychainItems()\n }\n \n private func cleanupLegacyKeychainItems() {\n // Check if we've already done cleanup\n let cleanupKey = \"bitchat.keychain.cleanup.v2\"\n if UserDefaults.standard.bool(forKey: cleanupKey) {\n return\n }\n \n \n // List of old service names to migrate from\n let legacyServices = [\n \"com.bitchat.passwords\",\n \"com.bitchat.deviceidentity\",\n \"com.bitchat.noise.identity\",\n \"chat.bitchat.passwords\",\n \"bitchat.keychain\"\n ]\n \n var migratedItems = 0\n \n // Try to migrate identity keys\n for oldService in legacyServices {\n // Check for noise identity key\n let query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: oldService,\n kSecAttrAccount as String: \"identity_noiseStaticKey\",\n kSecReturnData as String: true\n ]\n \n var result: AnyObject?\n let status = SecItemCopyMatching(query as CFDictionary, &result)\n \n if status == errSecSuccess, let data = result as? Data {\n // Save to new service\n if saveIdentityKey(data, forKey: \"noiseStaticKey\") {\n migratedItems += 1\n SecureLogger.logKeyOperation(\"migrate\", keyType: \"noiseStaticKey\", success: true)\n }\n // Delete from old service\n let deleteQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: oldService,\n kSecAttrAccount as String: \"identity_noiseStaticKey\"\n ]\n SecItemDelete(deleteQuery as CFDictionary)\n }\n }\n \n // Clean up all other legacy items\n for oldService in legacyServices {\n let deleteQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: oldService\n ]\n \n SecItemDelete(deleteQuery as CFDictionary)\n }\n \n \n // Mark cleanup as done\n UserDefaults.standard.set(true, forKey: cleanupKey)\n }\n \n \n private func isSandboxed() -> Bool {\n #if os(macOS)\n let environment = ProcessInfo.processInfo.environment\n return environment[\"APP_SANDBOX_CONTAINER_ID\"] != nil\n #else\n return false\n #endif\n }\n \n // MARK: - Identity Keys\n \n func saveIdentityKey(_ keyData: Data, forKey key: String) -> Bool {\n let fullKey = \"identity_\\(key)\"\n let result = saveData(keyData, forKey: fullKey)\n SecureLogger.logKeyOperation(\"save\", keyType: key, success: result)\n return result\n }\n \n func getIdentityKey(forKey key: String) -> Data? {\n let fullKey = \"identity_\\(key)\"\n return retrieveData(forKey: fullKey)\n }\n \n func deleteIdentityKey(forKey key: String) -> Bool {\n let result = delete(forKey: \"identity_\\(key)\")\n SecureLogger.logKeyOperation(\"delete\", keyType: key, success: result)\n return result\n }\n \n // MARK: - Generic Operations\n \n private func save(_ value: String, forKey key: String) -> Bool {\n guard let data = value.data(using: .utf8) else { return false }\n return saveData(data, forKey: key)\n }\n \n private func saveData(_ data: Data, forKey key: String) -> Bool {\n // Delete any existing item first to ensure clean state\n _ = delete(forKey: key)\n \n // Build query with all necessary attributes for sandboxed apps\n var query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrAccount as String: key,\n kSecValueData as String: data,\n kSecAttrService as String: service,\n // Important for sandboxed apps: make it accessible when unlocked\n kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlocked\n ]\n \n // Add a label for easier debugging\n query[kSecAttrLabel as String] = \"bitchat-\\(key)\"\n \n // For sandboxed apps, use the app group for sharing between app instances\n if isSandboxed() {\n query[kSecAttrAccessGroup as String] = appGroup\n }\n \n // For sandboxed macOS apps, we need to ensure the item is NOT synchronized\n #if os(macOS)\n query[kSecAttrSynchronizable as String] = false\n #endif\n \n let status = SecItemAdd(query as CFDictionary, nil)\n \n if status == errSecSuccess {\n return true\n } else if status == -34018 {\n SecureLogger.logError(NSError(domain: \"Keychain\", code: -34018), context: \"Missing keychain entitlement\", category: SecureLogger.keychain)\n } else if status != errSecDuplicateItem {\n SecureLogger.logError(NSError(domain: \"Keychain\", code: Int(status)), context: \"Error saving to keychain\", category: SecureLogger.keychain)\n }\n \n return false\n }\n \n private func retrieve(forKey key: String) -> String? {\n guard let data = retrieveData(forKey: key) else { return nil }\n return String(data: data, encoding: .utf8)\n }\n \n private func retrieveData(forKey key: String) -> Data? {\n var query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrAccount as String: key,\n kSecAttrService as String: service,\n kSecReturnData as String: true,\n kSecMatchLimit as String: kSecMatchLimitOne\n ]\n \n // For sandboxed apps, use the app group\n if isSandboxed() {\n query[kSecAttrAccessGroup as String] = appGroup\n }\n \n var result: AnyObject?\n let status = SecItemCopyMatching(query as CFDictionary, &result)\n \n if status == errSecSuccess {\n return result as? Data\n } else if status == -34018 {\n SecureLogger.logError(NSError(domain: \"Keychain\", code: -34018), context: \"Missing keychain entitlement\", category: SecureLogger.keychain)\n }\n \n return nil\n }\n \n private func delete(forKey key: String) -> Bool {\n // Build basic query\n var query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrAccount as String: key,\n kSecAttrService as String: service\n ]\n \n // For sandboxed apps, use the app group\n if isSandboxed() {\n query[kSecAttrAccessGroup as String] = appGroup\n }\n \n let status = SecItemDelete(query as CFDictionary)\n return status == errSecSuccess || status == errSecItemNotFound\n }\n \n // MARK: - Cleanup\n \n func deleteAllPasswords() -> Bool {\n var query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword\n ]\n \n // Add service if not empty\n if !service.isEmpty {\n query[kSecAttrService as String] = service\n }\n \n let status = SecItemDelete(query as CFDictionary)\n return status == errSecSuccess || status == errSecItemNotFound\n }\n \n // Force cleanup to run again (for development/testing)\n func resetCleanupFlag() {\n UserDefaults.standard.removeObject(forKey: \"bitchat.keychain.cleanup.v2\")\n }\n \n \n // Delete ALL keychain data for panic mode\n func deleteAllKeychainData() -> Bool {\n SecureLogger.log(\"Panic mode - deleting all keychain data\", category: SecureLogger.security, level: .warning)\n \n var totalDeleted = 0\n \n // Search without service restriction to catch all items\n let searchQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecMatchLimit as String: kSecMatchLimitAll,\n kSecReturnAttributes as String: true\n ]\n \n var result: AnyObject?\n let searchStatus = SecItemCopyMatching(searchQuery as CFDictionary, &result)\n \n if searchStatus == errSecSuccess, let items = result as? [[String: Any]] {\n for item in items {\n var shouldDelete = false\n let account = item[kSecAttrAccount as String] as? String ?? \"\"\n let service = item[kSecAttrService as String] as? String ?? \"\"\n \n // ONLY delete if service name contains \"bitchat\"\n // This is the safest approach - we only touch items we know are ours\n if service.lowercased().contains(\"bitchat\") {\n shouldDelete = true\n }\n \n if shouldDelete {\n // Build delete query with all available attributes for precise deletion\n var deleteQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword\n ]\n \n if !account.isEmpty {\n deleteQuery[kSecAttrAccount as String] = account\n }\n if !service.isEmpty {\n deleteQuery[kSecAttrService as String] = service\n }\n \n // Add access group if present\n if let accessGroup = item[kSecAttrAccessGroup as String] as? String,\n !accessGroup.isEmpty && accessGroup != \"test\" {\n deleteQuery[kSecAttrAccessGroup as String] = accessGroup\n }\n \n let deleteStatus = SecItemDelete(deleteQuery as CFDictionary)\n if deleteStatus == errSecSuccess {\n totalDeleted += 1\n SecureLogger.log(\"Deleted keychain item: \\(account) from \\(service)\", category: SecureLogger.keychain, level: .info)\n }\n }\n }\n }\n \n // Also try to delete by known service names (in case we missed any)\n let knownServices = [\n \"chat.bitchat\",\n \"com.bitchat.passwords\",\n \"com.bitchat.deviceidentity\", \n \"com.bitchat.noise.identity\",\n \"chat.bitchat.passwords\",\n \"bitchat.keychain\",\n \"bitchat\",\n \"com.bitchat\"\n ]\n \n for serviceName in knownServices {\n let query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: serviceName\n ]\n \n let status = SecItemDelete(query as CFDictionary)\n if status == errSecSuccess {\n totalDeleted += 1\n }\n }\n \n SecureLogger.log(\"Panic mode cleanup completed. Total items deleted: \\(totalDeleted)\", category: SecureLogger.keychain, level: .warning)\n \n return totalDeleted > 0\n }\n \n // MARK: - Debug\n \n func verifyIdentityKeyExists() -> Bool {\n let key = \"identity_noiseStaticKey\"\n return retrieveData(forKey: key) != nil\n }\n \n // Aggressive cleanup for legacy items - can be called manually\n func aggressiveCleanupLegacyItems() -> Int {\n var deletedCount = 0\n \n // List of KNOWN bitchat service names from our development history\n let knownBitchatServices = [\n \"com.bitchat.passwords\",\n \"com.bitchat.deviceidentity\",\n \"com.bitchat.noise.identity\",\n \"chat.bitchat.passwords\",\n \"bitchat.keychain\",\n \"Bitchat\",\n \"BitChat\"\n ]\n \n // First, delete all items from known legacy services\n for legacyService in knownBitchatServices {\n let deleteQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: legacyService\n ]\n \n let status = SecItemDelete(deleteQuery as CFDictionary)\n if status == errSecSuccess {\n deletedCount += 1\n }\n }\n \n // Now search for items that have our specific account patterns with bitchat service names\n let searchQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecMatchLimit as String: kSecMatchLimitAll,\n kSecReturnAttributes as String: true\n ]\n \n var result: AnyObject?\n let status = SecItemCopyMatching(searchQuery as CFDictionary, &result)\n \n if status == errSecSuccess, let items = result as? [[String: Any]] {\n for item in items {\n let account = item[kSecAttrAccount as String] as? String ?? \"\"\n let service = item[kSecAttrService as String] as? String ?? \"\"\n \n // ONLY delete if service name contains \"bitchat\" somewhere\n // This ensures we never touch other apps' keychain items\n var shouldDelete = false\n \n // Check if service contains \"bitchat\" (case insensitive) but NOT our current service\n let serviceLower = service.lowercased()\n if service != self.service && serviceLower.contains(\"bitchat\") {\n shouldDelete = true\n }\n \n if shouldDelete {\n // Build precise delete query\n let deleteQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: service,\n kSecAttrAccount as String: account\n ]\n \n let deleteStatus = SecItemDelete(deleteQuery as CFDictionary)\n if deleteStatus == errSecSuccess {\n deletedCount += 1\n }\n }\n }\n }\n \n return deletedCount\n }\n}"], ["/bitchat/bitchat/Noise/NoiseHandshakeCoordinator.swift", "//\n// NoiseHandshakeCoordinator.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\n\n/// Coordinates Noise handshakes to prevent race conditions and ensure reliable encryption establishment\nclass NoiseHandshakeCoordinator {\n \n // MARK: - Handshake State\n \n enum HandshakeState: Equatable {\n case idle\n case waitingToInitiate(since: Date)\n case initiating(attempt: Int, lastAttempt: Date)\n case responding(since: Date)\n case waitingForResponse(messagesSent: [Data], timeout: Date)\n case established(since: Date)\n case failed(reason: String, canRetry: Bool, lastAttempt: Date)\n \n var isActive: Bool {\n switch self {\n case .idle, .established, .failed:\n return false\n default:\n return true\n }\n }\n }\n \n // MARK: - Properties\n \n private var handshakeStates: [String: HandshakeState] = [:]\n private var handshakeQueue = DispatchQueue(label: \"chat.bitchat.noise.handshake\", attributes: .concurrent)\n \n // Configuration\n private let maxHandshakeAttempts = 3\n private let handshakeTimeout: TimeInterval = 10.0\n private let retryDelay: TimeInterval = 2.0\n private let minTimeBetweenHandshakes: TimeInterval = 1.0 // Reduced from 5.0 for faster recovery\n \n // Track handshake messages to detect duplicates\n private var processedHandshakeMessages: Set = []\n private let messageHistoryLimit = 100\n \n // MARK: - Role Determination\n \n /// Deterministically determine who should initiate the handshake\n /// Lower peer ID becomes the initiator to prevent simultaneous attempts\n func determineHandshakeRole(myPeerID: String, remotePeerID: String) -> NoiseRole {\n // Use simple string comparison for deterministic ordering\n return myPeerID < remotePeerID ? .initiator : .responder\n }\n \n /// Check if we should initiate handshake with a peer\n func shouldInitiateHandshake(myPeerID: String, remotePeerID: String, forceIfStale: Bool = false) -> Bool {\n return handshakeQueue.sync {\n // Check if we're already in an active handshake\n if let state = handshakeStates[remotePeerID], state.isActive {\n // Check if the handshake is stale and we should force a new one\n if forceIfStale {\n switch state {\n case .initiating(_, let lastAttempt):\n if Date().timeIntervalSince(lastAttempt) > handshakeTimeout {\n SecureLogger.log(\"Forcing new handshake with \\(remotePeerID) - previous stuck in initiating\", \n category: SecureLogger.handshake, level: .warning)\n return true\n }\n default:\n break\n }\n }\n \n SecureLogger.log(\"Already in active handshake with \\(remotePeerID), state: \\(state)\", \n category: SecureLogger.handshake, level: .debug)\n return false\n }\n \n // Check role\n let role = determineHandshakeRole(myPeerID: myPeerID, remotePeerID: remotePeerID)\n if role != .initiator {\n SecureLogger.log(\"Not initiator for handshake with \\(remotePeerID) (my: \\(myPeerID), their: \\(remotePeerID))\", \n category: SecureLogger.handshake, level: .debug)\n return false\n }\n \n // Check if we've failed recently and can't retry yet\n if case .failed(_, let canRetry, let lastAttempt) = handshakeStates[remotePeerID] {\n if !canRetry {\n return false\n }\n if Date().timeIntervalSince(lastAttempt) < retryDelay {\n return false\n }\n }\n \n return true\n }\n }\n \n /// Record that we're initiating a handshake\n func recordHandshakeInitiation(peerID: String) {\n handshakeQueue.async(flags: .barrier) {\n let attempt = self.getCurrentAttempt(for: peerID) + 1\n self.handshakeStates[peerID] = .initiating(attempt: attempt, lastAttempt: Date())\n SecureLogger.log(\"Recording handshake initiation with \\(peerID), attempt \\(attempt)\", \n category: SecureLogger.handshake, level: .info)\n }\n }\n \n /// Record that we're responding to a handshake\n func recordHandshakeResponse(peerID: String) {\n handshakeQueue.async(flags: .barrier) {\n self.handshakeStates[peerID] = .responding(since: Date())\n SecureLogger.log(\"Recording handshake response to \\(peerID)\", \n category: SecureLogger.handshake, level: .info)\n }\n }\n \n /// Record successful handshake completion\n func recordHandshakeSuccess(peerID: String) {\n handshakeQueue.async(flags: .barrier) {\n self.handshakeStates[peerID] = .established(since: Date())\n SecureLogger.log(\"Handshake successfully established with \\(peerID)\", \n category: SecureLogger.handshake, level: .info)\n }\n }\n \n /// Record handshake failure\n func recordHandshakeFailure(peerID: String, reason: String) {\n handshakeQueue.async(flags: .barrier) {\n let attempts = self.getCurrentAttempt(for: peerID)\n let canRetry = attempts < self.maxHandshakeAttempts\n self.handshakeStates[peerID] = .failed(reason: reason, canRetry: canRetry, lastAttempt: Date())\n SecureLogger.log(\"Handshake failed with \\(peerID): \\(reason), canRetry: \\(canRetry)\", \n category: SecureLogger.handshake, level: .warning)\n }\n }\n \n /// Check if we should accept an incoming handshake initiation\n func shouldAcceptHandshakeInitiation(myPeerID: String, remotePeerID: String) -> Bool {\n return handshakeQueue.sync {\n // If we're already established, reject new handshakes\n if case .established = handshakeStates[remotePeerID] {\n SecureLogger.log(\"Rejecting handshake from \\(remotePeerID) - already established\", \n category: SecureLogger.handshake, level: .debug)\n return false\n }\n \n let role = determineHandshakeRole(myPeerID: myPeerID, remotePeerID: remotePeerID)\n \n // If we're the initiator and already initiating, this is a race condition\n if role == .initiator {\n if case .initiating = handshakeStates[remotePeerID] {\n // They shouldn't be initiating, but accept it to recover from race condition\n SecureLogger.log(\"Accepting handshake from \\(remotePeerID) despite being initiator (race condition recovery)\", \n category: SecureLogger.handshake, level: .warning)\n return true\n }\n }\n \n // If we're the responder, we should accept\n return true\n }\n }\n \n /// Check if this is a duplicate handshake message\n func isDuplicateHandshakeMessage(_ data: Data) -> Bool {\n return handshakeQueue.sync {\n if processedHandshakeMessages.contains(data) {\n return true\n }\n \n // Add to processed messages with size limit\n if processedHandshakeMessages.count >= messageHistoryLimit {\n processedHandshakeMessages.removeAll()\n }\n processedHandshakeMessages.insert(data)\n return false\n }\n }\n \n /// Get time to wait before next handshake attempt\n func getRetryDelay(for peerID: String) -> TimeInterval? {\n return handshakeQueue.sync {\n guard let state = handshakeStates[peerID] else { return nil }\n \n switch state {\n case .failed(_, let canRetry, let lastAttempt):\n if !canRetry { return nil }\n let timeSinceFailure = Date().timeIntervalSince(lastAttempt)\n if timeSinceFailure >= retryDelay {\n return 0\n }\n return retryDelay - timeSinceFailure\n \n case .initiating(_, let lastAttempt):\n let timeSinceAttempt = Date().timeIntervalSince(lastAttempt)\n if timeSinceAttempt >= minTimeBetweenHandshakes {\n return 0\n }\n return minTimeBetweenHandshakes - timeSinceAttempt\n \n default:\n return nil\n }\n }\n }\n \n /// Reset handshake state for a peer\n func resetHandshakeState(for peerID: String) {\n handshakeQueue.async(flags: .barrier) {\n self.handshakeStates.removeValue(forKey: peerID)\n SecureLogger.log(\"Reset handshake state for \\(peerID)\", \n category: SecureLogger.handshake, level: .debug)\n }\n }\n \n /// Clean up stale handshake states\n func cleanupStaleHandshakes(staleTimeout: TimeInterval = 30.0) -> [String] {\n return handshakeQueue.sync {\n let now = Date()\n var stalePeerIDs: [String] = []\n \n for (peerID, state) in handshakeStates {\n var isStale = false\n \n switch state {\n case .initiating(_, let lastAttempt):\n if now.timeIntervalSince(lastAttempt) > staleTimeout {\n isStale = true\n }\n case .responding(let since):\n if now.timeIntervalSince(since) > staleTimeout {\n isStale = true\n }\n case .waitingForResponse(_, let timeout):\n if now > timeout {\n isStale = true\n }\n default:\n break\n }\n \n if isStale {\n stalePeerIDs.append(peerID)\n SecureLogger.log(\"Found stale handshake state for \\(peerID): \\(state)\", \n category: SecureLogger.handshake, level: .warning)\n }\n }\n \n // Clean up stale states\n for peerID in stalePeerIDs {\n handshakeStates.removeValue(forKey: peerID)\n }\n \n return stalePeerIDs\n }\n }\n \n /// Get current handshake state\n func getHandshakeState(for peerID: String) -> HandshakeState {\n return handshakeQueue.sync {\n return handshakeStates[peerID] ?? .idle\n }\n }\n \n /// Get current retry count for a peer\n func getRetryCount(for peerID: String) -> Int {\n return handshakeQueue.sync {\n switch handshakeStates[peerID] {\n case .initiating(let attempt, _):\n return attempt - 1 // Attempts start at 1, retries start at 0\n default:\n return 0\n }\n }\n }\n \n /// Increment retry count for a peer\n func incrementRetryCount(for peerID: String) {\n handshakeQueue.async(flags: .barrier) {\n let currentAttempt = self.getCurrentAttempt(for: peerID)\n self.handshakeStates[peerID] = .initiating(attempt: currentAttempt + 1, lastAttempt: Date())\n }\n }\n \n // MARK: - Private Helpers\n \n private func getCurrentAttempt(for peerID: String) -> Int {\n switch handshakeStates[peerID] {\n case .initiating(let attempt, _):\n return attempt\n case .failed(_, _, _):\n // Count previous attempts\n return 1 // Simplified for now\n default:\n return 0\n }\n }\n \n /// Log current handshake states for debugging\n func logHandshakeStates() {\n handshakeQueue.sync {\n SecureLogger.log(\"=== Handshake States ===\", category: SecureLogger.handshake, level: .debug)\n for (peerID, state) in handshakeStates {\n let stateDesc: String\n switch state {\n case .idle:\n stateDesc = \"idle\"\n case .waitingToInitiate(let since):\n stateDesc = \"waiting to initiate (since \\(since))\"\n case .initiating(let attempt, let lastAttempt):\n stateDesc = \"initiating (attempt \\(attempt), last: \\(lastAttempt))\"\n case .responding(let since):\n stateDesc = \"responding (since: \\(since))\"\n case .waitingForResponse(let messages, let timeout):\n stateDesc = \"waiting for response (\\(messages.count) messages, timeout: \\(timeout))\"\n case .established(let since):\n stateDesc = \"established (since \\(since))\"\n case .failed(let reason, let canRetry, let lastAttempt):\n stateDesc = \"failed: \\(reason) (canRetry: \\(canRetry), last: \\(lastAttempt))\"\n }\n SecureLogger.log(\" \\(peerID): \\(stateDesc)\", category: SecureLogger.handshake, level: .debug)\n }\n SecureLogger.log(\"========================\", category: SecureLogger.handshake, level: .debug)\n }\n }\n \n /// Clear all handshake states - used during panic mode\n func clearAllHandshakeStates() {\n handshakeQueue.async(flags: .barrier) {\n SecureLogger.log(\"Clearing all handshake states for panic mode\", category: SecureLogger.handshake, level: .warning)\n self.handshakeStates.removeAll()\n self.processedHandshakeMessages.removeAll()\n }\n }\n}"], ["/bitchat/bitchat/Identity/IdentityModels.swift", "//\n// IdentityModels.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # IdentityModels\n///\n/// Defines BitChat's innovative three-layer identity model that balances\n/// privacy, security, and usability in a decentralized mesh network.\n///\n/// ## Overview\n/// BitChat's identity system separates concerns across three distinct layers:\n/// 1. **Ephemeral Identity**: Short-lived, rotatable peer IDs for privacy\n/// 2. **Cryptographic Identity**: Long-term Noise static keys for security\n/// 3. **Social Identity**: User-assigned names and trust relationships\n///\n/// This separation allows users to maintain stable cryptographic identities\n/// while frequently rotating their network identifiers for privacy.\n///\n/// ## Three-Layer Architecture\n///\n/// ### Layer 1: Ephemeral Identity\n/// - Random 8-byte peer IDs that rotate periodically\n/// - Provides network-level privacy and prevents tracking\n/// - Changes don't affect cryptographic relationships\n/// - Includes handshake state tracking\n///\n/// ### Layer 2: Cryptographic Identity\n/// - Based on Noise Protocol static key pairs\n/// - Fingerprint derived from SHA256 of public key\n/// - Enables end-to-end encryption and authentication\n/// - Persists across peer ID rotations\n///\n/// ### Layer 3: Social Identity\n/// - User-assigned names (petnames) for contacts\n/// - Trust levels from unknown to verified\n/// - Favorite/blocked status\n/// - Personal notes and metadata\n///\n/// ## Privacy Design\n/// The model is designed with privacy-first principles:\n/// - No mandatory persistent storage\n/// - Optional identity caching with user consent\n/// - Ephemeral IDs prevent long-term tracking\n/// - Social mappings stored locally only\n///\n/// ## Trust Model\n/// Four levels of trust:\n/// 1. **Unknown**: New or unverified peers\n/// 2. **Casual**: Basic interaction history\n/// 3. **Trusted**: User has explicitly trusted\n/// 4. **Verified**: Cryptographic verification completed\n///\n/// ## Identity Resolution\n/// When a peer rotates their ephemeral ID:\n/// 1. Cryptographic handshake reveals their fingerprint\n/// 2. System looks up social identity by fingerprint\n/// 3. UI seamlessly maintains user relationships\n/// 4. Historical messages remain properly attributed\n///\n/// ## Conflict Resolution\n/// Handles edge cases like:\n/// - Multiple peers claiming same nickname\n/// - Nickname changes and conflicts\n/// - Identity rotation during active chats\n/// - Network partitions and rejoins\n///\n/// ## Usage Example\n/// ```swift\n/// // When peer connects with new ID\n/// let ephemeral = EphemeralIdentity(peerID: \"abc123\", ...)\n/// // After handshake\n/// let crypto = CryptographicIdentity(fingerprint: \"sha256...\", ...)\n/// // User assigns name\n/// let social = SocialIdentity(localPetname: \"Alice\", ...)\n/// ```\n///\n\nimport Foundation\n\n// MARK: - Three-Layer Identity Model\n\n/// Represents the ephemeral layer of identity - short-lived peer IDs that provide network privacy.\n/// These IDs rotate periodically to prevent tracking while maintaining cryptographic relationships.\nstruct EphemeralIdentity {\n let peerID: String // 8 random bytes\n let sessionStart: Date\n var handshakeState: HandshakeState\n}\n\nenum HandshakeState {\n case none\n case initiated\n case inProgress\n case completed(fingerprint: String)\n case failed(reason: String)\n}\n\n/// Represents the cryptographic layer of identity - the stable Noise Protocol static key pair.\n/// This identity persists across ephemeral ID rotations and enables secure communication.\n/// The fingerprint serves as the permanent identifier for a peer's cryptographic identity.\nstruct CryptographicIdentity: Codable {\n let fingerprint: String // SHA256 of public key\n let publicKey: Data // Noise static public key\n let firstSeen: Date\n let lastHandshake: Date?\n}\n\n/// Represents the social layer of identity - user-assigned names and trust relationships.\n/// This layer provides human-friendly identification and relationship management.\n/// All data in this layer is local-only and never transmitted over the network.\nstruct SocialIdentity: Codable {\n let fingerprint: String\n var localPetname: String? // User's name for this peer\n var claimedNickname: String // What peer calls themselves\n var trustLevel: TrustLevel\n var isFavorite: Bool\n var isBlocked: Bool\n var notes: String?\n}\n\nenum TrustLevel: String, Codable {\n case unknown = \"unknown\"\n case casual = \"casual\"\n case trusted = \"trusted\"\n case verified = \"verified\"\n}\n\n// MARK: - Identity Cache\n\n/// Persistent storage for identity mappings and relationships.\n/// Provides efficient lookup between fingerprints, nicknames, and social identities.\n/// Storage is optional and controlled by user privacy settings.\nstruct IdentityCache: Codable {\n // Fingerprint -> Social mapping\n var socialIdentities: [String: SocialIdentity] = [:]\n \n // Nickname -> [Fingerprints] reverse index\n // Multiple fingerprints can claim same nickname\n var nicknameIndex: [String: Set] = [:]\n \n // Verified fingerprints (cryptographic proof)\n var verifiedFingerprints: Set = []\n \n // Last interaction timestamps (privacy: optional)\n var lastInteractions: [String: Date] = [:] \n \n // Schema version for future migrations\n var version: Int = 1\n}\n\n// MARK: - Identity Resolution\n\nenum IdentityHint {\n case unknown\n case likelyKnown(fingerprint: String)\n case ambiguous(candidates: Set)\n case verified(fingerprint: String)\n}\n\n// MARK: - Pending Actions\n\nstruct PendingActions {\n var toggleFavorite: Bool?\n var setTrustLevel: TrustLevel?\n var setPetname: String?\n}\n\n// MARK: - Privacy Settings\n\nstruct PrivacySettings: Codable {\n // Level 1: Maximum privacy (default)\n var persistIdentityCache = false\n var showLastSeen = false\n \n // Level 2: Convenience\n var autoAcceptKnownFingerprints = false\n var rememberNicknameHistory = false\n \n // Level 3: Social\n var shareTrustNetworkHints = false // \"3 mutual contacts trust this person\"\n}\n\n// MARK: - Conflict Resolution\n\n/// Strategies for resolving identity conflicts in the decentralized network.\n/// Handles cases where multiple peers claim the same nickname or when\n/// identity mappings become ambiguous due to network partitions.\nenum ConflictResolution {\n case acceptNew(petname: String) // \"John (2)\"\n case rejectNew\n case blockFingerprint(String)\n case alertUser(message: String)\n}\n\n// MARK: - UI State\n\nstruct PeerUIState {\n let peerID: String\n let nickname: String\n var identityState: IdentityState\n var connectionQuality: ConnectionQuality\n \n enum IdentityState {\n case unknown // Gray - No identity info\n case unverifiedKnown(String) // Blue - Handshake done, matches cache\n case verified(String) // Green - Cryptographically verified\n case conflict(String, String) // Red - Nickname doesn't match fingerprint\n case pending // Yellow - Handshake in progress\n }\n}\n\nenum ConnectionQuality {\n case excellent\n case good\n case poor\n case disconnected\n}\n\n// MARK: - Migration Support\n// Removed LegacyFavorite - no longer needed"], ["/bitchat/bitchat/Services/DeliveryTracker.swift", "//\n// DeliveryTracker.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport Combine\n\nclass DeliveryTracker {\n static let shared = DeliveryTracker()\n \n // Track pending deliveries\n private var pendingDeliveries: [String: PendingDelivery] = [:]\n private let pendingLock = NSLock()\n \n // Track received ACKs to prevent duplicates\n private var receivedAckIDs = Set()\n private var sentAckIDs = Set()\n \n // Timeout configuration\n private let privateMessageTimeout: TimeInterval = 120 // 2 minutes\n private let roomMessageTimeout: TimeInterval = 180 // 3 minutes\n private let favoriteTimeout: TimeInterval = 600 // 10 minutes for favorites\n \n // Retry configuration\n private let maxRetries = 3\n private let retryDelay: TimeInterval = 5 // Base retry delay\n \n // Publishers for UI updates\n let deliveryStatusUpdated = PassthroughSubject<(messageID: String, status: DeliveryStatus), Never>()\n \n // Cleanup timer\n private var cleanupTimer: Timer?\n \n struct PendingDelivery {\n let messageID: String\n let sentAt: Date\n let recipientID: String\n let recipientNickname: String\n let retryCount: Int\n let isFavorite: Bool\n var timeoutTimer: Timer?\n \n var isTimedOut: Bool {\n let timeout: TimeInterval = isFavorite ? 300 : 30\n return Date().timeIntervalSince(sentAt) > timeout\n }\n \n var shouldRetry: Bool {\n return retryCount < 3 && isFavorite\n }\n }\n \n private init() {\n startCleanupTimer()\n }\n \n deinit {\n cleanupTimer?.invalidate()\n }\n \n // MARK: - Public Methods\n \n func trackMessage(_ message: BitchatMessage, recipientID: String, recipientNickname: String, isFavorite: Bool = false, expectedRecipients: Int = 1) {\n // Only track private messages\n guard message.isPrivate else { return }\n \n SecureLogger.log(\"Tracking message \\(message.id) - private: \\(message.isPrivate), recipient: \\(recipientNickname)\", category: SecureLogger.session, level: .info)\n \n \n let delivery = PendingDelivery(\n messageID: message.id,\n sentAt: Date(),\n recipientID: recipientID,\n recipientNickname: recipientNickname,\n retryCount: 0,\n isFavorite: isFavorite,\n timeoutTimer: nil\n )\n \n // Store the delivery with lock\n pendingLock.lock()\n pendingDeliveries[message.id] = delivery\n pendingLock.unlock()\n \n // Update status to sent (only if not already delivered)\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in\n guard let self = self else { return }\n \n self.pendingLock.lock()\n let stillPending = self.pendingDeliveries[message.id] != nil\n self.pendingLock.unlock()\n \n // Only update to sent if still pending (not already delivered)\n if stillPending {\n SecureLogger.log(\"Updating message \\(message.id) to sent status (still pending)\", category: SecureLogger.session, level: .debug)\n self.updateDeliveryStatus(message.id, status: .sent)\n } else {\n SecureLogger.log(\"Skipping sent status update for \\(message.id) - already delivered\", category: SecureLogger.session, level: .debug)\n }\n }\n \n // Schedule timeout (outside of lock)\n scheduleTimeout(for: message.id)\n }\n \n func processDeliveryAck(_ ack: DeliveryAck) {\n pendingLock.lock()\n defer { pendingLock.unlock() }\n \n SecureLogger.log(\"Processing delivery ACK for message \\(ack.originalMessageID) from \\(ack.recipientNickname)\", category: SecureLogger.session, level: .info)\n \n // Prevent duplicate ACK processing\n guard !receivedAckIDs.contains(ack.ackID) else {\n SecureLogger.log(\"Duplicate ACK \\(ack.ackID) - ignoring\", category: SecureLogger.session, level: .warning)\n return\n }\n receivedAckIDs.insert(ack.ackID)\n \n // Find the pending delivery\n guard let delivery = pendingDeliveries[ack.originalMessageID] else {\n // Message might have already been delivered or timed out\n SecureLogger.log(\"No pending delivery found for message \\(ack.originalMessageID)\", category: SecureLogger.session, level: .warning)\n return\n }\n \n // Cancel timeout timer\n delivery.timeoutTimer?.invalidate()\n \n // Direct message - mark as delivered\n SecureLogger.log(\"Marking private message \\(ack.originalMessageID) as delivered to \\(ack.recipientNickname)\", category: SecureLogger.session, level: .info)\n updateDeliveryStatus(ack.originalMessageID, status: .delivered(to: ack.recipientNickname, at: Date()))\n pendingDeliveries.removeValue(forKey: ack.originalMessageID)\n }\n \n func generateAck(for message: BitchatMessage, myPeerID: String, myNickname: String, hopCount: UInt8) -> DeliveryAck? {\n // Don't ACK our own messages\n guard message.senderPeerID != myPeerID else { \n return nil \n }\n \n // Only ACK private messages\n guard message.isPrivate else { \n return nil \n }\n \n // Don't ACK if we've already sent an ACK for this message\n guard !sentAckIDs.contains(message.id) else { \n return nil \n }\n sentAckIDs.insert(message.id)\n \n \n return DeliveryAck(\n originalMessageID: message.id,\n recipientID: myPeerID,\n recipientNickname: myNickname,\n hopCount: hopCount\n )\n }\n \n func clearDeliveryStatus(for messageID: String) {\n pendingLock.lock()\n defer { pendingLock.unlock() }\n \n if let delivery = pendingDeliveries[messageID] {\n delivery.timeoutTimer?.invalidate()\n }\n pendingDeliveries.removeValue(forKey: messageID)\n }\n \n // MARK: - Private Methods\n \n private func updateDeliveryStatus(_ messageID: String, status: DeliveryStatus) {\n SecureLogger.log(\"Updating delivery status for message \\(messageID): \\(status)\", category: SecureLogger.session, level: .debug)\n DispatchQueue.main.async { [weak self] in\n self?.deliveryStatusUpdated.send((messageID: messageID, status: status))\n }\n }\n \n private func scheduleTimeout(for messageID: String) {\n // Get delivery info with lock\n pendingLock.lock()\n guard let delivery = pendingDeliveries[messageID] else {\n pendingLock.unlock()\n return\n }\n let isFavorite = delivery.isFavorite\n pendingLock.unlock()\n \n let timeout = isFavorite ? favoriteTimeout : privateMessageTimeout\n \n let timer = Timer.scheduledTimer(withTimeInterval: timeout, repeats: false) { [weak self] _ in\n self?.handleTimeout(messageID: messageID)\n }\n \n pendingLock.lock()\n if var updatedDelivery = pendingDeliveries[messageID] {\n updatedDelivery.timeoutTimer = timer\n pendingDeliveries[messageID] = updatedDelivery\n }\n pendingLock.unlock()\n }\n \n private func handleTimeout(messageID: String) {\n pendingLock.lock()\n guard let delivery = pendingDeliveries[messageID] else {\n pendingLock.unlock()\n return\n }\n \n let shouldRetry = delivery.shouldRetry\n \n if shouldRetry {\n pendingLock.unlock()\n // Retry for favorites (outside of lock)\n retryDelivery(messageID: messageID)\n } else {\n // Mark as failed\n let reason = \"Message not delivered\"\n pendingDeliveries.removeValue(forKey: messageID)\n pendingLock.unlock()\n updateDeliveryStatus(messageID, status: .failed(reason: reason))\n }\n }\n \n private func retryDelivery(messageID: String) {\n pendingLock.lock()\n guard let delivery = pendingDeliveries[messageID] else {\n pendingLock.unlock()\n return\n }\n \n // Increment retry count\n let newDelivery = PendingDelivery(\n messageID: delivery.messageID,\n sentAt: delivery.sentAt,\n recipientID: delivery.recipientID,\n recipientNickname: delivery.recipientNickname,\n retryCount: delivery.retryCount + 1,\n isFavorite: delivery.isFavorite,\n timeoutTimer: nil\n )\n \n pendingDeliveries[messageID] = newDelivery\n let retryCount = delivery.retryCount\n pendingLock.unlock()\n \n // Exponential backoff for retry\n let delay = retryDelay * pow(2, Double(retryCount))\n \n DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in\n // Trigger resend through delegate or notification\n NotificationCenter.default.post(\n name: Notification.Name(\"bitchat.retryMessage\"),\n object: nil,\n userInfo: [\"messageID\": messageID]\n )\n \n // Schedule new timeout\n self?.scheduleTimeout(for: messageID)\n }\n }\n \n private func startCleanupTimer() {\n cleanupTimer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in\n self?.cleanupOldDeliveries()\n }\n }\n \n private func cleanupOldDeliveries() {\n pendingLock.lock()\n defer { pendingLock.unlock() }\n \n let now = Date()\n let maxAge: TimeInterval = 3600 // 1 hour\n \n // Clean up old pending deliveries\n pendingDeliveries = pendingDeliveries.filter { (_, delivery) in\n now.timeIntervalSince(delivery.sentAt) < maxAge\n }\n \n // Clean up old ACK IDs (keep last 1000)\n if receivedAckIDs.count > 1000 {\n receivedAckIDs.removeAll()\n }\n if sentAckIDs.count > 1000 {\n sentAckIDs.removeAll()\n }\n }\n}"], ["/bitchat/bitchat/Utils/BatteryOptimizer.swift", "//\n// BatteryOptimizer.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport Combine\n#if os(iOS)\nimport UIKit\n#elseif os(macOS)\nimport IOKit.ps\n#endif\n\nenum PowerMode {\n case performance // Max performance, battery drain OK\n case balanced // Default balanced mode\n case powerSaver // Aggressive power saving\n case ultraLowPower // Emergency mode\n \n var scanDuration: TimeInterval {\n switch self {\n case .performance: return 3.0\n case .balanced: return 2.0\n case .powerSaver: return 1.0\n case .ultraLowPower: return 0.5\n }\n }\n \n var scanPauseDuration: TimeInterval {\n switch self {\n case .performance: return 2.0\n case .balanced: return 3.0\n case .powerSaver: return 8.0\n case .ultraLowPower: return 20.0\n }\n }\n \n var maxConnections: Int {\n switch self {\n case .performance: return 20\n case .balanced: return 10\n case .powerSaver: return 5\n case .ultraLowPower: return 2\n }\n }\n \n var advertisingInterval: TimeInterval {\n // Note: iOS doesn't let us control this directly, but we can stop/start advertising\n switch self {\n case .performance: return 0.0 // Continuous\n case .balanced: return 5.0 // Advertise every 5 seconds\n case .powerSaver: return 15.0 // Advertise every 15 seconds\n case .ultraLowPower: return 30.0 // Advertise every 30 seconds\n }\n }\n \n var messageAggregationWindow: TimeInterval {\n switch self {\n case .performance: return 0.05 // 50ms\n case .balanced: return 0.1 // 100ms\n case .powerSaver: return 0.3 // 300ms\n case .ultraLowPower: return 0.5 // 500ms\n }\n }\n}\n\nclass BatteryOptimizer {\n static let shared = BatteryOptimizer()\n \n @Published var currentPowerMode: PowerMode = .balanced\n @Published var isInBackground: Bool = false\n @Published var batteryLevel: Float = 1.0\n @Published var isCharging: Bool = false\n \n private var observers: [NSObjectProtocol] = []\n \n private init() {\n setupObservers()\n updateBatteryStatus()\n }\n \n deinit {\n observers.forEach { NotificationCenter.default.removeObserver($0) }\n }\n \n private func setupObservers() {\n #if os(iOS)\n // Monitor app state\n observers.append(\n NotificationCenter.default.addObserver(\n forName: UIApplication.didEnterBackgroundNotification,\n object: nil,\n queue: .main\n ) { [weak self] _ in\n self?.isInBackground = true\n self?.updatePowerMode()\n }\n )\n \n observers.append(\n NotificationCenter.default.addObserver(\n forName: UIApplication.willEnterForegroundNotification,\n object: nil,\n queue: .main\n ) { [weak self] _ in\n self?.isInBackground = false\n self?.updatePowerMode()\n }\n )\n \n // Monitor battery\n UIDevice.current.isBatteryMonitoringEnabled = true\n \n observers.append(\n NotificationCenter.default.addObserver(\n forName: UIDevice.batteryLevelDidChangeNotification,\n object: nil,\n queue: .main\n ) { [weak self] _ in\n self?.updateBatteryStatus()\n }\n )\n \n observers.append(\n NotificationCenter.default.addObserver(\n forName: UIDevice.batteryStateDidChangeNotification,\n object: nil,\n queue: .main\n ) { [weak self] _ in\n self?.updateBatteryStatus()\n }\n )\n #endif\n }\n \n private func updateBatteryStatus() {\n #if os(iOS)\n batteryLevel = UIDevice.current.batteryLevel\n if batteryLevel < 0 {\n batteryLevel = 1.0 // Unknown battery level\n }\n \n isCharging = UIDevice.current.batteryState == .charging || \n UIDevice.current.batteryState == .full\n #elseif os(macOS)\n if let info = getMacOSBatteryInfo() {\n batteryLevel = info.level\n isCharging = info.isCharging\n }\n #endif\n \n updatePowerMode()\n }\n \n #if os(macOS)\n private func getMacOSBatteryInfo() -> (level: Float, isCharging: Bool)? {\n let snapshot = IOPSCopyPowerSourcesInfo().takeRetainedValue()\n let sources = IOPSCopyPowerSourcesList(snapshot).takeRetainedValue() as Array\n \n for source in sources {\n if let description = IOPSGetPowerSourceDescription(snapshot, source).takeUnretainedValue() as? [String: Any] {\n if let currentCapacity = description[kIOPSCurrentCapacityKey] as? Int,\n let maxCapacity = description[kIOPSMaxCapacityKey] as? Int {\n let level = Float(currentCapacity) / Float(maxCapacity)\n let isCharging = description[kIOPSPowerSourceStateKey] as? String == kIOPSACPowerValue\n return (level, isCharging)\n }\n }\n }\n return nil\n }\n #endif\n \n private func updatePowerMode() {\n // Determine optimal power mode based on:\n // 1. Battery level\n // 2. Charging status\n // 3. Background/foreground state\n \n if isCharging {\n // When charging, use performance mode unless battery is critical\n currentPowerMode = batteryLevel < 0.1 ? .balanced : .performance\n } else if isInBackground {\n // In background, always use power saving\n if batteryLevel < 0.2 {\n currentPowerMode = .ultraLowPower\n } else if batteryLevel < 0.5 {\n currentPowerMode = .powerSaver\n } else {\n currentPowerMode = .balanced\n }\n } else {\n // Foreground, not charging\n if batteryLevel < 0.1 {\n currentPowerMode = .ultraLowPower\n } else if batteryLevel < 0.3 {\n currentPowerMode = .powerSaver\n } else if batteryLevel < 0.6 {\n currentPowerMode = .balanced\n } else {\n currentPowerMode = .performance\n }\n }\n }\n \n // Manual power mode override\n func setPowerMode(_ mode: PowerMode) {\n currentPowerMode = mode\n }\n \n // Get current scan parameters\n var scanParameters: (duration: TimeInterval, pause: TimeInterval) {\n return (currentPowerMode.scanDuration, currentPowerMode.scanPauseDuration)\n }\n \n // Should we skip non-essential operations?\n var shouldSkipNonEssential: Bool {\n return currentPowerMode == .ultraLowPower || \n (currentPowerMode == .powerSaver && isInBackground)\n }\n \n // Should we reduce message frequency?\n var shouldThrottleMessages: Bool {\n return currentPowerMode == .powerSaver || currentPowerMode == .ultraLowPower\n }\n}"], ["/bitchat/bitchat/Noise/NoiseSecurityConsiderations.swift", "//\n// NoiseSecurityConsiderations.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport CryptoKit\n\n// MARK: - Security Constants\n\nenum NoiseSecurityConstants {\n // Maximum message size to prevent memory exhaustion\n static let maxMessageSize = 65535 // 64KB as per Noise spec\n \n // Maximum handshake message size\n static let maxHandshakeMessageSize = 2048 // 2KB to accommodate XX pattern\n \n // Session timeout - sessions older than this should be renegotiated\n static let sessionTimeout: TimeInterval = 86400 // 24 hours\n \n // Maximum number of messages before rekey (2^64 - 1 is the nonce limit)\n static let maxMessagesPerSession: UInt64 = 1_000_000_000 // 1 billion messages\n \n // Handshake timeout - abandon incomplete handshakes\n static let handshakeTimeout: TimeInterval = 60 // 1 minute\n \n // Maximum concurrent sessions per peer\n static let maxSessionsPerPeer = 3\n \n // Rate limiting\n static let maxHandshakesPerMinute = 10\n static let maxMessagesPerSecond = 100\n \n // Global rate limiting (across all peers)\n static let maxGlobalHandshakesPerMinute = 30\n static let maxGlobalMessagesPerSecond = 500\n}\n\n// MARK: - Security Validations\n\nstruct NoiseSecurityValidator {\n \n /// Validate message size\n static func validateMessageSize(_ data: Data) -> Bool {\n return data.count <= NoiseSecurityConstants.maxMessageSize\n }\n \n /// Validate handshake message size\n static func validateHandshakeMessageSize(_ data: Data) -> Bool {\n return data.count <= NoiseSecurityConstants.maxHandshakeMessageSize\n }\n \n /// Validate peer ID format\n static func validatePeerID(_ peerID: String) -> Bool {\n // Peer ID should be reasonable length and contain valid characters\n let validCharset = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: \"-_\"))\n return peerID.count > 0 && \n peerID.count <= 64 && \n peerID.rangeOfCharacter(from: validCharset.inverted) == nil\n }\n}\n\n// MARK: - Enhanced Noise Session with Security\n\nclass SecureNoiseSession: NoiseSession {\n private(set) var messageCount: UInt64 = 0\n private let sessionStartTime = Date()\n private(set) var lastActivityTime = Date()\n \n override func encrypt(_ plaintext: Data) throws -> Data {\n // Check session age\n if Date().timeIntervalSince(sessionStartTime) > NoiseSecurityConstants.sessionTimeout {\n throw NoiseSecurityError.sessionExpired\n }\n \n // Check message count\n if messageCount >= NoiseSecurityConstants.maxMessagesPerSession {\n throw NoiseSecurityError.sessionExhausted\n }\n \n // Validate message size\n guard NoiseSecurityValidator.validateMessageSize(plaintext) else {\n throw NoiseSecurityError.messageTooLarge\n }\n \n let encrypted = try super.encrypt(plaintext)\n messageCount += 1\n lastActivityTime = Date()\n \n return encrypted\n }\n \n override func decrypt(_ ciphertext: Data) throws -> Data {\n // Check session age\n if Date().timeIntervalSince(sessionStartTime) > NoiseSecurityConstants.sessionTimeout {\n throw NoiseSecurityError.sessionExpired\n }\n \n // Validate message size\n guard NoiseSecurityValidator.validateMessageSize(ciphertext) else {\n throw NoiseSecurityError.messageTooLarge\n }\n \n let decrypted = try super.decrypt(ciphertext)\n lastActivityTime = Date()\n \n return decrypted\n }\n \n func needsRenegotiation() -> Bool {\n // Check if we've used more than 90% of message limit\n let messageThreshold = UInt64(Double(NoiseSecurityConstants.maxMessagesPerSession) * 0.9)\n if messageCount >= messageThreshold {\n return true\n }\n \n // Check if last activity was more than 30 minutes ago\n if Date().timeIntervalSince(lastActivityTime) > NoiseSecurityConstants.sessionTimeout {\n return true\n }\n \n return false\n }\n \n // MARK: - Testing Support\n #if DEBUG\n func setLastActivityTimeForTesting(_ date: Date) {\n lastActivityTime = date\n }\n \n func setMessageCountForTesting(_ count: UInt64) {\n messageCount = count\n }\n #endif\n}\n\n// MARK: - Rate Limiter\n\nclass NoiseRateLimiter {\n private var handshakeTimestamps: [String: [Date]] = [:] // peerID -> timestamps\n private var messageTimestamps: [String: [Date]] = [:] // peerID -> timestamps\n \n // Global rate limiting\n private var globalHandshakeTimestamps: [Date] = []\n private var globalMessageTimestamps: [Date] = []\n \n private let queue = DispatchQueue(label: \"chat.bitchat.noise.ratelimit\", attributes: .concurrent)\n \n func allowHandshake(from peerID: String) -> Bool {\n return queue.sync(flags: .barrier) {\n let now = Date()\n let oneMinuteAgo = now.addingTimeInterval(-60)\n \n // Check global rate limit first\n globalHandshakeTimestamps = globalHandshakeTimestamps.filter { $0 > oneMinuteAgo }\n if globalHandshakeTimestamps.count >= NoiseSecurityConstants.maxGlobalHandshakesPerMinute {\n SecureLogger.log(\"Global handshake rate limit exceeded: \\(globalHandshakeTimestamps.count)/\\(NoiseSecurityConstants.maxGlobalHandshakesPerMinute) per minute\", category: SecureLogger.security, level: .warning)\n return false\n }\n \n // Check per-peer rate limit\n var timestamps = handshakeTimestamps[peerID] ?? []\n timestamps = timestamps.filter { $0 > oneMinuteAgo }\n \n if timestamps.count >= NoiseSecurityConstants.maxHandshakesPerMinute {\n SecureLogger.log(\"Per-peer handshake rate limit exceeded for \\(peerID): \\(timestamps.count)/\\(NoiseSecurityConstants.maxHandshakesPerMinute) per minute\", category: SecureLogger.security, level: .warning)\n return false\n }\n \n // Record new handshake\n timestamps.append(now)\n handshakeTimestamps[peerID] = timestamps\n globalHandshakeTimestamps.append(now)\n return true\n }\n }\n \n func allowMessage(from peerID: String) -> Bool {\n return queue.sync(flags: .barrier) {\n let now = Date()\n let oneSecondAgo = now.addingTimeInterval(-1)\n \n // Check global rate limit first\n globalMessageTimestamps = globalMessageTimestamps.filter { $0 > oneSecondAgo }\n if globalMessageTimestamps.count >= NoiseSecurityConstants.maxGlobalMessagesPerSecond {\n SecureLogger.log(\"Global message rate limit exceeded: \\(globalMessageTimestamps.count)/\\(NoiseSecurityConstants.maxGlobalMessagesPerSecond) per second\", category: SecureLogger.security, level: .warning)\n return false\n }\n \n // Check per-peer rate limit\n var timestamps = messageTimestamps[peerID] ?? []\n timestamps = timestamps.filter { $0 > oneSecondAgo }\n \n if timestamps.count >= NoiseSecurityConstants.maxMessagesPerSecond {\n SecureLogger.log(\"Per-peer message rate limit exceeded for \\(peerID): \\(timestamps.count)/\\(NoiseSecurityConstants.maxMessagesPerSecond) per second\", category: SecureLogger.security, level: .warning)\n return false\n }\n \n // Record new message\n timestamps.append(now)\n messageTimestamps[peerID] = timestamps\n globalMessageTimestamps.append(now)\n return true\n }\n }\n \n func reset(for peerID: String) {\n queue.async(flags: .barrier) {\n self.handshakeTimestamps.removeValue(forKey: peerID)\n self.messageTimestamps.removeValue(forKey: peerID)\n }\n }\n}\n\n// MARK: - Security Errors\n\nenum NoiseSecurityError: Error {\n case sessionExpired\n case sessionExhausted\n case messageTooLarge\n case invalidPeerID\n case rateLimitExceeded\n case handshakeTimeout\n}\n"], ["/bitchat/bitchat/Protocols/BinaryEncodingUtils.swift", "//\n// BinaryEncodingUtils.swift\n// bitchat\n//\n// Binary encoding utilities for efficient protocol messages\n//\n\nimport Foundation\n\n// MARK: - Hex Encoding/Decoding\n\nextension Data {\n func hexEncodedString() -> String {\n if self.isEmpty {\n return \"\"\n }\n return self.map { String(format: \"%02x\", $0) }.joined()\n }\n \n init?(hexString: String) {\n let len = hexString.count / 2\n var data = Data(capacity: len)\n var index = hexString.startIndex\n \n for _ in 0..> 8) & 0xFF))\n self.append(UInt8(value & 0xFF))\n }\n \n mutating func appendUInt32(_ value: UInt32) {\n self.append(UInt8((value >> 24) & 0xFF))\n self.append(UInt8((value >> 16) & 0xFF))\n self.append(UInt8((value >> 8) & 0xFF))\n self.append(UInt8(value & 0xFF))\n }\n \n mutating func appendUInt64(_ value: UInt64) {\n for i in (0..<8).reversed() {\n self.append(UInt8((value >> (i * 8)) & 0xFF))\n }\n }\n \n mutating func appendString(_ string: String, maxLength: Int = 255) {\n guard let data = string.data(using: .utf8) else { return }\n let length = Swift.min(data.count, maxLength)\n \n if maxLength <= 255 {\n self.append(UInt8(length))\n } else {\n self.appendUInt16(UInt16(length))\n }\n \n self.append(data.prefix(length))\n }\n \n mutating func appendData(_ data: Data, maxLength: Int = 65535) {\n let length = Swift.min(data.count, maxLength)\n \n if maxLength <= 255 {\n self.append(UInt8(length))\n } else {\n self.appendUInt16(UInt16(length))\n }\n \n self.append(data.prefix(length))\n }\n \n mutating func appendDate(_ date: Date) {\n let timestamp = UInt64(date.timeIntervalSince1970 * 1000) // milliseconds\n self.appendUInt64(timestamp)\n }\n \n mutating func appendUUID(_ uuid: String) {\n // Convert UUID string to 16 bytes\n var uuidData = Data(count: 16)\n \n let cleanUUID = uuid.replacingOccurrences(of: \"-\", with: \"\")\n var index = cleanUUID.startIndex\n \n for i in 0..<16 {\n guard index < cleanUUID.endIndex else { break }\n let nextIndex = cleanUUID.index(index, offsetBy: 2)\n if let byte = UInt8(String(cleanUUID[index.. UInt8? {\n guard offset >= 0 && offset < self.count else { return nil }\n let value = self[offset]\n offset += 1\n return value\n }\n \n func readUInt16(at offset: inout Int) -> UInt16? {\n guard offset + 2 <= self.count else { return nil }\n let value = UInt16(self[offset]) << 8 | UInt16(self[offset + 1])\n offset += 2\n return value\n }\n \n func readUInt32(at offset: inout Int) -> UInt32? {\n guard offset + 4 <= self.count else { return nil }\n let value = UInt32(self[offset]) << 24 |\n UInt32(self[offset + 1]) << 16 |\n UInt32(self[offset + 2]) << 8 |\n UInt32(self[offset + 3])\n offset += 4\n return value\n }\n \n func readUInt64(at offset: inout Int) -> UInt64? {\n guard offset + 8 <= self.count else { return nil }\n var value: UInt64 = 0\n for i in 0..<8 {\n value = (value << 8) | UInt64(self[offset + i])\n }\n offset += 8\n return value\n }\n \n func readString(at offset: inout Int, maxLength: Int = 255) -> String? {\n let length: Int\n \n if maxLength <= 255 {\n guard let len = readUInt8(at: &offset) else { return nil }\n length = Int(len)\n } else {\n guard let len = readUInt16(at: &offset) else { return nil }\n length = Int(len)\n }\n \n guard offset + length <= self.count else { return nil }\n \n let stringData = self[offset.. Data? {\n let length: Int\n \n if maxLength <= 255 {\n guard let len = readUInt8(at: &offset) else { return nil }\n length = Int(len)\n } else {\n guard let len = readUInt16(at: &offset) else { return nil }\n length = Int(len)\n }\n \n guard offset + length <= self.count else { return nil }\n \n let data = self[offset.. Date? {\n guard let timestamp = readUInt64(at: &offset) else { return nil }\n return Date(timeIntervalSince1970: Double(timestamp) / 1000.0)\n }\n \n func readUUID(at offset: inout Int) -> String? {\n guard offset + 16 <= self.count else { return nil }\n \n let uuidData = self[offset.. Data? {\n guard offset + count <= self.count else { return nil }\n \n let data = self[offset.. Data\n static func fromBinaryData(_ data: Data) -> Self?\n}\n\n// MARK: - Message Type Registry\n\nenum BinaryMessageType: UInt8 {\n case deliveryAck = 0x01\n case readReceipt = 0x02\n case versionHello = 0x07\n case versionAck = 0x08\n case noiseIdentityAnnouncement = 0x09\n case noiseMessage = 0x0A\n}"], ["/bitchat/bitchat/Utils/OptimizedBloomFilter.swift", "//\n// OptimizedBloomFilter.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport CryptoKit\n\n/// Optimized Bloom filter using bit-packed storage and better hash functions\nstruct OptimizedBloomFilter {\n private var bitArray: [UInt64]\n private let bitCount: Int\n private let hashCount: Int\n \n // Statistics\n private(set) var insertCount: Int = 0\n \n init(expectedItems: Int = 1000, falsePositiveRate: Double = 0.01) {\n // Calculate optimal bit count and hash count\n let m = Double(expectedItems) * abs(log(falsePositiveRate)) / (log(2) * log(2))\n self.bitCount = Int(max(64, m.rounded()))\n \n let k = Double(bitCount) / Double(expectedItems) * log(2)\n self.hashCount = Int(max(1, min(10, k.rounded())))\n \n // Initialize bit array (64 bits per UInt64)\n let arraySize = (bitCount + 63) / 64\n self.bitArray = Array(repeating: 0, count: arraySize)\n }\n \n mutating func insert(_ item: String) {\n let hashes = generateHashes(item)\n \n for i in 0.. Bool {\n let hashes = generateHashes(item)\n \n for i in 0.. [Int] {\n guard let data = item.data(using: .utf8) else {\n return Array(repeating: 0, count: hashCount)\n }\n \n // Use SHA256 for high-quality hash values\n let hash = SHA256.hash(data: data)\n let hashBytes = Array(hash)\n \n var hashes = [Int]()\n \n // Extract multiple hash values from the SHA256 output\n for i in 0.. 0 else { return 0 }\n \n // Count set bits\n var setBits = 0\n for value in bitArray {\n setBits += value.nonzeroBitCount\n }\n \n // Calculate probability: (1 - e^(-kn/m))^k\n let ratio = Double(hashCount * insertCount) / Double(bitCount)\n return pow(1 - exp(-ratio), Double(hashCount))\n }\n \n // Get memory usage in bytes\n var memorySizeBytes: Int {\n return bitArray.count * 8\n }\n}\n\n// Extension for adaptive Bloom filter that adjusts based on network size\nextension OptimizedBloomFilter {\n static func adaptive(for networkSize: Int) -> OptimizedBloomFilter {\n // Adjust parameters based on network size\n let expectedItems: Int\n let falsePositiveRate: Double\n \n switch networkSize {\n case 0..<50:\n expectedItems = 500\n falsePositiveRate = 0.01\n case 50..<200:\n expectedItems = 2000\n falsePositiveRate = 0.02\n case 200..<500:\n expectedItems = 5000\n falsePositiveRate = 0.03\n default:\n expectedItems = 10000\n falsePositiveRate = 0.05\n }\n \n return OptimizedBloomFilter(expectedItems: expectedItems, falsePositiveRate: falsePositiveRate)\n }\n}"], ["/bitchat/bitchat/Utils/LRUCache.swift", "//\n// LRUCache.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\n\n/// Thread-safe LRU (Least Recently Used) cache implementation\nfinal class LRUCache {\n private class Node {\n var key: Key\n var value: Value\n var prev: Node?\n var next: Node?\n \n init(key: Key, value: Value) {\n self.key = key\n self.value = value\n }\n }\n \n private let maxSize: Int\n private var cache: [Key: Node] = [:]\n private var head: Node?\n private var tail: Node?\n private let queue = DispatchQueue(label: \"bitchat.lrucache\", attributes: .concurrent)\n \n init(maxSize: Int) {\n self.maxSize = maxSize\n }\n \n func set(_ key: Key, value: Value) {\n queue.sync(flags: .barrier) {\n if let node = cache[key] {\n // Update existing value and move to front\n node.value = value\n moveToFront(node)\n } else {\n // Add new node\n let newNode = Node(key: key, value: value)\n cache[key] = newNode\n addToFront(newNode)\n \n // Remove oldest if over capacity\n if cache.count > maxSize {\n if let tailNode = tail {\n removeNode(tailNode)\n cache.removeValue(forKey: tailNode.key)\n }\n }\n }\n }\n }\n \n func get(_ key: Key) -> Value? {\n return queue.sync(flags: .barrier) {\n guard let node = cache[key] else { return nil }\n moveToFront(node)\n return node.value\n }\n }\n \n func contains(_ key: Key) -> Bool {\n return queue.sync {\n return cache[key] != nil\n }\n }\n \n func remove(_ key: Key) {\n queue.sync(flags: .barrier) {\n if let node = cache[key] {\n removeNode(node)\n cache.removeValue(forKey: key)\n }\n }\n }\n \n func removeAll() {\n queue.sync(flags: .barrier) {\n cache.removeAll()\n head = nil\n tail = nil\n }\n }\n \n var count: Int {\n return queue.sync {\n return cache.count\n }\n }\n \n var keys: [Key] {\n return queue.sync {\n return Array(cache.keys)\n }\n }\n \n // MARK: - Private Helpers\n \n private func addToFront(_ node: Node) {\n node.next = head\n node.prev = nil\n \n if let head = head {\n head.prev = node\n }\n \n head = node\n \n if tail == nil {\n tail = node\n }\n }\n \n private func removeNode(_ node: Node) {\n if let prev = node.prev {\n prev.next = node.next\n } else {\n head = node.next\n }\n \n if let next = node.next {\n next.prev = node.prev\n } else {\n tail = node.prev\n }\n \n node.prev = nil\n node.next = nil\n }\n \n private func moveToFront(_ node: Node) {\n guard node !== head else { return }\n removeNode(node)\n addToFront(node)\n }\n}\n\n// MARK: - Bounded Set\n\n/// Thread-safe set with maximum size using LRU eviction\nfinal class BoundedSet {\n private let cache: LRUCache\n \n init(maxSize: Int) {\n self.cache = LRUCache(maxSize: maxSize)\n }\n \n func insert(_ element: Element) {\n cache.set(element, value: true)\n }\n \n func contains(_ element: Element) -> Bool {\n return cache.get(element) != nil\n }\n \n func remove(_ element: Element) {\n cache.remove(element)\n }\n \n func removeAll() {\n cache.removeAll()\n }\n \n var count: Int {\n return cache.count\n }\n}"], ["/bitchat/bitchat/Services/NotificationService.swift", "//\n// NotificationService.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport UserNotifications\n#if os(iOS)\nimport UIKit\n#elseif os(macOS)\nimport AppKit\n#endif\n\nclass NotificationService {\n static let shared = NotificationService()\n \n private init() {}\n \n func requestAuthorization() {\n UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in\n if granted {\n // Permission granted\n } else {\n // Permission denied\n }\n }\n }\n \n func sendLocalNotification(title: String, body: String, identifier: String, userInfo: [String: Any]? = nil) {\n // For now, skip app state check entirely to avoid thread issues\n // The NotificationDelegate will handle foreground presentation\n DispatchQueue.main.async {\n let content = UNMutableNotificationContent()\n content.title = title\n content.body = body\n content.sound = .default\n if let userInfo = userInfo {\n content.userInfo = userInfo\n }\n \n let request = UNNotificationRequest(\n identifier: identifier,\n content: content,\n trigger: nil // Deliver immediately\n )\n \n UNUserNotificationCenter.current().add(request) { _ in\n // Notification added\n }\n }\n }\n \n func sendMentionNotification(from sender: String, message: String) {\n let title = \"@🫵 you were mentioned by \\(sender)\"\n let body = message\n let identifier = \"mention-\\(UUID().uuidString)\"\n \n sendLocalNotification(title: title, body: body, identifier: identifier)\n }\n \n func sendPrivateMessageNotification(from sender: String, message: String, peerID: String) {\n let title = \"🔒 private message from \\(sender)\"\n let body = message\n let identifier = \"private-\\(UUID().uuidString)\"\n let userInfo = [\"peerID\": peerID, \"senderName\": sender]\n \n sendLocalNotification(title: title, body: body, identifier: identifier, userInfo: userInfo)\n }\n \n func sendFavoriteOnlineNotification(nickname: String) {\n // Send directly without checking app state for favorites\n DispatchQueue.main.async {\n let content = UNMutableNotificationContent()\n content.title = \"⭐ \\(nickname) is online!\"\n content.body = \"wanna get in there?\"\n content.sound = .default\n \n let request = UNNotificationRequest(\n identifier: \"favorite-online-\\(UUID().uuidString)\",\n content: content,\n trigger: nil\n )\n \n UNUserNotificationCenter.current().add(request) { _ in\n // Notification added\n }\n }\n }\n \n func sendNetworkAvailableNotification(peerCount: Int) {\n let title = \"👥 bitchatters nearby!\"\n let body = peerCount == 1 ? \"1 person around\" : \"\\(peerCount) people around\"\n let identifier = \"network-available-\\(Date().timeIntervalSince1970)\"\n \n // For network notifications, we want to show them even in foreground\n // No app state check - let the notification delegate handle presentation\n DispatchQueue.main.async {\n let content = UNMutableNotificationContent()\n content.title = title\n content.body = body\n content.sound = .default\n content.interruptionLevel = .timeSensitive // Make it more prominent\n \n let request = UNNotificationRequest(\n identifier: identifier,\n content: content,\n trigger: nil // Deliver immediately\n )\n \n UNUserNotificationCenter.current().add(request) { _ in\n // Notification added\n }\n }\n }\n}\n"], ["/bitchat/bitchat/Utils/CompressionUtil.swift", "//\n// CompressionUtil.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport Compression\n\nstruct CompressionUtil {\n // Compression threshold - don't compress if data is smaller than this\n static let compressionThreshold = 100 // bytes\n \n // Compress data using LZ4 algorithm (fast compression/decompression)\n static func compress(_ data: Data) -> Data? {\n // Skip compression for small data\n guard data.count >= compressionThreshold else { return nil }\n \n let maxCompressedSize = data.count + (data.count / 255) + 16\n let destinationBuffer = UnsafeMutablePointer.allocate(capacity: maxCompressedSize)\n defer { destinationBuffer.deallocate() }\n \n let compressedSize = data.withUnsafeBytes { sourceBuffer in\n guard let sourcePtr = sourceBuffer.bindMemory(to: UInt8.self).baseAddress else { return 0 }\n return compression_encode_buffer(\n destinationBuffer, data.count,\n sourcePtr, data.count,\n nil, COMPRESSION_LZ4\n )\n }\n \n guard compressedSize > 0 && compressedSize < data.count else { return nil }\n \n return Data(bytes: destinationBuffer, count: compressedSize)\n }\n \n // Decompress LZ4 compressed data\n static func decompress(_ compressedData: Data, originalSize: Int) -> Data? {\n let destinationBuffer = UnsafeMutablePointer.allocate(capacity: originalSize)\n defer { destinationBuffer.deallocate() }\n \n let decompressedSize = compressedData.withUnsafeBytes { sourceBuffer in\n guard let sourcePtr = sourceBuffer.bindMemory(to: UInt8.self).baseAddress else { return 0 }\n return compression_decode_buffer(\n destinationBuffer, originalSize,\n sourcePtr, compressedData.count,\n nil, COMPRESSION_LZ4\n )\n }\n \n guard decompressedSize > 0 else { return nil }\n \n return Data(bytes: destinationBuffer, count: decompressedSize)\n }\n \n // Helper to check if compression is worth it\n static func shouldCompress(_ data: Data) -> Bool {\n // Don't compress if:\n // 1. Data is too small\n // 2. Data appears to be already compressed (high entropy)\n guard data.count >= compressionThreshold else { return false }\n \n // Simple entropy check - count unique bytes\n var byteFrequency = [UInt8: Int]()\n for byte in data {\n byteFrequency[byte, default: 0] += 1\n }\n \n // If we have very high byte diversity, data is likely already compressed\n let uniqueByteRatio = Double(byteFrequency.count) / Double(min(data.count, 256))\n return uniqueByteRatio < 0.9 // Compress if less than 90% unique bytes\n }\n}"]], "task_instance_info": {"created_time": "2025-08-21 03:19:36", "created_task_model": "DeepSeek-R1", "function_skeleton": "private func formatFingerprint ( _ fingerprint: String ) -> String { }", "code_description": "This code segment functions to: Format cryptographic identification strings by inserting spacing characters at regular intervals and introducing line breaks after specific groupings to enhance visual readability of the structured data blocks."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\n private func formatFingerprint(_ fingerprint: String) -> String {\n return stride(from: 0, to: fingerprint.count, by: 4).map { index -> String in\n let start = fingerprint.index(fingerprint.startIndex, offsetBy: index)\n let end = fingerprint.index(start, offsetBy: 4, limitedBy: fingerprint.endIndex) ?? fingerprint.endIndex\n return String(fingerprint[start.. String {\n let uppercased = fingerprint.uppercased()\n var formatted = \"\"\n for (index, char) in uppercased.enumerated() {\n if index > 0 && index % 4 == 0 {\n if index % 16 == 0 {\n formatted += \"\\n\"\n } else {\n formatted += \" \"\n }\n }\n formatted += String(char)\n }\n return formatted\n }", "predict_code_clean": "private func formatFingerprint(_ fingerprint: String) -> String {\n return stride(from: 0, to: fingerprint.count, by: 4).map { index -> String in\n let start = fingerprint.index(fingerprint.startIndex, offsetBy: index)\n let end = fingerprint.index(start, offsetBy: 4, limitedBy: fingerprint.endIndex) ?? fingerprint.endIndex\n return String(fingerprint[start..\n//\n\nimport SwiftUI\n\nstruct FingerprintView: View {\n @ObservedObject var viewModel: ChatViewModel\n let peerID: String\n @Environment(\\.dismiss) var dismiss\n @Environment(\\.colorScheme) var colorScheme\n \n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n private var backgroundColor: Color {\n colorScheme == .dark ? Color.black : Color.white\n }\n \n var body: some View {\n VStack(spacing: 20) {\n // Header\n HStack {\n Text(\"SECURITY VERIFICATION\")\n .font(.system(size: 16, weight: .bold, design: .monospaced))\n .foregroundColor(textColor)\n \n Spacer()\n \n Button(\"DONE\") {\n dismiss()\n }\n .foregroundColor(textColor)\n }\n .padding()\n \n VStack(alignment: .leading, spacing: 16) {\n // Peer info\n let peerNickname = viewModel.meshService.getPeerNicknames()[peerID] ?? \"Unknown\"\n let encryptionStatus = viewModel.getEncryptionStatus(for: peerID)\n \n HStack {\n if let icon = encryptionStatus.icon {\n Image(systemName: icon)\n .font(.system(size: 20))\n .foregroundColor(encryptionStatus == .noiseVerified ? Color.green : textColor)\n }\n \n VStack(alignment: .leading, spacing: 4) {\n Text(peerNickname)\n .font(.system(size: 18, weight: .semibold, design: .monospaced))\n .foregroundColor(textColor)\n \n Text(encryptionStatus.description)\n .font(.system(size: 12, design: .monospaced))\n .foregroundColor(textColor.opacity(0.7))\n }\n \n Spacer()\n }\n .padding()\n .background(Color.gray.opacity(0.1))\n .cornerRadius(8)\n \n // Their fingerprint\n VStack(alignment: .leading, spacing: 8) {\n Text(\"THEIR FINGERPRINT:\")\n .font(.system(size: 12, weight: .bold, design: .monospaced))\n .foregroundColor(textColor.opacity(0.7))\n \n if let fingerprint = viewModel.getFingerprint(for: peerID) {\n Text(formatFingerprint(fingerprint))\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(textColor)\n .multilineTextAlignment(.leading)\n .lineLimit(nil)\n .fixedSize(horizontal: false, vertical: true)\n .padding()\n .frame(maxWidth: .infinity)\n .background(Color.gray.opacity(0.1))\n .cornerRadius(8)\n .contextMenu {\n Button(\"Copy\") {\n #if os(iOS)\n UIPasteboard.general.string = fingerprint\n #else\n NSPasteboard.general.clearContents()\n NSPasteboard.general.setString(fingerprint, forType: .string)\n #endif\n }\n }\n } else {\n Text(\"not available - handshake in progress\")\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(Color.orange)\n .padding()\n }\n }\n \n // My fingerprint\n VStack(alignment: .leading, spacing: 8) {\n Text(\"YOUR FINGERPRINT:\")\n .font(.system(size: 12, weight: .bold, design: .monospaced))\n .foregroundColor(textColor.opacity(0.7))\n \n let myFingerprint = viewModel.getMyFingerprint()\n Text(formatFingerprint(myFingerprint))\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(textColor)\n .multilineTextAlignment(.leading)\n .lineLimit(nil)\n .fixedSize(horizontal: false, vertical: true)\n .padding()\n .frame(maxWidth: .infinity)\n .background(Color.gray.opacity(0.1))\n .cornerRadius(8)\n .contextMenu {\n Button(\"Copy\") {\n #if os(iOS)\n UIPasteboard.general.string = myFingerprint\n #else\n NSPasteboard.general.clearContents()\n NSPasteboard.general.setString(myFingerprint, forType: .string)\n #endif\n }\n }\n }\n \n // Verification status\n if encryptionStatus == .noiseSecured || encryptionStatus == .noiseVerified {\n let isVerified = encryptionStatus == .noiseVerified\n \n VStack(spacing: 12) {\n Text(isVerified ? \"✓ VERIFIED\" : \"⚠️ NOT VERIFIED\")\n .font(.system(size: 14, weight: .bold, design: .monospaced))\n .foregroundColor(isVerified ? Color.green : Color.orange)\n .frame(maxWidth: .infinity)\n \n Text(isVerified ? \n \"you have verified this person's identity.\" :\n \"compare these fingerprints with \\(peerNickname) using a secure channel.\")\n .font(.system(size: 12, design: .monospaced))\n .foregroundColor(textColor.opacity(0.7))\n .multilineTextAlignment(.center)\n .lineLimit(nil)\n .fixedSize(horizontal: false, vertical: true)\n .frame(maxWidth: .infinity)\n \n if !isVerified {\n Button(action: {\n viewModel.verifyFingerprint(for: peerID)\n dismiss()\n }) {\n Text(\"MARK AS VERIFIED\")\n .font(.system(size: 14, weight: .bold, design: .monospaced))\n .foregroundColor(.white)\n .padding(.horizontal, 20)\n .padding(.vertical, 10)\n .background(Color.green)\n .cornerRadius(8)\n }\n .buttonStyle(PlainButtonStyle())\n }\n }\n .padding(.top)\n .frame(maxWidth: .infinity)\n }\n }\n .padding()\n .frame(maxWidth: 500) // Constrain max width for better readability\n \n Spacer()\n }\n .padding()\n .frame(maxWidth: .infinity, maxHeight: .infinity)\n .background(backgroundColor)\n .presentationDetents([.large])\n .presentationDragIndicator(.visible)\n }\n \n ", "suffix_code": "\n}\n", "middle_code": "private func formatFingerprint(_ fingerprint: String) -> String {\n let uppercased = fingerprint.uppercased()\n var formatted = \"\"\n for (index, char) in uppercased.enumerated() {\n if index > 0 && index % 4 == 0 {\n if index % 16 == 0 {\n formatted += \"\\n\"\n } else {\n formatted += \" \"\n }\n }\n formatted += String(char)\n }\n return formatted\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/bitchat/bitchat/Views/ContentView.swift", "//\n// ContentView.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport SwiftUI\n\n// MARK: - Supporting Types\n\n// Pre-computed peer data for performance\nstruct PeerDisplayData: Identifiable {\n let id: String\n let displayName: String\n let rssi: Int?\n let isFavorite: Bool\n let isMe: Bool\n let hasUnreadMessages: Bool\n let encryptionStatus: EncryptionStatus\n}\n\n// MARK: - Lazy Link Preview\n\n// Lazy loading wrapper for link previews\nstruct LazyLinkPreviewView: View {\n let url: URL\n let title: String?\n @State private var isVisible = false\n \n var body: some View {\n GeometryReader { geometry in\n if isVisible {\n LinkPreviewView(url: url, title: title)\n } else {\n // Placeholder while not visible\n RoundedRectangle(cornerRadius: 10)\n .fill(Color.gray.opacity(0.1))\n .frame(height: 80)\n .onAppear {\n // Only load when view appears on screen\n isVisible = true\n }\n }\n }\n .frame(height: 80)\n }\n}\n\n// MARK: - Main Content View\n\nstruct ContentView: View {\n // MARK: - Properties\n \n @EnvironmentObject var viewModel: ChatViewModel\n @State private var messageText = \"\"\n @State private var textFieldSelection: NSRange? = nil\n @FocusState private var isTextFieldFocused: Bool\n @Environment(\\.colorScheme) var colorScheme\n @State private var showPeerList = false\n @State private var showSidebar = false\n @State private var sidebarDragOffset: CGFloat = 0\n @State private var showAppInfo = false\n @State private var showCommandSuggestions = false\n @State private var commandSuggestions: [String] = []\n @State private var backSwipeOffset: CGFloat = 0\n @State private var showPrivateChat = false\n @State private var showMessageActions = false\n @State private var selectedMessageSender: String?\n @State private var selectedMessageSenderID: String?\n @FocusState private var isNicknameFieldFocused: Bool\n @State private var lastScrollTime: Date = .distantPast\n @State private var scrollThrottleTimer: Timer?\n @State private var autocompleteDebounceTimer: Timer?\n \n // MARK: - Computed Properties\n \n private var backgroundColor: Color {\n colorScheme == .dark ? Color.black : Color.white\n }\n \n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n private var secondaryTextColor: Color {\n colorScheme == .dark ? Color.green.opacity(0.8) : Color(red: 0, green: 0.5, blue: 0).opacity(0.8)\n }\n \n // MARK: - Body\n \n var body: some View {\n GeometryReader { geometry in\n ZStack {\n // Base layer - Main public chat (always visible)\n mainChatView\n \n // Private chat slide-over\n if viewModel.selectedPrivateChatPeer != nil {\n privateChatView\n .frame(width: geometry.size.width)\n .background(backgroundColor)\n .transition(.asymmetric(\n insertion: .move(edge: .trailing),\n removal: .move(edge: .trailing)\n ))\n .offset(x: showPrivateChat ? -1 : max(0, geometry.size.width))\n .offset(x: backSwipeOffset.isNaN ? 0 : backSwipeOffset)\n .gesture(\n DragGesture()\n .onChanged { value in\n if value.translation.width > 0 && !value.translation.width.isNaN {\n let maxWidth = max(0, geometry.size.width)\n backSwipeOffset = min(value.translation.width, maxWidth.isNaN ? 0 : maxWidth)\n }\n }\n .onEnded { value in\n let translation = value.translation.width.isNaN ? 0 : value.translation.width\n let velocity = value.velocity.width.isNaN ? 0 : value.velocity.width\n if translation > 50 || (translation > 30 && velocity > 300) {\n withAnimation(.easeOut(duration: 0.2)) {\n showPrivateChat = false\n backSwipeOffset = 0\n viewModel.endPrivateChat()\n }\n } else {\n withAnimation(.easeOut(duration: 0.15)) {\n backSwipeOffset = 0\n }\n }\n }\n )\n }\n \n // Sidebar overlay\n HStack(spacing: 0) {\n // Tap to dismiss area\n Color.clear\n .contentShape(Rectangle())\n .onTapGesture {\n withAnimation(.easeInOut(duration: 0.2)) {\n showSidebar = false\n sidebarDragOffset = 0\n }\n }\n \n // Only render sidebar content when it's visible or animating\n if showSidebar || sidebarDragOffset != 0 {\n sidebarView\n #if os(macOS)\n .frame(width: min(300, max(0, geometry.size.width.isNaN ? 300 : geometry.size.width) * 0.4))\n #else\n .frame(width: max(0, geometry.size.width.isNaN ? 300 : geometry.size.width) * 0.7)\n #endif\n .transition(.move(edge: .trailing))\n } else {\n // Empty placeholder when hidden\n Color.clear\n #if os(macOS)\n .frame(width: min(300, max(0, geometry.size.width.isNaN ? 300 : geometry.size.width) * 0.4))\n #else\n .frame(width: max(0, geometry.size.width.isNaN ? 300 : geometry.size.width) * 0.7)\n #endif\n }\n }\n .offset(x: {\n let dragOffset = sidebarDragOffset.isNaN ? 0 : sidebarDragOffset\n let width = geometry.size.width.isNaN ? 0 : max(0, geometry.size.width)\n return showSidebar ? -dragOffset : width - dragOffset\n }())\n .animation(.easeInOut(duration: 0.25), value: showSidebar)\n }\n }\n #if os(macOS)\n .frame(minWidth: 600, minHeight: 400)\n #endif\n .onChange(of: viewModel.selectedPrivateChatPeer) { newValue in\n withAnimation(.easeInOut(duration: 0.2)) {\n showPrivateChat = newValue != nil\n }\n }\n .sheet(isPresented: $showAppInfo) {\n AppInfoView()\n }\n .sheet(isPresented: Binding(\n get: { viewModel.showingFingerprintFor != nil },\n set: { _ in viewModel.showingFingerprintFor = nil }\n )) {\n if let peerID = viewModel.showingFingerprintFor {\n FingerprintView(viewModel: viewModel, peerID: peerID)\n }\n }\n .confirmationDialog(\n selectedMessageSender.map { \"@\\($0)\" } ?? \"Actions\",\n isPresented: $showMessageActions,\n titleVisibility: .visible\n ) {\n Button(\"private message\") {\n if let peerID = selectedMessageSenderID {\n viewModel.startPrivateChat(with: peerID)\n withAnimation(.easeInOut(duration: 0.2)) {\n showSidebar = false\n sidebarDragOffset = 0\n }\n }\n }\n \n Button(\"hug\") {\n if let sender = selectedMessageSender {\n viewModel.sendMessage(\"/hug @\\(sender)\")\n }\n }\n \n Button(\"slap\") {\n if let sender = selectedMessageSender {\n viewModel.sendMessage(\"/slap @\\(sender)\")\n }\n }\n \n Button(\"BLOCK\", role: .destructive) {\n if let sender = selectedMessageSender {\n viewModel.sendMessage(\"/block \\(sender)\")\n }\n }\n \n Button(\"cancel\", role: .cancel) {}\n }\n .onDisappear {\n // Clean up timers\n scrollThrottleTimer?.invalidate()\n autocompleteDebounceTimer?.invalidate()\n }\n }\n \n // MARK: - Message List View\n \n private func messagesView(privatePeer: String?) -> some View {\n ScrollViewReader { proxy in\n ScrollView {\n VStack(alignment: .leading, spacing: 0) {\n // Extract messages based on context (private or public chat)\n let messages: [BitchatMessage] = {\n if let privatePeer = privatePeer {\n let msgs = viewModel.getPrivateChatMessages(for: privatePeer)\n return msgs\n } else {\n return viewModel.messages\n }\n }()\n \n // Implement windowing - show last 100 messages for performance\n let windowedMessages = messages.suffix(100)\n \n ForEach(windowedMessages, id: \\.id) { message in\n VStack(alignment: .leading, spacing: 0) {\n // Check if current user is mentioned\n let _ = message.mentions?.contains(viewModel.nickname) ?? false\n \n if message.sender == \"system\" {\n // System messages\n Text(viewModel.formatMessageAsText(message, colorScheme: colorScheme))\n .textSelection(.enabled)\n .fixedSize(horizontal: false, vertical: true)\n .frame(maxWidth: .infinity, alignment: .leading)\n } else {\n // Regular messages with natural text wrapping\n VStack(alignment: .leading, spacing: 0) {\n HStack(alignment: .top, spacing: 0) {\n // Single text view for natural wrapping\n Text(viewModel.formatMessageAsText(message, colorScheme: colorScheme))\n .textSelection(.enabled)\n .fixedSize(horizontal: false, vertical: true)\n .frame(maxWidth: .infinity, alignment: .leading)\n \n // Delivery status indicator for private messages\n if message.isPrivate && message.sender == viewModel.nickname,\n let status = message.deliveryStatus {\n DeliveryStatusView(status: status, colorScheme: colorScheme)\n .padding(.leading, 4)\n }\n }\n \n // Check for plain URLs\n let urls = message.content.extractURLs()\n if !urls.isEmpty {\n ForEach(urls.prefix(3).indices, id: \\.self) { index in\n let urlInfo = urls[index]\n LazyLinkPreviewView(url: urlInfo.url, title: nil)\n .padding(.top, 3)\n .padding(.horizontal, 1)\n .id(\"\\(message.id)-\\(urlInfo.url.absoluteString)\")\n }\n }\n }\n }\n }\n .id(message.id)\n .contentShape(Rectangle())\n .onTapGesture {\n // Only show actions for messages from other users (not system or self)\n if message.sender != \"system\" && message.sender != viewModel.nickname {\n selectedMessageSender = message.sender\n selectedMessageSenderID = message.senderPeerID\n showMessageActions = true\n }\n }\n .padding(.horizontal, 12)\n .padding(.vertical, 2)\n }\n }\n .padding(.vertical, 4)\n }\n .background(backgroundColor)\n .onTapGesture(count: 3) {\n // Triple-tap to clear current chat\n viewModel.sendMessage(\"/clear\")\n }\n .onChange(of: viewModel.messages.count) { _ in\n if privatePeer == nil && !viewModel.messages.isEmpty {\n // Throttle scroll animations to prevent excessive UI updates\n let now = Date()\n if now.timeIntervalSince(lastScrollTime) > 0.5 {\n // Immediate scroll if enough time has passed\n lastScrollTime = now\n proxy.scrollTo(viewModel.messages.suffix(100).last?.id, anchor: .bottom)\n } else {\n // Schedule a delayed scroll\n scrollThrottleTimer?.invalidate()\n scrollThrottleTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in\n lastScrollTime = Date()\n proxy.scrollTo(viewModel.messages.suffix(100).last?.id, anchor: .bottom)\n }\n }\n }\n }\n .onChange(of: viewModel.privateChats) { _ in\n if let peerID = privatePeer,\n let messages = viewModel.privateChats[peerID],\n !messages.isEmpty {\n // Same throttling for private chats\n let now = Date()\n if now.timeIntervalSince(lastScrollTime) > 0.5 {\n lastScrollTime = now\n proxy.scrollTo(messages.suffix(100).last?.id, anchor: .bottom)\n } else {\n scrollThrottleTimer?.invalidate()\n scrollThrottleTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in\n lastScrollTime = Date()\n proxy.scrollTo(messages.suffix(100).last?.id, anchor: .bottom)\n }\n }\n }\n }\n .onAppear {\n // Also check when view appears\n if let peerID = privatePeer {\n // Try multiple times to ensure read receipts are sent\n viewModel.markPrivateMessagesAsRead(from: peerID)\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {\n viewModel.markPrivateMessagesAsRead(from: peerID)\n }\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {\n viewModel.markPrivateMessagesAsRead(from: peerID)\n }\n }\n }\n }\n }\n \n // MARK: - Input View\n \n private var inputView: some View {\n VStack(spacing: 0) {\n // @mentions autocomplete\n if viewModel.showAutocomplete && !viewModel.autocompleteSuggestions.isEmpty {\n VStack(alignment: .leading, spacing: 0) {\n ForEach(viewModel.autocompleteSuggestions, id: \\.self) { suggestion in\n Button(action: {\n _ = viewModel.completeNickname(suggestion, in: &messageText)\n }) {\n HStack {\n Text(\"@\\(suggestion)\")\n .font(.system(size: 11, design: .monospaced))\n .foregroundColor(textColor)\n .fontWeight(.medium)\n Spacer()\n }\n .padding(.horizontal, 12)\n .padding(.vertical, 3)\n .frame(maxWidth: .infinity, alignment: .leading)\n }\n .buttonStyle(.plain)\n .background(Color.gray.opacity(0.1))\n }\n }\n .background(backgroundColor)\n .overlay(\n RoundedRectangle(cornerRadius: 4)\n .stroke(secondaryTextColor.opacity(0.3), lineWidth: 1)\n )\n .padding(.horizontal, 12)\n }\n \n // Command suggestions\n if showCommandSuggestions && !commandSuggestions.isEmpty {\n VStack(alignment: .leading, spacing: 0) {\n // Define commands with aliases and syntax\n let commandInfo: [(commands: [String], syntax: String?, description: String)] = [\n ([\"/block\"], \"[nickname]\", \"block or list blocked peers\"),\n ([\"/clear\"], nil, \"clear chat messages\"),\n ([\"/hug\"], \"\", \"send someone a warm hug\"),\n ([\"/m\", \"/msg\"], \" [message]\", \"send private message\"),\n ([\"/slap\"], \"\", \"slap someone with a trout\"),\n ([\"/unblock\"], \"\", \"unblock a peer\"),\n ([\"/w\"], nil, \"see who's online\")\n ]\n \n // Build the display\n let allCommands = commandInfo\n \n // Show matching commands\n ForEach(commandSuggestions, id: \\.self) { command in\n // Find the command info for this suggestion\n if let info = allCommands.first(where: { $0.commands.contains(command) }) {\n Button(action: {\n // Replace current text with selected command\n messageText = command + \" \"\n showCommandSuggestions = false\n commandSuggestions = []\n }) {\n HStack {\n // Show all aliases together\n Text(info.commands.joined(separator: \", \"))\n .font(.system(size: 11, design: .monospaced))\n .foregroundColor(textColor)\n .fontWeight(.medium)\n \n // Show syntax if any\n if let syntax = info.syntax {\n Text(syntax)\n .font(.system(size: 10, design: .monospaced))\n .foregroundColor(secondaryTextColor.opacity(0.8))\n }\n \n Spacer()\n \n // Show description\n Text(info.description)\n .font(.system(size: 10, design: .monospaced))\n .foregroundColor(secondaryTextColor)\n }\n .padding(.horizontal, 12)\n .padding(.vertical, 3)\n .frame(maxWidth: .infinity, alignment: .leading)\n }\n .buttonStyle(.plain)\n .background(Color.gray.opacity(0.1))\n }\n }\n }\n .background(backgroundColor)\n .overlay(\n RoundedRectangle(cornerRadius: 4)\n .stroke(secondaryTextColor.opacity(0.3), lineWidth: 1)\n )\n .padding(.horizontal, 12)\n }\n \n HStack(alignment: .center, spacing: 4) {\n TextField(\"type a message...\", text: $messageText)\n .textFieldStyle(.plain)\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(textColor)\n .focused($isTextFieldFocused)\n .padding(.leading, 12)\n .autocorrectionDisabled(true)\n #if os(iOS)\n .textInputAutocapitalization(.never)\n #endif\n .onChange(of: messageText) { newValue in\n // Cancel previous debounce timer\n autocompleteDebounceTimer?.invalidate()\n \n // Debounce autocomplete updates to reduce calls during rapid typing\n autocompleteDebounceTimer = Timer.scheduledTimer(withTimeInterval: 0.15, repeats: false) { _ in\n // Get cursor position (approximate - end of text for now)\n let cursorPosition = newValue.count\n viewModel.updateAutocomplete(for: newValue, cursorPosition: cursorPosition)\n }\n \n // Check for command autocomplete (instant, no debounce needed)\n if newValue.hasPrefix(\"/\") && newValue.count >= 1 {\n // Build context-aware command list\n let commandDescriptions = [\n (\"/block\", \"block or list blocked peers\"),\n (\"/clear\", \"clear chat messages\"),\n (\"/hug\", \"send someone a warm hug\"),\n (\"/m\", \"send private message\"),\n (\"/slap\", \"slap someone with a trout\"),\n (\"/unblock\", \"unblock a peer\"),\n (\"/w\", \"see who's online\")\n ]\n \n let input = newValue.lowercased()\n \n // Map of aliases to primary commands\n let aliases: [String: String] = [\n \"/join\": \"/j\",\n \"/msg\": \"/m\"\n ]\n \n // Filter commands, but convert aliases to primary\n commandSuggestions = commandDescriptions\n .filter { $0.0.starts(with: input) }\n .map { $0.0 }\n \n // Also check if input matches an alias\n for (alias, primary) in aliases {\n if alias.starts(with: input) && !commandSuggestions.contains(primary) {\n if commandDescriptions.contains(where: { $0.0 == primary }) {\n commandSuggestions.append(primary)\n }\n }\n }\n \n // Remove duplicates and sort\n commandSuggestions = Array(Set(commandSuggestions)).sorted()\n showCommandSuggestions = !commandSuggestions.isEmpty\n } else {\n showCommandSuggestions = false\n commandSuggestions = []\n }\n }\n .onSubmit {\n sendMessage()\n }\n \n Button(action: sendMessage) {\n Image(systemName: \"arrow.up.circle.fill\")\n .font(.system(size: 20))\n .foregroundColor(messageText.isEmpty ? Color.gray :\n viewModel.selectedPrivateChatPeer != nil\n ? Color.orange : textColor)\n }\n .buttonStyle(.plain)\n .padding(.trailing, 12)\n .accessibilityLabel(\"Send message\")\n .accessibilityHint(messageText.isEmpty ? \"Enter a message to send\" : \"Double tap to send\")\n }\n .padding(.vertical, 8)\n .background(backgroundColor.opacity(0.95))\n }\n .onAppear {\n // Delay keyboard focus to avoid iOS constraint warnings\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {\n isTextFieldFocused = true\n }\n }\n }\n \n // MARK: - Actions\n \n private func sendMessage() {\n viewModel.sendMessage(messageText)\n messageText = \"\"\n }\n \n // MARK: - Sidebar View\n \n private var sidebarView: some View {\n HStack(spacing: 0) {\n // Grey vertical bar for visual continuity\n Rectangle()\n .fill(Color.gray.opacity(0.3))\n .frame(width: 1)\n \n VStack(alignment: .leading, spacing: 0) {\n // Header - match main toolbar height\n HStack {\n Text(\"NETWORK\")\n .font(.system(size: 16, weight: .bold, design: .monospaced))\n .foregroundColor(textColor)\n Spacer()\n }\n .frame(height: 44) // Match header height\n .padding(.horizontal, 12)\n .background(backgroundColor.opacity(0.95))\n \n Divider()\n \n // Rooms and People list\n ScrollView {\n VStack(alignment: .leading, spacing: 12) {\n // People section\n VStack(alignment: .leading, spacing: 8) {\n // Show appropriate header based on context\n if !viewModel.connectedPeers.isEmpty {\n HStack(spacing: 4) {\n Image(systemName: \"person.2.fill\")\n .font(.system(size: 10))\n .accessibilityHidden(true)\n Text(\"PEOPLE\")\n .font(.system(size: 11, weight: .bold, design: .monospaced))\n }\n .foregroundColor(secondaryTextColor)\n .padding(.horizontal, 12)\n }\n \n if viewModel.connectedPeers.isEmpty {\n Text(\"nobody around...\")\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(secondaryTextColor)\n .padding(.horizontal)\n } else {\n // Extract peer data for display\n let peerNicknames = viewModel.meshService.getPeerNicknames()\n let peerRSSI = viewModel.meshService.getPeerRSSI()\n let myPeerID = viewModel.meshService.myPeerID\n \n // Show all connected peers\n let peersToShow: [String] = viewModel.connectedPeers\n let _ = print(\"ContentView: Showing \\(peersToShow.count) peers: \\(peersToShow.joined(separator: \", \"))\")\n \n // Pre-compute peer data outside ForEach to reduce overhead\n let peerData = peersToShow.map { peerID in\n let rssiValue = peerRSSI[peerID]?.intValue\n if rssiValue == nil {\n print(\"ContentView: No RSSI for peer \\(peerID) in dictionary with \\(peerRSSI.count) entries\")\n print(\"ContentView: peerRSSI keys: \\(peerRSSI.keys.joined(separator: \", \"))\")\n } else {\n print(\"ContentView: RSSI for peer \\(peerID) is \\(rssiValue!)\")\n }\n return PeerDisplayData(\n id: peerID,\n displayName: peerID == myPeerID ? viewModel.nickname : (peerNicknames[peerID] ?? \"anon\\(peerID.prefix(4))\"),\n rssi: rssiValue,\n isFavorite: viewModel.isFavorite(peerID: peerID),\n isMe: peerID == myPeerID,\n hasUnreadMessages: viewModel.unreadPrivateMessages.contains(peerID),\n encryptionStatus: viewModel.getEncryptionStatus(for: peerID)\n )\n }.sorted { (peer1: PeerDisplayData, peer2: PeerDisplayData) in\n // Sort: favorites first, then alphabetically by nickname\n if peer1.isFavorite != peer2.isFavorite {\n return peer1.isFavorite\n }\n return peer1.displayName < peer2.displayName\n }\n \n ForEach(peerData) { peer in\n HStack(spacing: 8) {\n // Signal strength indicator or unread message icon\n if peer.isMe {\n Image(systemName: \"person.fill\")\n .font(.system(size: 10))\n .foregroundColor(textColor)\n .accessibilityLabel(\"You\")\n } else if peer.hasUnreadMessages {\n Image(systemName: \"envelope.fill\")\n .font(.system(size: 12))\n .foregroundColor(Color.orange)\n .accessibilityLabel(\"Unread message from \\(peer.displayName)\")\n } else if let rssi = peer.rssi {\n Image(systemName: \"circle.fill\")\n .font(.system(size: 8))\n .foregroundColor(viewModel.getRSSIColor(rssi: rssi, colorScheme: colorScheme))\n .accessibilityLabel(\"Signal strength: \\(rssi > -60 ? \"excellent\" : rssi > -70 ? \"good\" : rssi > -80 ? \"fair\" : \"poor\")\")\n } else {\n // No RSSI data available\n Image(systemName: \"circle\")\n .font(.system(size: 8))\n .foregroundColor(Color.secondary.opacity(0.5))\n .accessibilityLabel(\"Signal strength: unknown\")\n }\n \n // Peer name\n if peer.isMe {\n HStack {\n Text(peer.displayName + \" (you)\")\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(textColor)\n \n Spacer()\n }\n } else {\n Text(peer.displayName)\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(peerNicknames[peer.id] != nil ? textColor : secondaryTextColor)\n \n // Encryption status icon (after peer name)\n if let icon = peer.encryptionStatus.icon {\n Image(systemName: icon)\n .font(.system(size: 10))\n .foregroundColor(peer.encryptionStatus == .noiseVerified ? Color.green : \n peer.encryptionStatus == .noiseSecured ? textColor :\n peer.encryptionStatus == .noiseHandshaking ? Color.orange :\n Color.red)\n .accessibilityLabel(\"Encryption: \\(peer.encryptionStatus == .noiseVerified ? \"verified\" : peer.encryptionStatus == .noiseSecured ? \"secured\" : peer.encryptionStatus == .noiseHandshaking ? \"establishing\" : \"none\")\")\n }\n \n Spacer()\n \n // Favorite star\n Button(action: {\n viewModel.toggleFavorite(peerID: peer.id)\n }) {\n Image(systemName: peer.isFavorite ? \"star.fill\" : \"star\")\n .font(.system(size: 12))\n .foregroundColor(peer.isFavorite ? Color.yellow : secondaryTextColor)\n }\n .buttonStyle(.plain)\n .accessibilityLabel(peer.isFavorite ? \"Remove \\(peer.displayName) from favorites\" : \"Add \\(peer.displayName) to favorites\")\n }\n }\n .padding(.horizontal)\n .padding(.vertical, 8)\n .contentShape(Rectangle())\n .onTapGesture {\n if !peer.isMe && peerNicknames[peer.id] != nil {\n viewModel.startPrivateChat(with: peer.id)\n withAnimation(.easeInOut(duration: 0.2)) {\n showSidebar = false\n sidebarDragOffset = 0\n }\n }\n }\n .onTapGesture(count: 2) {\n if !peer.isMe {\n // Show fingerprint on double tap\n viewModel.showFingerprint(for: peer.id)\n }\n }\n }\n }\n }\n }\n .padding(.vertical, 8)\n }\n \n Spacer()\n }\n .background(backgroundColor)\n }\n }\n \n // MARK: - View Components\n \n private var mainChatView: some View {\n VStack(spacing: 0) {\n mainHeaderView\n Divider()\n messagesView(privatePeer: nil)\n Divider()\n inputView\n }\n .background(backgroundColor)\n .foregroundColor(textColor)\n .gesture(\n DragGesture()\n .onChanged { value in\n let translation = value.translation.width.isNaN ? 0 : value.translation.width\n if !showSidebar && translation < 0 {\n sidebarDragOffset = max(translation, -300)\n } else if showSidebar && translation > 0 {\n sidebarDragOffset = min(-300 + translation, 0)\n }\n }\n .onEnded { value in\n let translation = value.translation.width.isNaN ? 0 : value.translation.width\n let velocity = value.velocity.width.isNaN ? 0 : value.velocity.width\n withAnimation(.easeOut(duration: 0.2)) {\n if !showSidebar {\n if translation < -100 || (translation < -50 && velocity < -500) {\n showSidebar = true\n sidebarDragOffset = 0\n } else {\n sidebarDragOffset = 0\n }\n } else {\n if translation > 100 || (translation > 50 && velocity > 500) {\n showSidebar = false\n sidebarDragOffset = 0\n } else {\n sidebarDragOffset = 0\n }\n }\n }\n }\n )\n }\n \n private var privateChatView: some View {\n HStack(spacing: 0) {\n // Vertical separator bar\n Rectangle()\n .fill(Color.gray.opacity(0.3))\n .frame(width: 1)\n \n VStack(spacing: 0) {\n privateHeaderView\n Divider()\n messagesView(privatePeer: viewModel.selectedPrivateChatPeer)\n Divider()\n inputView\n }\n .background(backgroundColor)\n .foregroundColor(textColor)\n }\n }\n \n \n private var mainHeaderView: some View {\n HStack(spacing: 0) {\n Text(\"bitchat/\")\n .font(.system(size: 18, weight: .medium, design: .monospaced))\n .foregroundColor(textColor)\n .onTapGesture(count: 3) {\n // PANIC: Triple-tap to clear all data\n viewModel.panicClearAllData()\n }\n .onTapGesture(count: 1) {\n // Single tap for app info\n showAppInfo = true\n }\n \n HStack(spacing: 0) {\n Text(\"@\")\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(secondaryTextColor)\n \n TextField(\"nickname\", text: $viewModel.nickname)\n .textFieldStyle(.plain)\n .font(.system(size: 14, design: .monospaced))\n .frame(maxWidth: 100)\n .foregroundColor(textColor)\n .focused($isNicknameFieldFocused)\n .autocorrectionDisabled(true)\n #if os(iOS)\n .textInputAutocapitalization(.never)\n #endif\n .onChange(of: isNicknameFieldFocused) { isFocused in\n if !isFocused {\n // Only validate when losing focus\n viewModel.validateAndSaveNickname()\n }\n }\n .onSubmit {\n viewModel.validateAndSaveNickname()\n }\n }\n \n Spacer()\n \n // People counter with unread indicator\n HStack(spacing: 4) {\n if !viewModel.unreadPrivateMessages.isEmpty {\n Image(systemName: \"envelope.fill\")\n .font(.system(size: 12))\n .foregroundColor(Color.orange)\n .accessibilityLabel(\"Unread private messages\")\n }\n \n let otherPeersCount = viewModel.connectedPeers.filter { $0 != viewModel.meshService.myPeerID }.count\n \n HStack(spacing: 4) {\n // People icon with count\n Image(systemName: \"person.2.fill\")\n .font(.system(size: 11))\n .accessibilityLabel(\"\\(otherPeersCount) connected \\(otherPeersCount == 1 ? \"person\" : \"people\")\")\n Text(\"\\(otherPeersCount)\")\n .font(.system(size: 12, design: .monospaced))\n .accessibilityHidden(true)\n }\n .foregroundColor(viewModel.isConnected ? textColor : Color.red)\n }\n .onTapGesture {\n withAnimation(.easeInOut(duration: 0.2)) {\n showSidebar.toggle()\n sidebarDragOffset = 0\n }\n }\n }\n .frame(height: 44)\n .padding(.horizontal, 12)\n .background(backgroundColor.opacity(0.95))\n }\n \n private var privateHeaderView: some View {\n Group {\n if let privatePeerID = viewModel.selectedPrivateChatPeer,\n let privatePeerNick = viewModel.meshService.getPeerNicknames()[privatePeerID] {\n HStack {\n Button(action: {\n withAnimation(.easeInOut(duration: 0.2)) {\n showPrivateChat = false\n viewModel.endPrivateChat()\n }\n }) {\n HStack(spacing: 4) {\n Image(systemName: \"chevron.left\")\n .font(.system(size: 12))\n Text(\"back\")\n .font(.system(size: 14, design: .monospaced))\n }\n .foregroundColor(textColor)\n }\n .buttonStyle(.plain)\n .accessibilityLabel(\"Back to main chat\")\n \n Spacer()\n \n Button(action: {\n viewModel.showFingerprint(for: privatePeerID)\n }) {\n HStack(spacing: 6) {\n Text(\"\\(privatePeerNick)\")\n .font(.system(size: 16, weight: .medium, design: .monospaced))\n .foregroundColor(Color.orange)\n // Dynamic encryption status icon\n let encryptionStatus = viewModel.getEncryptionStatus(for: privatePeerID)\n if let icon = encryptionStatus.icon {\n Image(systemName: icon)\n .font(.system(size: 14))\n .foregroundColor(encryptionStatus == .noiseVerified ? Color.green : \n encryptionStatus == .noiseSecured ? Color.orange :\n Color.red)\n .accessibilityLabel(\"Encryption status: \\(encryptionStatus == .noiseVerified ? \"verified\" : encryptionStatus == .noiseSecured ? \"secured\" : \"not encrypted\")\")\n }\n }\n .frame(maxWidth: .infinity)\n .accessibilityLabel(\"Private chat with \\(privatePeerNick)\")\n .accessibilityHint(\"Tap to view encryption fingerprint\")\n }\n .buttonStyle(.plain)\n \n Spacer()\n \n // Favorite button\n Button(action: {\n viewModel.toggleFavorite(peerID: privatePeerID)\n }) {\n Image(systemName: viewModel.isFavorite(peerID: privatePeerID) ? \"star.fill\" : \"star\")\n .font(.system(size: 16))\n .foregroundColor(viewModel.isFavorite(peerID: privatePeerID) ? Color.yellow : textColor)\n }\n .buttonStyle(.plain)\n .accessibilityLabel(viewModel.isFavorite(peerID: privatePeerID) ? \"Remove from favorites\" : \"Add to favorites\")\n .accessibilityHint(\"Double tap to toggle favorite status\")\n }\n .frame(height: 44)\n .padding(.horizontal, 12)\n .background(backgroundColor.opacity(0.95))\n } else {\n EmptyView()\n }\n }\n }\n \n}\n\n// MARK: - Helper Views\n\n// Helper view for rendering message content with clickable hashtags\nstruct MessageContentView: View {\n let message: BitchatMessage\n let viewModel: ChatViewModel\n let colorScheme: ColorScheme\n let isMentioned: Bool\n \n var body: some View {\n let content = message.content\n let hashtagPattern = \"#([a-zA-Z0-9_]+)\"\n let mentionPattern = \"@([a-zA-Z0-9_]+)\"\n \n let hashtagRegex = try? NSRegularExpression(pattern: hashtagPattern, options: [])\n let mentionRegex = try? NSRegularExpression(pattern: mentionPattern, options: [])\n \n let hashtagMatches = hashtagRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n let mentionMatches = mentionRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n \n // Combine all matches and sort by location\n var allMatches: [(range: NSRange, type: String)] = []\n for match in hashtagMatches {\n allMatches.append((match.range(at: 0), \"hashtag\"))\n }\n for match in mentionMatches {\n allMatches.append((match.range(at: 0), \"mention\"))\n }\n allMatches.sort { $0.range.location < $1.range.location }\n \n // Build the text as a concatenated Text view for natural wrapping\n let segments = buildTextSegments()\n var result = Text(\"\")\n \n for segment in segments {\n if segment.type == \"hashtag\" {\n // Note: We can't have clickable links in concatenated Text, so hashtags won't be clickable\n result = result + Text(segment.text)\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(Color.blue)\n .underline()\n } else if segment.type == \"mention\" {\n result = result + Text(segment.text)\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(Color.orange)\n } else {\n result = result + Text(segment.text)\n .font(.system(size: 14, design: .monospaced))\n .fontWeight(isMentioned ? .bold : .regular)\n }\n }\n \n return result\n .textSelection(.enabled)\n }\n \n // MARK: - Helper Methods\n \n private func buildTextSegments() -> [(text: String, type: String)] {\n var segments: [(text: String, type: String)] = []\n let content = message.content\n var lastEnd = content.startIndex\n \n let hashtagPattern = \"#([a-zA-Z0-9_]+)\"\n let mentionPattern = \"@([a-zA-Z0-9_]+)\"\n \n let hashtagRegex = try? NSRegularExpression(pattern: hashtagPattern, options: [])\n let mentionRegex = try? NSRegularExpression(pattern: mentionPattern, options: [])\n \n let hashtagMatches = hashtagRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n let mentionMatches = mentionRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n \n // Combine all matches and sort by location\n var allMatches: [(range: NSRange, type: String)] = []\n for match in hashtagMatches {\n allMatches.append((match.range(at: 0), \"hashtag\"))\n }\n for match in mentionMatches {\n allMatches.append((match.range(at: 0), \"mention\"))\n }\n allMatches.sort { $0.range.location < $1.range.location }\n \n for (matchRange, matchType) in allMatches {\n if let range = Range(matchRange, in: content) {\n // Add text before the match\n if lastEnd < range.lowerBound {\n let beforeText = String(content[lastEnd..\n//\n\nimport SwiftUI\n#if os(iOS)\nimport LinkPresentation\nimport UIKit\n#endif\n\n// MARK: - Link Metadata Cache\n\n/// Cache for link metadata to prevent repeated network requests\nprivate class LinkMetadataCache {\n static let shared = LinkMetadataCache()\n \n #if os(iOS)\n private let cache = NSCache()\n private let imageCache = NSCache()\n #endif\n private let queue = DispatchQueue(label: \"chat.bitchat.linkmetadata.cache\", attributes: .concurrent)\n \n private init() {\n #if os(iOS)\n cache.countLimit = 100 // Keep metadata for up to 100 URLs\n imageCache.countLimit = 50 // Keep images for up to 50 URLs\n imageCache.totalCostLimit = 50 * 1024 * 1024 // 50MB limit for images\n #endif\n }\n \n #if os(iOS)\n class CachedMetadata {\n let metadata: LPLinkMetadata?\n let title: String?\n let host: String?\n let error: Error?\n let timestamp: Date\n \n init(metadata: LPLinkMetadata? = nil, title: String? = nil, host: String? = nil, error: Error? = nil) {\n self.metadata = metadata\n self.title = title\n self.host = host\n self.error = error\n self.timestamp = Date()\n }\n }\n \n func getCachedMetadata(for url: URL) -> (metadata: LPLinkMetadata?, title: String?, host: String?, image: UIImage?)? {\n return queue.sync {\n guard let cached = cache.object(forKey: url as NSURL) else { return nil }\n \n // Check if cache is older than 24 hours\n if Date().timeIntervalSince(cached.timestamp) > 86400 {\n cache.removeObject(forKey: url as NSURL)\n imageCache.removeObject(forKey: url as NSURL)\n return nil\n }\n \n let image = imageCache.object(forKey: url as NSURL)\n return (cached.metadata, cached.title, cached.host, image)\n }\n }\n \n func cacheMetadata(_ metadata: LPLinkMetadata?, title: String?, host: String?, image: UIImage?, for url: URL) {\n queue.async(flags: .barrier) {\n let cached = CachedMetadata(metadata: metadata, title: title, host: host)\n self.cache.setObject(cached, forKey: url as NSURL)\n \n if let image = image {\n let cost = Int(image.size.width * image.size.height * 4) // Approximate memory usage\n self.imageCache.setObject(image, forKey: url as NSURL, cost: cost)\n }\n }\n }\n \n func cacheError(_ error: Error, for url: URL) {\n queue.async(flags: .barrier) {\n let cached = CachedMetadata(error: error)\n self.cache.setObject(cached, forKey: url as NSURL)\n }\n }\n #endif\n \n func clearCache() {\n queue.async(flags: .barrier) {\n #if os(iOS)\n self.cache.removeAllObjects()\n self.imageCache.removeAllObjects()\n #endif\n }\n }\n}\n\n// MARK: - Link Preview View\n\nstruct LinkPreviewView: View {\n let url: URL\n let title: String?\n @Environment(\\.colorScheme) var colorScheme\n #if os(iOS)\n @State private var metadata: LPLinkMetadata?\n @State private var cachedTitle: String?\n @State private var cachedHost: String?\n @State private var isLoading = false\n #endif\n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n private var backgroundColor: Color {\n colorScheme == .dark ? Color.black : Color.white\n }\n \n private var borderColor: Color {\n textColor.opacity(0.3)\n }\n \n var body: some View {\n // Always use our custom compact view for consistent appearance\n compactLinkView\n .onAppear {\n loadFromCacheOrFetch()\n }\n }\n \n #if os(iOS)\n @State private var previewImage: UIImage? = nil\n #endif\n \n private var compactLinkView: some View {\n Button(action: {\n #if os(iOS)\n UIApplication.shared.open(url)\n #else\n NSWorkspace.shared.open(url)\n #endif\n }) {\n HStack(spacing: 12) {\n // Preview image or icon\n Group {\n #if os(iOS)\n if let image = previewImage {\n Image(uiImage: image)\n .resizable()\n .aspectRatio(contentMode: .fill)\n .frame(width: 60, height: 60)\n .clipped()\n .cornerRadius(8)\n } else {\n // Favicon or default icon\n RoundedRectangle(cornerRadius: 8)\n .fill(Color.blue.opacity(0.1))\n .frame(width: 60, height: 60)\n .overlay(\n Image(systemName: \"link\")\n .font(.system(size: 24))\n .foregroundColor(Color.blue)\n )\n }\n #else\n RoundedRectangle(cornerRadius: 8)\n .fill(Color.blue.opacity(0.1))\n .frame(width: 60, height: 60)\n .overlay(\n Image(systemName: \"link\")\n .font(.system(size: 24))\n .foregroundColor(Color.blue)\n )\n #endif\n }\n \n VStack(alignment: .leading, spacing: 4) {\n // Title\n #if os(iOS)\n Text(cachedTitle ?? metadata?.title ?? title ?? url.host ?? \"Link\")\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(textColor)\n .lineLimit(2)\n .multilineTextAlignment(.leading)\n #else\n Text(title ?? url.host ?? \"Link\")\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(textColor)\n .lineLimit(2)\n .multilineTextAlignment(.leading)\n #endif\n \n // Host\n #if os(iOS)\n Text(cachedHost ?? url.host ?? url.absoluteString)\n .font(.system(size: 11, design: .monospaced))\n .foregroundColor(textColor.opacity(0.6))\n .lineLimit(1)\n #else\n Text(url.host ?? url.absoluteString)\n .font(.system(size: 11, design: .monospaced))\n .foregroundColor(textColor.opacity(0.6))\n .lineLimit(1)\n #endif\n }\n \n Spacer()\n }\n .padding(10)\n .frame(maxWidth: .infinity, alignment: .leading)\n .background(\n RoundedRectangle(cornerRadius: 10)\n .fill(colorScheme == .dark ? Color.gray.opacity(0.15) : Color.gray.opacity(0.08))\n )\n .overlay(\n RoundedRectangle(cornerRadius: 10)\n .stroke(borderColor, lineWidth: 1)\n )\n }\n .buttonStyle(.plain)\n }\n \n private var simpleLinkView: some View {\n Button(action: {\n #if os(iOS)\n UIApplication.shared.open(url)\n #else\n NSWorkspace.shared.open(url)\n #endif\n }) {\n HStack(spacing: 12) {\n // Link icon\n Image(systemName: \"link.circle.fill\")\n .font(.system(size: 32))\n .foregroundColor(Color.blue.opacity(0.8))\n .frame(width: 40, height: 40)\n \n VStack(alignment: .leading, spacing: 4) {\n // Title\n Text(title ?? url.host ?? \"Link\")\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(textColor)\n .lineLimit(2)\n .multilineTextAlignment(.leading)\n \n // URL\n Text(url.absoluteString)\n .font(.system(size: 11, design: .monospaced))\n .foregroundColor(Color.blue)\n .lineLimit(1)\n .truncationMode(.middle)\n }\n \n Spacer()\n \n // Arrow indicator\n Image(systemName: \"chevron.right\")\n .font(.system(size: 14))\n .foregroundColor(textColor.opacity(0.5))\n }\n .padding(12)\n .frame(maxWidth: .infinity, alignment: .leading)\n .background(\n RoundedRectangle(cornerRadius: 10)\n .fill(colorScheme == .dark ? Color.gray.opacity(0.15) : Color.gray.opacity(0.08))\n )\n .overlay(\n RoundedRectangle(cornerRadius: 10)\n .stroke(borderColor, lineWidth: 1)\n )\n }\n .buttonStyle(.plain)\n }\n \n private func loadFromCacheOrFetch() {\n #if os(iOS)\n // Check if we already have data in state\n guard metadata == nil && !isLoading else { \n return \n }\n \n // Check cache first\n if let cached = LinkMetadataCache.shared.getCachedMetadata(for: url) {\n // print(\"🔗 LinkPreviewView: Using CACHED metadata for: \\(url.absoluteString)\")\n self.metadata = cached.metadata\n self.cachedTitle = cached.title ?? cached.metadata?.title\n self.cachedHost = cached.host ?? url.host\n self.previewImage = cached.image\n return\n }\n \n // Not in cache, fetch it\n // print(\"🔗 LinkPreviewView: FETCHING metadata for: \\(url.absoluteString)\")\n isLoading = true\n \n let provider = LPMetadataProvider()\n provider.startFetchingMetadata(for: url) { fetchedMetadata, error in\n DispatchQueue.main.async {\n self.isLoading = false\n \n if let error = error {\n // Check if it's an ATS error for subresources (non-critical)\n let errorString = error.localizedDescription.lowercased()\n let isATSError = errorString.contains(\"app transport security\") || \n errorString.contains(\"secure connection\")\n \n if !isATSError {\n // Only log non-ATS errors\n // print(\"🔗 LinkPreviewView: Error fetching metadata: \\(error)\")\n }\n \n // Still try to show basic preview with URL info\n self.cachedTitle = self.title ?? self.url.host\n self.cachedHost = self.url.host\n \n // Cache even failed attempts to avoid repeated fetches\n LinkMetadataCache.shared.cacheMetadata(\n nil,\n title: self.cachedTitle,\n host: self.cachedHost,\n image: nil,\n for: self.url\n )\n return\n }\n \n if let fetchedMetadata = fetchedMetadata {\n // Use the fetched metadata, or create new with our title\n if let title = self.title, !title.isEmpty {\n fetchedMetadata.title = title\n }\n self.metadata = fetchedMetadata\n self.cachedTitle = fetchedMetadata.title ?? self.title\n self.cachedHost = self.url.host\n \n // Try to extract image\n if let imageProvider = fetchedMetadata.imageProvider {\n imageProvider.loadObject(ofClass: UIImage.self) { image, error in\n DispatchQueue.main.async {\n if let image = image as? UIImage {\n self.previewImage = image\n // Cache everything including the image\n LinkMetadataCache.shared.cacheMetadata(\n fetchedMetadata,\n title: self.cachedTitle,\n host: self.cachedHost,\n image: image,\n for: self.url\n )\n } else {\n // Cache without image\n LinkMetadataCache.shared.cacheMetadata(\n fetchedMetadata,\n title: self.cachedTitle,\n host: self.cachedHost,\n image: nil,\n for: self.url\n )\n }\n }\n }\n } else {\n // No image, cache what we have\n LinkMetadataCache.shared.cacheMetadata(\n fetchedMetadata,\n title: self.cachedTitle,\n host: self.cachedHost,\n image: nil,\n for: self.url\n )\n }\n }\n }\n }\n #endif\n }\n}\n\n#if os(iOS)\n// UIViewRepresentable wrapper for LPLinkView\nstruct LinkPreview: UIViewRepresentable {\n let metadata: LPLinkMetadata\n \n func makeUIView(context: Context) -> UIView {\n let containerView = UIView()\n containerView.backgroundColor = .clear\n \n let linkView = LPLinkView(metadata: metadata)\n linkView.isUserInteractionEnabled = false // We handle taps at the SwiftUI level\n linkView.translatesAutoresizingMaskIntoConstraints = false\n \n containerView.addSubview(linkView)\n NSLayoutConstraint.activate([\n linkView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),\n linkView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),\n linkView.topAnchor.constraint(equalTo: containerView.topAnchor),\n linkView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)\n ])\n \n return containerView\n }\n \n func updateUIView(_ uiView: UIView, context: Context) {\n // Update if needed\n }\n}\n#endif\n\n// Helper to extract URLs from text\nextension String {\n func extractURLs() -> [(url: URL, range: Range)] {\n var urls: [(URL, Range)] = []\n \n // Check for plain URLs\n let types: NSTextCheckingResult.CheckingType = .link\n if let detector = try? NSDataDetector(types: types.rawValue) {\n let matches = detector.matches(in: self, range: NSRange(location: 0, length: self.utf16.count))\n for match in matches {\n if let range = Range(match.range, in: self),\n let url = match.url {\n urls.append((url, range))\n }\n }\n }\n \n return urls\n }\n}\n\n#Preview {\n VStack {\n LinkPreviewView(url: URL(string: \"https://example.com\")!, title: \"Example Website\")\n .padding()\n }\n}\n"], ["/bitchat/bitchat/Views/AppInfoView.swift", "import SwiftUI\n\nstruct AppInfoView: View {\n @Environment(\\.dismiss) var dismiss\n @Environment(\\.colorScheme) var colorScheme\n \n private var backgroundColor: Color {\n colorScheme == .dark ? Color.black : Color.white\n }\n \n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n private var secondaryTextColor: Color {\n colorScheme == .dark ? Color.green.opacity(0.8) : Color(red: 0, green: 0.5, blue: 0).opacity(0.8)\n }\n \n // MARK: - Constants\n private enum Strings {\n static let appName = \"bitchat\"\n static let tagline = \"mesh sidegroupchat\"\n \n enum Features {\n static let title = \"FEATURES\"\n static let offlineComm = (\"wifi.slash\", \"offline communication\", \"works without internet using Bluetooth low energy\")\n static let encryption = (\"lock.shield\", \"end-to-end encryption\", \"private messages encrypted with noise protocol\")\n static let extendedRange = (\"antenna.radiowaves.left.and.right\", \"extended range\", \"messages relay through peers, going the distance\")\n static let favorites = (\"star.fill\", \"favorites\", \"get notified when your favorite people join\")\n static let mentions = (\"at\", \"mentions\", \"use @nickname to notify specific people\")\n }\n \n enum Privacy {\n static let title = \"PRIVACY\"\n static let noTracking = (\"eye.slash\", \"no tracking\", \"no servers, accounts, or data collection\")\n static let ephemeral = (\"shuffle\", \"ephemeral identity\", \"new peer ID generated regularly\")\n static let panic = (\"hand.raised.fill\", \"panic mode\", \"triple-tap logo to instantly clear all data\")\n }\n \n enum HowToUse {\n static let title = \"HOW TO USE\"\n static let instructions = [\n \"• set your nickname by tapping it\",\n \"• swipe left for sidebar\",\n \"• tap a peer to start a private chat\",\n \"• use @nickname to mention someone\",\n \"• triple-tap chat to clear\"\n ]\n }\n \n enum Warning {\n static let title = \"WARNING\"\n static let message = \"private message security has not yet been fully audited. do not use for critical situations until this warning disappears.\"\n }\n }\n \n var body: some View {\n #if os(macOS)\n VStack(spacing: 0) {\n // Custom header for macOS\n HStack {\n Spacer()\n Button(\"DONE\") {\n dismiss()\n }\n .buttonStyle(.plain)\n .foregroundColor(textColor)\n .padding()\n }\n .background(backgroundColor.opacity(0.95))\n \n ScrollView {\n infoContent\n }\n .background(backgroundColor)\n }\n .frame(width: 600, height: 700)\n #else\n NavigationView {\n ScrollView {\n infoContent\n }\n .background(backgroundColor)\n .navigationBarTitleDisplayMode(.inline)\n .toolbar {\n ToolbarItem(placement: .navigationBarTrailing) {\n Button(\"DONE\") {\n dismiss()\n }\n .foregroundColor(textColor)\n }\n }\n }\n #endif\n }\n \n @ViewBuilder\n private var infoContent: some View {\n VStack(alignment: .leading, spacing: 24) {\n // Header\n VStack(alignment: .center, spacing: 8) {\n Text(Strings.appName)\n .font(.system(size: 32, weight: .bold, design: .monospaced))\n .foregroundColor(textColor)\n \n Text(Strings.tagline)\n .font(.system(size: 16, design: .monospaced))\n .foregroundColor(secondaryTextColor)\n }\n .frame(maxWidth: .infinity)\n .padding(.vertical)\n \n // Features\n VStack(alignment: .leading, spacing: 16) {\n SectionHeader(Strings.Features.title)\n \n FeatureRow(icon: Strings.Features.offlineComm.0, \n title: Strings.Features.offlineComm.1,\n description: Strings.Features.offlineComm.2)\n \n FeatureRow(icon: Strings.Features.encryption.0,\n title: Strings.Features.encryption.1,\n description: Strings.Features.encryption.2)\n \n FeatureRow(icon: Strings.Features.extendedRange.0,\n title: Strings.Features.extendedRange.1,\n description: Strings.Features.extendedRange.2)\n \n FeatureRow(icon: Strings.Features.favorites.0,\n title: Strings.Features.favorites.1,\n description: Strings.Features.favorites.2)\n \n FeatureRow(icon: Strings.Features.mentions.0,\n title: Strings.Features.mentions.1,\n description: Strings.Features.mentions.2)\n }\n \n // Privacy\n VStack(alignment: .leading, spacing: 16) {\n SectionHeader(Strings.Privacy.title)\n \n FeatureRow(icon: Strings.Privacy.noTracking.0,\n title: Strings.Privacy.noTracking.1,\n description: Strings.Privacy.noTracking.2)\n \n FeatureRow(icon: Strings.Privacy.ephemeral.0,\n title: Strings.Privacy.ephemeral.1,\n description: Strings.Privacy.ephemeral.2)\n \n FeatureRow(icon: Strings.Privacy.panic.0,\n title: Strings.Privacy.panic.1,\n description: Strings.Privacy.panic.2)\n }\n \n // How to Use\n VStack(alignment: .leading, spacing: 16) {\n SectionHeader(Strings.HowToUse.title)\n \n VStack(alignment: .leading, spacing: 8) {\n ForEach(Strings.HowToUse.instructions, id: \\.self) { instruction in\n Text(instruction)\n }\n }\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(textColor)\n }\n \n // Warning\n VStack(alignment: .leading, spacing: 6) {\n SectionHeader(Strings.Warning.title)\n .foregroundColor(Color.red)\n \n Text(Strings.Warning.message)\n .font(.system(size: 14, design: .monospaced))\n .foregroundColor(Color.red)\n .fixedSize(horizontal: false, vertical: true)\n }\n .padding(.top, 6)\n .padding(.bottom, 16)\n .padding(.horizontal)\n .background(Color.red.opacity(0.1))\n .cornerRadius(8)\n \n .padding(.top)\n }\n .padding()\n }\n}\n\nstruct SectionHeader: View {\n let title: String\n @Environment(\\.colorScheme) var colorScheme\n \n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n init(_ title: String) {\n self.title = title\n }\n \n var body: some View {\n Text(title)\n .font(.system(size: 16, weight: .bold, design: .monospaced))\n .foregroundColor(textColor)\n .padding(.top, 8)\n }\n}\n\nstruct FeatureRow: View {\n let icon: String\n let title: String\n let description: String\n @Environment(\\.colorScheme) var colorScheme\n \n private var textColor: Color {\n colorScheme == .dark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n }\n \n private var secondaryTextColor: Color {\n colorScheme == .dark ? Color.green.opacity(0.8) : Color(red: 0, green: 0.5, blue: 0).opacity(0.8)\n }\n \n var body: some View {\n HStack(alignment: .top, spacing: 12) {\n Image(systemName: icon)\n .font(.system(size: 20))\n .foregroundColor(textColor)\n .frame(width: 30)\n \n VStack(alignment: .leading, spacing: 4) {\n Text(title)\n .font(.system(size: 14, weight: .semibold, design: .monospaced))\n .foregroundColor(textColor)\n \n Text(description)\n .font(.system(size: 12, design: .monospaced))\n .foregroundColor(secondaryTextColor)\n .fixedSize(horizontal: false, vertical: true)\n }\n \n Spacer()\n }\n }\n}\n\n#Preview {\n AppInfoView()\n}\n"], ["/bitchat/bitchat/ViewModels/ChatViewModel.swift", "//\n// ChatViewModel.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # ChatViewModel\n///\n/// The central business logic and state management component for BitChat.\n/// Coordinates between the UI layer and the networking/encryption services.\n///\n/// ## Overview\n/// ChatViewModel implements the MVVM pattern, serving as the binding layer between\n/// SwiftUI views and the underlying BitChat services. It manages:\n/// - Message state and delivery\n/// - Peer connections and presence\n/// - Private chat sessions\n/// - Command processing\n/// - UI state like autocomplete and notifications\n///\n/// ## Architecture\n/// The ViewModel acts as:\n/// - **BitchatDelegate**: Receives messages and events from BluetoothMeshService\n/// - **State Manager**: Maintains all UI-relevant state with @Published properties\n/// - **Command Processor**: Handles IRC-style commands (/msg, /who, etc.)\n/// - **Message Router**: Directs messages to appropriate chats (public/private)\n///\n/// ## Key Features\n///\n/// ### Message Management\n/// - Batches incoming messages for performance (100ms window)\n/// - Maintains separate public and private message queues\n/// - Limits message history to prevent memory issues (1337 messages)\n/// - Tracks delivery and read receipts\n///\n/// ### Privacy Features\n/// - Ephemeral by design - no persistent message storage\n/// - Supports verified fingerprints for secure communication\n/// - Blocks messages from blocked users\n/// - Emergency wipe capability (triple-tap)\n///\n/// ### User Experience\n/// - Smart autocomplete for mentions and commands\n/// - Unread message indicators\n/// - Connection status tracking\n/// - Favorite peers management\n///\n/// ## Command System\n/// Supports IRC-style commands:\n/// - `/nick `: Change nickname\n/// - `/msg `: Send private message\n/// - `/who`: List connected peers\n/// - `/slap `: Fun interaction\n/// - `/clear`: Clear message history\n/// - `/help`: Show available commands\n///\n/// ## Performance Optimizations\n/// - Message batching reduces UI updates\n/// - Caches expensive computations (RSSI colors, encryption status)\n/// - Debounces autocomplete suggestions\n/// - Efficient peer list management\n///\n/// ## Thread Safety\n/// - All @Published properties trigger UI updates on main thread\n/// - Background operations use proper queue management\n/// - Atomic operations for critical state updates\n///\n/// ## Usage Example\n/// ```swift\n/// let viewModel = ChatViewModel()\n/// viewModel.nickname = \"Alice\"\n/// viewModel.startServices()\n/// viewModel.sendMessage(\"Hello, mesh network!\")\n/// ```\n///\n\nimport Foundation\nimport SwiftUI\nimport Combine\nimport CryptoKit\nimport CommonCrypto\n#if os(iOS)\nimport UIKit\n#endif\n\n/// Manages the application state and business logic for BitChat.\n/// Acts as the primary coordinator between UI components and backend services,\n/// implementing the BitchatDelegate protocol to handle network events.\nclass ChatViewModel: ObservableObject {\n // MARK: - Published Properties\n \n @Published var messages: [BitchatMessage] = []\n private let maxMessages = 1337 // Maximum messages before oldest are removed\n @Published var connectedPeers: [String] = []\n \n // MARK: - Message Batching Properties\n \n // Message batching for performance\n private var pendingMessages: [BitchatMessage] = []\n private var pendingPrivateMessages: [String: [BitchatMessage]] = [:] // peerID -> messages\n private var messageBatchTimer: Timer?\n private let messageBatchInterval: TimeInterval = 0.1 // 100ms batching window\n @Published var nickname: String = \"\" {\n didSet {\n // Trim whitespace whenever nickname is set\n let trimmed = nickname.trimmingCharacters(in: .whitespacesAndNewlines)\n if trimmed != nickname {\n nickname = trimmed\n }\n }\n }\n @Published var isConnected = false\n @Published var privateChats: [String: [BitchatMessage]] = [:] // peerID -> messages\n @Published var selectedPrivateChatPeer: String? = nil\n private var selectedPrivateChatFingerprint: String? = nil // Track by fingerprint for persistence across reconnections\n @Published var unreadPrivateMessages: Set = []\n @Published var autocompleteSuggestions: [String] = []\n @Published var showAutocomplete: Bool = false\n @Published var autocompleteRange: NSRange? = nil\n @Published var selectedAutocompleteIndex: Int = 0\n \n // MARK: - Autocomplete Properties\n \n // Autocomplete optimization\n private let mentionRegex = try? NSRegularExpression(pattern: \"@([a-zA-Z0-9_]*)$\", options: [])\n private var cachedNicknames: [String] = []\n private var lastNicknameUpdate: Date = .distantPast\n \n // Temporary property to fix compilation\n @Published var showPasswordPrompt = false\n \n // MARK: - Services and Storage\n \n var meshService = BluetoothMeshService()\n private let userDefaults = UserDefaults.standard\n private let nicknameKey = \"bitchat.nickname\"\n \n // MARK: - Caches\n \n // Caches for expensive computations\n private var rssiColorCache: [String: Color] = [:] // key: \"\\(rssi)_\\(isDark)\"\n private var encryptionStatusCache: [String: EncryptionStatus] = [:] // key: peerID\n \n // MARK: - Social Features\n \n @Published var favoritePeers: Set = [] // Now stores public key fingerprints instead of peer IDs\n private var peerIDToPublicKeyFingerprint: [String: String] = [:] // Maps ephemeral peer IDs to persistent fingerprints\n private var blockedUsers: Set = [] // Stores public key fingerprints of blocked users\n \n // MARK: - Encryption and Security\n \n // Noise Protocol encryption status\n @Published var peerEncryptionStatus: [String: EncryptionStatus] = [:] // peerID -> encryption status\n @Published var verifiedFingerprints: Set = [] // Set of verified fingerprints\n @Published var showingFingerprintFor: String? = nil // Currently showing fingerprint sheet for peer\n \n // Messages are naturally ephemeral - no persistent storage\n \n // MARK: - Message Delivery Tracking\n \n // Delivery tracking\n private var deliveryTrackerCancellable: AnyCancellable?\n \n // Track sent read receipts to avoid duplicates\n private var sentReadReceipts: Set = [] // messageID set\n \n // MARK: - Initialization\n \n init() {\n loadNickname()\n loadFavorites()\n loadBlockedUsers()\n loadVerifiedFingerprints()\n meshService.delegate = self\n \n // Log startup info\n \n // Log fingerprint after a delay to ensure encryption service is ready\n DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in\n if let self = self {\n _ = self.getMyFingerprint()\n }\n }\n \n // Start mesh service immediately\n meshService.startServices()\n \n // Set up message retry service\n MessageRetryService.shared.meshService = meshService\n \n // Set up Noise encryption callbacks\n setupNoiseCallbacks()\n \n // Request notification permission\n NotificationService.shared.requestAuthorization()\n \n // Subscribe to delivery status updates\n deliveryTrackerCancellable = DeliveryTracker.shared.deliveryStatusUpdated\n .receive(on: DispatchQueue.main)\n .sink { [weak self] (messageID, status) in\n self?.updateMessageDeliveryStatus(messageID, status: status)\n }\n \n // Listen for retry notifications\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(handleRetryMessage),\n name: Notification.Name(\"bitchat.retryMessage\"),\n object: nil\n )\n \n // When app becomes active, send read receipts for visible messages\n #if os(macOS)\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appDidBecomeActive),\n name: NSApplication.didBecomeActiveNotification,\n object: nil\n )\n \n // Add app lifecycle observers to save data\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillResignActive),\n name: NSApplication.willResignActiveNotification,\n object: nil\n )\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillTerminate),\n name: NSApplication.willTerminateNotification,\n object: nil\n )\n #else\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appDidBecomeActive),\n name: UIApplication.didBecomeActiveNotification,\n object: nil\n )\n \n // Add screenshot detection for iOS\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(userDidTakeScreenshot),\n name: UIApplication.userDidTakeScreenshotNotification,\n object: nil\n )\n \n // Add app lifecycle observers to save data\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillResignActive),\n name: UIApplication.willResignActiveNotification,\n object: nil\n )\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillTerminate),\n name: UIApplication.willTerminateNotification,\n object: nil\n )\n #endif\n }\n \n // MARK: - Deinitialization\n \n deinit {\n // Clean up timer\n messageBatchTimer?.invalidate()\n \n // Force immediate save\n userDefaults.synchronize()\n }\n \n // MARK: - Nickname Management\n \n private func loadNickname() {\n if let savedNickname = userDefaults.string(forKey: nicknameKey) {\n // Trim whitespace when loading\n nickname = savedNickname.trimmingCharacters(in: .whitespacesAndNewlines)\n } else {\n nickname = \"anon\\(Int.random(in: 1000...9999))\"\n saveNickname()\n }\n }\n \n func saveNickname() {\n userDefaults.set(nickname, forKey: nicknameKey)\n userDefaults.synchronize() // Force immediate save\n \n // Send announce with new nickname to all peers\n meshService.sendBroadcastAnnounce()\n }\n \n func validateAndSaveNickname() {\n // Trim whitespace from nickname\n let trimmed = nickname.trimmingCharacters(in: .whitespacesAndNewlines)\n \n // Check if nickname is empty after trimming\n if trimmed.isEmpty {\n nickname = \"anon\\(Int.random(in: 1000...9999))\"\n } else {\n nickname = trimmed\n }\n saveNickname()\n }\n \n // MARK: - Favorites Management\n \n private func loadFavorites() {\n // Load favorites from secure storage\n favoritePeers = SecureIdentityStateManager.shared.getFavorites()\n }\n \n private func saveFavorites() {\n // Favorites are now saved automatically in SecureIdentityStateManager\n // This method is kept for compatibility\n }\n \n // MARK: - Blocked Users Management\n \n private func loadBlockedUsers() {\n // Load blocked users from secure storage\n let allIdentities = SecureIdentityStateManager.shared.getAllSocialIdentities()\n blockedUsers = Set(allIdentities.filter { $0.isBlocked }.map { $0.fingerprint })\n }\n \n private func saveBlockedUsers() {\n // Blocked users are now saved automatically in SecureIdentityStateManager\n // This method is kept for compatibility\n }\n \n \n func toggleFavorite(peerID: String) {\n // First try to get fingerprint from mesh service (supports peer ID rotation)\n var fingerprint: String? = meshService.getFingerprint(for: peerID)\n \n // Fallback to local mapping if not found in mesh service\n if fingerprint == nil {\n fingerprint = peerIDToPublicKeyFingerprint[peerID]\n }\n \n guard let fp = fingerprint else {\n return\n }\n \n let isFavorite = SecureIdentityStateManager.shared.isFavorite(fingerprint: fp)\n SecureIdentityStateManager.shared.setFavorite(fp, isFavorite: !isFavorite)\n \n // Update local set for UI\n if isFavorite {\n favoritePeers.remove(fp)\n } else {\n favoritePeers.insert(fp)\n }\n }\n \n func isFavorite(peerID: String) -> Bool {\n // First try to get fingerprint from mesh service (supports peer ID rotation)\n var fingerprint: String? = meshService.getFingerprint(for: peerID)\n \n // Fallback to local mapping if not found in mesh service\n if fingerprint == nil {\n fingerprint = peerIDToPublicKeyFingerprint[peerID]\n }\n \n guard let fp = fingerprint else {\n return false\n }\n \n return SecureIdentityStateManager.shared.isFavorite(fingerprint: fp)\n }\n \n // MARK: - Public Key and Identity Management\n \n // Called when we receive a peer's public key\n func registerPeerPublicKey(peerID: String, publicKeyData: Data) {\n // Create a fingerprint from the public key (full SHA256, not truncated)\n let fingerprintStr = SHA256.hash(data: publicKeyData)\n .compactMap { String(format: \"%02x\", $0) }\n .joined()\n \n // Only register if not already registered\n if peerIDToPublicKeyFingerprint[peerID] != fingerprintStr {\n peerIDToPublicKeyFingerprint[peerID] = fingerprintStr\n }\n \n // Update identity state manager with handshake completion\n SecureIdentityStateManager.shared.updateHandshakeState(peerID: peerID, state: .completed(fingerprint: fingerprintStr))\n \n // Update encryption status now that we have the fingerprint\n updateEncryptionStatus(for: peerID)\n \n // Check if we have a claimed nickname for this peer\n let peerNicknames = meshService.getPeerNicknames()\n if let nickname = peerNicknames[peerID], nickname != \"Unknown\" && nickname != \"anon\\(peerID.prefix(4))\" {\n // Update or create social identity with the claimed nickname\n if var identity = SecureIdentityStateManager.shared.getSocialIdentity(for: fingerprintStr) {\n identity.claimedNickname = nickname\n SecureIdentityStateManager.shared.updateSocialIdentity(identity)\n } else {\n let newIdentity = SocialIdentity(\n fingerprint: fingerprintStr,\n localPetname: nil,\n claimedNickname: nickname,\n trustLevel: .casual,\n isFavorite: false,\n isBlocked: false,\n notes: nil\n )\n SecureIdentityStateManager.shared.updateSocialIdentity(newIdentity)\n }\n }\n \n // Check if this peer is the one we're in a private chat with\n updatePrivateChatPeerIfNeeded()\n }\n \n private func isPeerBlocked(_ peerID: String) -> Bool {\n // Check if we have the public key fingerprint for this peer\n if let fingerprint = peerIDToPublicKeyFingerprint[peerID] {\n return SecureIdentityStateManager.shared.isBlocked(fingerprint: fingerprint)\n }\n \n // Try to get fingerprint from mesh service\n if let fingerprint = meshService.getPeerFingerprint(peerID) {\n return SecureIdentityStateManager.shared.isBlocked(fingerprint: fingerprint)\n }\n \n return false\n }\n \n // Helper method to find current peer ID for a fingerprint\n private func getCurrentPeerIDForFingerprint(_ fingerprint: String) -> String? {\n // Search through all connected peers to find the one with matching fingerprint\n for peerID in connectedPeers {\n if let mappedFingerprint = peerIDToPublicKeyFingerprint[peerID],\n mappedFingerprint == fingerprint {\n return peerID\n }\n }\n return nil\n }\n \n // Helper method to update selectedPrivateChatPeer if fingerprint matches\n private func updatePrivateChatPeerIfNeeded() {\n guard let chatFingerprint = selectedPrivateChatFingerprint else { return }\n \n // Find current peer ID for the fingerprint\n if let currentPeerID = getCurrentPeerIDForFingerprint(chatFingerprint) {\n // Update the selected peer if it's different\n if let oldPeerID = selectedPrivateChatPeer, oldPeerID != currentPeerID {\n // Migrate messages from old peer ID to new peer ID\n if let oldMessages = privateChats[oldPeerID] {\n if privateChats[currentPeerID] == nil {\n privateChats[currentPeerID] = []\n }\n privateChats[currentPeerID]?.append(contentsOf: oldMessages)\n trimPrivateChatMessagesIfNeeded(for: currentPeerID)\n privateChats.removeValue(forKey: oldPeerID)\n }\n \n // Migrate unread status\n if unreadPrivateMessages.contains(oldPeerID) {\n unreadPrivateMessages.remove(oldPeerID)\n unreadPrivateMessages.insert(currentPeerID)\n }\n \n selectedPrivateChatPeer = currentPeerID\n } else if selectedPrivateChatPeer == nil {\n // Just set the peer ID if we don't have one\n selectedPrivateChatPeer = currentPeerID\n }\n \n // Clear unread messages for the current peer ID\n unreadPrivateMessages.remove(currentPeerID)\n }\n }\n \n // MARK: - Message Sending\n \n /// Sends a message through the BitChat network.\n /// - Parameter content: The message content to send\n /// - Note: Automatically handles command processing if content starts with '/'\n /// Routes to private chat if one is selected, otherwise broadcasts\n func sendMessage(_ content: String) {\n guard !content.isEmpty else { return }\n \n // Check for commands\n if content.hasPrefix(\"/\") {\n handleCommand(content)\n return\n }\n \n if selectedPrivateChatPeer != nil {\n // Update peer ID in case it changed due to reconnection\n updatePrivateChatPeerIfNeeded()\n \n if let selectedPeer = selectedPrivateChatPeer {\n // Send as private message\n sendPrivateMessage(content, to: selectedPeer)\n } else {\n }\n } else {\n // Parse mentions from the content\n let mentions = parseMentions(from: content)\n \n // Add message to local display\n let message = BitchatMessage(\n sender: nickname,\n content: content,\n timestamp: Date(),\n isRelay: false,\n originalSender: nil,\n isPrivate: false,\n recipientNickname: nil,\n senderPeerID: meshService.myPeerID,\n mentions: mentions.isEmpty ? nil : mentions\n )\n \n // Add to main messages immediately for user feedback\n messages.append(message)\n trimMessagesIfNeeded()\n \n // Force immediate UI update for user's own messages\n objectWillChange.send()\n \n // Send via mesh with mentions\n meshService.sendMessage(content, mentions: mentions)\n }\n }\n \n /// Sends an encrypted private message to a specific peer.\n /// - Parameters:\n /// - content: The message content to encrypt and send\n /// - peerID: The recipient's peer ID\n /// - Note: Automatically establishes Noise encryption if not already active\n func sendPrivateMessage(_ content: String, to peerID: String) {\n guard !content.isEmpty else { return }\n guard let recipientNickname = meshService.getPeerNicknames()[peerID] else { \n return \n }\n \n // Check if the recipient is blocked\n if isPeerBlocked(peerID) {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot send message to \\(recipientNickname): user is blocked.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n return\n }\n \n // IMPORTANT: When sending a message, it means we're viewing this chat\n // Send read receipts for any delivered messages from this peer\n markPrivateMessagesAsRead(from: peerID)\n \n // Create the message locally\n let message = BitchatMessage(\n sender: nickname,\n content: content,\n timestamp: Date(),\n isRelay: false,\n originalSender: nil,\n isPrivate: true,\n recipientNickname: recipientNickname,\n senderPeerID: meshService.myPeerID,\n deliveryStatus: .sending\n )\n \n // Add to our private chat history\n if privateChats[peerID] == nil {\n privateChats[peerID] = []\n }\n privateChats[peerID]?.append(message)\n trimPrivateChatMessagesIfNeeded(for: peerID)\n \n // Track the message for delivery confirmation\n let isFavorite = isFavorite(peerID: peerID)\n DeliveryTracker.shared.trackMessage(message, recipientID: peerID, recipientNickname: recipientNickname, isFavorite: isFavorite)\n \n // Immediate UI update for user's own messages\n objectWillChange.send()\n \n // Send via mesh with the same message ID\n meshService.sendPrivateMessage(content, to: peerID, recipientNickname: recipientNickname, messageID: message.id)\n }\n \n // MARK: - Private Chat Management\n \n /// Initiates a private chat session with a peer.\n /// - Parameter peerID: The peer's ID to start chatting with\n /// - Note: Switches the UI to private chat mode and loads message history\n func startPrivateChat(with peerID: String) {\n let peerNickname = meshService.getPeerNicknames()[peerID] ?? \"unknown\"\n \n // Check if the peer is blocked\n if isPeerBlocked(peerID) {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot start chat with \\(peerNickname): user is blocked.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n return\n }\n \n // Trigger handshake if we don't have a session yet\n let sessionState = meshService.getNoiseSessionState(for: peerID)\n switch sessionState {\n case .none, .failed:\n // Initiate handshake when opening PM\n meshService.triggerHandshake(with: peerID)\n default:\n break\n }\n \n selectedPrivateChatPeer = peerID\n // Also track by fingerprint for persistence across reconnections\n selectedPrivateChatFingerprint = peerIDToPublicKeyFingerprint[peerID]\n unreadPrivateMessages.remove(peerID)\n \n // Check if we need to migrate messages from an old peer ID\n // This happens when peer IDs change between sessions\n if privateChats[peerID] == nil || privateChats[peerID]?.isEmpty == true {\n \n // Look for messages from this nickname under other peer IDs\n var migratedMessages: [BitchatMessage] = []\n var oldPeerIDsToRemove: [String] = []\n \n for (oldPeerID, messages) in privateChats {\n if oldPeerID != peerID {\n // Check if any messages in this chat are from the peer's nickname\n // Check if this chat contains messages with this peer\n let messagesWithPeer = messages.filter { msg in\n // Message is FROM the peer to us\n (msg.sender == peerNickname && msg.sender != nickname) ||\n // OR message is FROM us TO the peer\n (msg.sender == nickname && (msg.recipientNickname == peerNickname || \n // Also check if this was a private message in a chat that only has us and one other person\n (msg.isPrivate && messages.allSatisfy { m in \n m.sender == nickname || m.sender == peerNickname \n })))\n }\n \n if !messagesWithPeer.isEmpty {\n \n // Check if ALL messages in this chat are between us and this peer\n let allMessagesAreWithPeer = messages.allSatisfy { msg in\n (msg.sender == peerNickname || msg.sender == nickname) &&\n (msg.recipientNickname == nil || msg.recipientNickname == peerNickname || msg.recipientNickname == nickname)\n }\n \n if allMessagesAreWithPeer {\n // This entire chat history belongs to this peer, migrate it all\n migratedMessages.append(contentsOf: messages)\n oldPeerIDsToRemove.append(oldPeerID)\n }\n }\n }\n }\n \n // Remove old peer ID entries that were fully migrated\n for oldPeerID in oldPeerIDsToRemove {\n privateChats.removeValue(forKey: oldPeerID)\n unreadPrivateMessages.remove(oldPeerID)\n }\n \n // Initialize chat history with migrated messages if any\n if !migratedMessages.isEmpty {\n privateChats[peerID] = migratedMessages.sorted { $0.timestamp < $1.timestamp }\n trimPrivateChatMessagesIfNeeded(for: peerID)\n } else {\n privateChats[peerID] = []\n }\n }\n \n _ = privateChats[peerID] ?? []\n \n // Send read receipts for unread messages from this peer\n // Add a small delay to ensure UI has updated\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [weak self] in\n self?.markPrivateMessagesAsRead(from: peerID)\n }\n \n // Also try immediately in case messages are already there\n markPrivateMessagesAsRead(from: peerID)\n }\n \n func endPrivateChat() {\n selectedPrivateChatPeer = nil\n selectedPrivateChatFingerprint = nil\n }\n \n // MARK: - Message Retry Handling\n \n @objc private func handleRetryMessage(_ notification: Notification) {\n guard let messageID = notification.userInfo?[\"messageID\"] as? String else { return }\n \n // Find the message to retry\n if let message = messages.first(where: { $0.id == messageID }) {\n SecureLogger.log(\"Retrying message \\(messageID) to \\(message.recipientNickname ?? \"unknown\")\", \n category: SecureLogger.session, level: .info)\n \n // Resend the message through mesh service\n if message.isPrivate,\n let peerID = getPeerIDForNickname(message.recipientNickname ?? \"\") {\n // Update status to sending\n updateMessageDeliveryStatus(messageID, status: .sending)\n \n // Resend via mesh service\n meshService.sendMessage(message.content, \n mentions: message.mentions ?? [], \n to: peerID,\n messageID: messageID,\n timestamp: message.timestamp)\n }\n }\n }\n \n // MARK: - App Lifecycle\n \n @objc private func appDidBecomeActive() {\n // When app becomes active, send read receipts for visible private chat\n if let peerID = selectedPrivateChatPeer {\n // Try immediately\n self.markPrivateMessagesAsRead(from: peerID)\n // And again with a delay\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {\n self.markPrivateMessagesAsRead(from: peerID)\n }\n }\n }\n \n @objc private func userDidTakeScreenshot() {\n // Send screenshot notification based on current context\n let screenshotMessage = \"* \\(nickname) took a screenshot *\"\n \n if let peerID = selectedPrivateChatPeer {\n // In private chat - send to the other person\n if let peerNickname = meshService.getPeerNicknames()[peerID] {\n // Only send screenshot notification if we have an established session\n // This prevents triggering handshake requests for screenshot notifications\n let sessionState = meshService.getNoiseSessionState(for: peerID)\n switch sessionState {\n case .established:\n // Send the message directly without going through sendPrivateMessage to avoid local echo\n meshService.sendPrivateMessage(screenshotMessage, to: peerID, recipientNickname: peerNickname)\n default:\n // Don't send screenshot notification if no session exists\n SecureLogger.log(\"Skipping screenshot notification to \\(peerID) - no established session\", category: SecureLogger.security, level: .debug)\n }\n }\n \n // Show local notification immediately as system message\n let localNotification = BitchatMessage(\n sender: \"system\",\n content: \"you took a screenshot\",\n timestamp: Date(),\n isRelay: false,\n originalSender: nil,\n isPrivate: true,\n recipientNickname: meshService.getPeerNicknames()[peerID],\n senderPeerID: meshService.myPeerID\n )\n if privateChats[peerID] == nil {\n privateChats[peerID] = []\n }\n privateChats[peerID]?.append(localNotification)\n trimPrivateChatMessagesIfNeeded(for: peerID)\n \n } else {\n // In public chat - send to everyone\n meshService.sendMessage(screenshotMessage, mentions: [])\n \n // Show local notification immediately as system message\n let localNotification = BitchatMessage(\n sender: \"system\",\n content: \"you took a screenshot\",\n timestamp: Date(),\n isRelay: false\n )\n // System messages can be batched\n addMessageToBatch(localNotification)\n }\n }\n \n @objc private func appWillResignActive() {\n // Flush any pending messages when app goes to background\n flushMessageBatchImmediately()\n \n userDefaults.synchronize()\n }\n \n @objc func applicationWillTerminate() {\n // Flush any pending messages immediately\n flushMessageBatchImmediately()\n \n // Force save any pending identity changes (verifications, favorites, etc)\n SecureIdentityStateManager.shared.forceSave()\n \n // Verify identity key is still there\n _ = KeychainManager.shared.verifyIdentityKeyExists()\n \n userDefaults.synchronize()\n \n // Verify identity key after save\n _ = KeychainManager.shared.verifyIdentityKeyExists()\n }\n \n @objc private func appWillTerminate() {\n // Flush any pending messages immediately\n flushMessageBatchImmediately()\n \n userDefaults.synchronize()\n }\n \n func markPrivateMessagesAsRead(from peerID: String) {\n // Get the nickname for this peer\n let peerNickname = meshService.getPeerNicknames()[peerID] ?? \"\"\n \n // First ensure we have the latest messages (in case of migration)\n if let messages = privateChats[peerID], !messages.isEmpty {\n } else {\n \n // Look through ALL private chats to find messages from this nickname\n for (_, chatMessages) in privateChats {\n let relevantMessages = chatMessages.filter { msg in\n msg.sender == peerNickname && msg.sender != nickname\n }\n if !relevantMessages.isEmpty {\n }\n }\n }\n \n guard let messages = privateChats[peerID], !messages.isEmpty else { \n return \n }\n \n \n // Find messages from the peer that haven't been read yet\n var readReceiptsSent = 0\n for (_, message) in messages.enumerated() {\n // Only send read receipts for messages from the other peer (not our own)\n // Check multiple conditions to ensure we catch all messages from the peer\n let isOurMessage = message.sender == nickname\n let isFromPeerByNickname = !peerNickname.isEmpty && message.sender == peerNickname\n let isFromPeerByID = message.senderPeerID == peerID\n let isPrivateToUs = message.isPrivate && message.recipientNickname == nickname\n \n // This is a message FROM the peer if it's not from us AND (matches nickname OR peer ID OR is private to us)\n let isFromPeer = !isOurMessage && (isFromPeerByNickname || isFromPeerByID || isPrivateToUs)\n \n if message.id == message.id { // Always true, for debugging\n }\n \n if isFromPeer {\n if let status = message.deliveryStatus {\n switch status {\n case .sent, .delivered:\n // Create and send read receipt for sent or delivered messages\n // Check if we've already sent a receipt for this message\n if !sentReadReceipts.contains(message.id) {\n // Send to the CURRENT peer ID, not the old senderPeerID which may have changed\n let receipt = ReadReceipt(\n originalMessageID: message.id,\n readerID: meshService.myPeerID,\n readerNickname: nickname\n )\n meshService.sendReadReceipt(receipt, to: peerID)\n sentReadReceipts.insert(message.id)\n readReceiptsSent += 1\n } else {\n }\n case .read:\n // Already read, no need to send another receipt\n break\n default:\n // Message not yet delivered, can't mark as read\n break\n }\n } else {\n // No delivery status - this might be an older message\n // Send read receipt anyway for backwards compatibility\n if !sentReadReceipts.contains(message.id) {\n let receipt = ReadReceipt(\n originalMessageID: message.id,\n readerID: meshService.myPeerID,\n readerNickname: nickname\n )\n meshService.sendReadReceipt(receipt, to: peerID)\n sentReadReceipts.insert(message.id)\n readReceiptsSent += 1\n } else {\n }\n }\n } else {\n }\n }\n \n }\n \n func getPrivateChatMessages(for peerID: String) -> [BitchatMessage] {\n let messages = privateChats[peerID] ?? []\n if !messages.isEmpty {\n }\n return messages\n }\n \n func getPeerIDForNickname(_ nickname: String) -> String? {\n let nicknames = meshService.getPeerNicknames()\n return nicknames.first(where: { $0.value == nickname })?.key\n }\n \n \n // MARK: - Emergency Functions\n \n // PANIC: Emergency data clearing for activist safety\n func panicClearAllData() {\n // Flush any pending messages immediately before clearing\n flushMessageBatchImmediately()\n \n // Clear all messages\n messages.removeAll()\n privateChats.removeAll()\n unreadPrivateMessages.removeAll()\n \n // First run aggressive cleanup to get rid of all legacy items\n _ = KeychainManager.shared.aggressiveCleanupLegacyItems()\n \n // Then delete all current keychain data\n _ = KeychainManager.shared.deleteAllKeychainData()\n \n // Clear UserDefaults identity fallbacks\n userDefaults.removeObject(forKey: \"bitchat.noiseIdentityKey\")\n userDefaults.removeObject(forKey: \"bitchat.messageRetentionKey\")\n \n // Clear verified fingerprints\n verifiedFingerprints.removeAll()\n // Verified fingerprints are cleared when identity data is cleared below\n \n // Clear message retry queue\n MessageRetryService.shared.clearRetryQueue()\n \n \n // Reset nickname to anonymous\n nickname = \"anon\\(Int.random(in: 1000...9999))\"\n saveNickname()\n \n // Clear favorites\n favoritePeers.removeAll()\n peerIDToPublicKeyFingerprint.removeAll()\n \n // Clear identity data from secure storage\n SecureIdentityStateManager.shared.clearAllIdentityData()\n \n // Clear autocomplete state\n autocompleteSuggestions.removeAll()\n showAutocomplete = false\n autocompleteRange = nil\n selectedAutocompleteIndex = 0\n \n // Clear selected private chat\n selectedPrivateChatPeer = nil\n selectedPrivateChatFingerprint = nil\n \n // Clear read receipt tracking\n sentReadReceipts.removeAll()\n \n // Clear all caches\n invalidateEncryptionCache()\n invalidateRSSIColorCache()\n \n // Disconnect from all peers and clear persistent identity\n // This will force creation of a new identity (new fingerprint) on next launch\n meshService.emergencyDisconnectAll()\n \n // Force immediate UserDefaults synchronization\n userDefaults.synchronize()\n \n // Force UI update\n objectWillChange.send()\n \n }\n \n \n \n // MARK: - Formatting Helpers\n \n func formatTimestamp(_ date: Date) -> String {\n let formatter = DateFormatter()\n formatter.dateFormat = \"HH:mm:ss\"\n return formatter.string(from: date)\n }\n \n func getRSSIColor(rssi: Int, colorScheme: ColorScheme) -> Color {\n let isDark = colorScheme == .dark\n let cacheKey = \"\\(rssi)_\\(isDark)\"\n \n // Check cache first\n if let cachedColor = rssiColorCache[cacheKey] {\n return cachedColor\n }\n \n // RSSI typically ranges from -30 (excellent) to -90 (poor)\n // We'll map this to colors from green (strong) to red (weak)\n \n let color: Color\n if rssi >= -50 {\n // Excellent signal: bright green\n color = isDark ? Color(red: 0.0, green: 1.0, blue: 0.0) : Color(red: 0.0, green: 0.7, blue: 0.0)\n } else if rssi >= -60 {\n // Good signal: green-yellow\n color = isDark ? Color(red: 0.5, green: 1.0, blue: 0.0) : Color(red: 0.3, green: 0.7, blue: 0.0)\n } else if rssi >= -70 {\n // Fair signal: yellow\n color = isDark ? Color(red: 1.0, green: 1.0, blue: 0.0) : Color(red: 0.7, green: 0.7, blue: 0.0)\n } else if rssi >= -80 {\n // Weak signal: orange\n color = isDark ? Color(red: 1.0, green: 0.6, blue: 0.0) : Color(red: 0.8, green: 0.4, blue: 0.0)\n } else {\n // Poor signal: red\n color = isDark ? Color(red: 1.0, green: 0.2, blue: 0.2) : Color(red: 0.8, green: 0.0, blue: 0.0)\n }\n \n // Cache the result\n rssiColorCache[cacheKey] = color\n return color\n }\n \n // MARK: - Autocomplete\n \n func updateAutocomplete(for text: String, cursorPosition: Int) {\n // Quick early exit for empty text\n guard cursorPosition > 0 else {\n if showAutocomplete {\n showAutocomplete = false\n autocompleteSuggestions = []\n autocompleteRange = nil\n }\n return\n }\n \n // Find @ symbol before cursor\n let beforeCursor = String(text.prefix(cursorPosition))\n \n // Use cached regex\n guard let regex = mentionRegex,\n let match = regex.firstMatch(in: beforeCursor, options: [], range: NSRange(location: 0, length: beforeCursor.count)) else {\n if showAutocomplete {\n showAutocomplete = false\n autocompleteSuggestions = []\n autocompleteRange = nil\n }\n return\n }\n \n // Extract the partial nickname\n let partialRange = match.range(at: 1)\n guard let range = Range(partialRange, in: beforeCursor) else {\n if showAutocomplete {\n showAutocomplete = false\n autocompleteSuggestions = []\n autocompleteRange = nil\n }\n return\n }\n \n let partial = String(beforeCursor[range]).lowercased()\n \n // Update cached nicknames only if peer list changed (check every 1 second max)\n let now = Date()\n if now.timeIntervalSince(lastNicknameUpdate) > 1.0 || cachedNicknames.isEmpty {\n let peerNicknames = meshService.getPeerNicknames()\n cachedNicknames = Array(peerNicknames.values).sorted()\n lastNicknameUpdate = now\n }\n \n // Filter suggestions using cached nicknames\n let suggestions = cachedNicknames.filter { nick in\n nick.lowercased().hasPrefix(partial)\n }\n \n // Batch UI updates\n if !suggestions.isEmpty {\n // Only update if suggestions changed\n if autocompleteSuggestions != suggestions {\n autocompleteSuggestions = suggestions\n }\n if !showAutocomplete {\n showAutocomplete = true\n }\n if autocompleteRange != match.range(at: 0) {\n autocompleteRange = match.range(at: 0)\n }\n selectedAutocompleteIndex = 0\n } else {\n if showAutocomplete {\n showAutocomplete = false\n autocompleteSuggestions = []\n autocompleteRange = nil\n selectedAutocompleteIndex = 0\n }\n }\n }\n \n func completeNickname(_ nickname: String, in text: inout String) -> Int {\n guard let range = autocompleteRange else { return text.count }\n \n // Replace the @partial with @nickname\n let nsText = text as NSString\n let newText = nsText.replacingCharacters(in: range, with: \"@\\(nickname) \")\n text = newText\n \n // Hide autocomplete\n showAutocomplete = false\n autocompleteSuggestions = []\n autocompleteRange = nil\n selectedAutocompleteIndex = 0\n \n // Return new cursor position (after the space)\n return range.location + nickname.count + 2\n }\n \n // MARK: - Message Formatting\n \n func getSenderColor(for message: BitchatMessage, colorScheme: ColorScheme) -> Color {\n let isDark = colorScheme == .dark\n let primaryColor = isDark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n \n // Always use the same color for all senders - no RSSI-based coloring\n return primaryColor\n }\n \n \n func formatMessageContent(_ message: BitchatMessage, colorScheme: ColorScheme) -> AttributedString {\n let isDark = colorScheme == .dark\n let contentText = message.content\n var processedContent = AttributedString()\n \n // Regular expressions for mentions and hashtags\n let mentionPattern = \"@([a-zA-Z0-9_]+)\"\n let hashtagPattern = \"#([a-zA-Z0-9_]+)\"\n \n let mentionRegex = try? NSRegularExpression(pattern: mentionPattern, options: [])\n let hashtagRegex = try? NSRegularExpression(pattern: hashtagPattern, options: [])\n \n let mentionMatches = mentionRegex?.matches(in: contentText, options: [], range: NSRange(location: 0, length: contentText.count)) ?? []\n let hashtagMatches = hashtagRegex?.matches(in: contentText, options: [], range: NSRange(location: 0, length: contentText.count)) ?? []\n \n // Combine and sort all matches\n var allMatches: [(range: NSRange, type: String)] = []\n for match in mentionMatches {\n allMatches.append((match.range(at: 0), \"mention\"))\n }\n for match in hashtagMatches {\n allMatches.append((match.range(at: 0), \"hashtag\"))\n }\n allMatches.sort { $0.range.location < $1.range.location }\n \n var lastEndIndex = contentText.startIndex\n \n for (matchRange, matchType) in allMatches {\n // Add text before the match\n if let range = Range(matchRange, in: contentText) {\n let beforeText = String(contentText[lastEndIndex.. AttributedString {\n // Check cache first\n let isDark = colorScheme == .dark\n if let cachedText = message.getCachedFormattedText(isDark: isDark) {\n return cachedText\n }\n \n // Not cached, format the message\n var result = AttributedString()\n \n let primaryColor = isDark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n let secondaryColor = primaryColor.opacity(0.7)\n \n // Timestamp\n let timestamp = AttributedString(\"[\\(formatTimestamp(message.timestamp))] \")\n var timestampStyle = AttributeContainer()\n timestampStyle.foregroundColor = message.sender == \"system\" ? Color.gray : secondaryColor\n timestampStyle.font = .system(size: 12, design: .monospaced)\n result.append(timestamp.mergingAttributes(timestampStyle))\n \n if message.sender != \"system\" {\n // Sender\n let sender = AttributedString(\"<@\\(message.sender)> \")\n var senderStyle = AttributeContainer()\n \n // Use consistent color for all senders\n senderStyle.foregroundColor = primaryColor\n // Bold the user's own nickname\n let fontWeight: Font.Weight = message.sender == nickname ? .bold : .medium\n senderStyle.font = .system(size: 14, weight: fontWeight, design: .monospaced)\n result.append(sender.mergingAttributes(senderStyle))\n \n // Process content with hashtags and mentions\n let content = message.content\n \n let hashtagPattern = \"#([a-zA-Z0-9_]+)\"\n let mentionPattern = \"@([a-zA-Z0-9_]+)\"\n \n let hashtagRegex = try? NSRegularExpression(pattern: hashtagPattern, options: [])\n let mentionRegex = try? NSRegularExpression(pattern: mentionPattern, options: [])\n \n // Use NSDataDetector for URL detection\n let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)\n \n let hashtagMatches = hashtagRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n let mentionMatches = mentionRegex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n let urlMatches = detector?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n \n // Combine and sort matches\n var allMatches: [(range: NSRange, type: String)] = []\n for match in hashtagMatches {\n allMatches.append((match.range(at: 0), \"hashtag\"))\n }\n for match in mentionMatches {\n allMatches.append((match.range(at: 0), \"mention\"))\n }\n for match in urlMatches {\n allMatches.append((match.range, \"url\"))\n }\n allMatches.sort { $0.range.location < $1.range.location }\n \n // Build content with styling\n var lastEnd = content.startIndex\n let isMentioned = message.mentions?.contains(nickname) ?? false\n \n for (range, type) in allMatches {\n // Add text before match\n if let nsRange = Range(range, in: content) {\n let beforeText = String(content[lastEnd.. AttributedString {\n var result = AttributedString()\n \n let isDark = colorScheme == .dark\n let primaryColor = isDark ? Color.green : Color(red: 0, green: 0.5, blue: 0)\n let secondaryColor = primaryColor.opacity(0.7)\n \n let timestamp = AttributedString(\"[\\(formatTimestamp(message.timestamp))] \")\n var timestampStyle = AttributeContainer()\n timestampStyle.foregroundColor = message.sender == \"system\" ? Color.gray : secondaryColor\n timestampStyle.font = .system(size: 12, design: .monospaced)\n result.append(timestamp.mergingAttributes(timestampStyle))\n \n if message.sender == \"system\" {\n let content = AttributedString(\"* \\(message.content) *\")\n var contentStyle = AttributeContainer()\n contentStyle.foregroundColor = Color.gray\n contentStyle.font = .system(size: 12, design: .monospaced).italic()\n result.append(content.mergingAttributes(contentStyle))\n } else {\n let sender = AttributedString(\"<\\(message.sender)> \")\n var senderStyle = AttributeContainer()\n \n // Use consistent color for all senders\n senderStyle.foregroundColor = primaryColor\n // Bold the user's own nickname\n let fontWeight: Font.Weight = message.sender == nickname ? .bold : .medium\n senderStyle.font = .system(size: 12, weight: fontWeight, design: .monospaced)\n result.append(sender.mergingAttributes(senderStyle))\n \n \n // Process content to highlight mentions\n let contentText = message.content\n var processedContent = AttributedString()\n \n // Regular expression to find @mentions\n let pattern = \"@([a-zA-Z0-9_]+)\"\n let regex = try? NSRegularExpression(pattern: pattern, options: [])\n let matches = regex?.matches(in: contentText, options: [], range: NSRange(location: 0, length: contentText.count)) ?? []\n \n var lastEndIndex = contentText.startIndex\n \n for match in matches {\n // Add text before the mention\n if let range = Range(match.range(at: 0), in: contentText) {\n let beforeText = String(contentText[lastEndIndex.. EncryptionStatus {\n // Check cache first\n if let cachedStatus = encryptionStatusCache[peerID] {\n return cachedStatus\n }\n \n // This must be a pure function - no state mutations allowed\n // to avoid SwiftUI update loops\n \n let sessionState = meshService.getNoiseSessionState(for: peerID)\n let storedStatus = peerEncryptionStatus[peerID]\n \n let status: EncryptionStatus\n \n // Determine status based on session state\n switch sessionState {\n case .established:\n // We have encryption, now check if it's verified\n if let fingerprint = getFingerprint(for: peerID) {\n if verifiedFingerprints.contains(fingerprint) {\n status = .noiseVerified\n } else {\n status = .noiseSecured\n }\n } else {\n // We have a session but no fingerprint yet - still secured\n status = .noiseSecured\n }\n case .handshaking, .handshakeQueued:\n // Currently establishing encryption\n status = .noiseHandshaking\n case .none:\n // No handshake attempted\n status = .noHandshake\n case .failed:\n // Handshake failed - show broken lock\n status = .none\n }\n \n // Cache the result\n encryptionStatusCache[peerID] = status\n \n // Only log occasionally to avoid spam\n if Int.random(in: 0..<100) == 0 {\n SecureLogger.log(\"getEncryptionStatus for \\(peerID): sessionState=\\(sessionState), stored=\\(String(describing: storedStatus)), final=\\(status)\", category: SecureLogger.security, level: .debug)\n }\n \n return status\n }\n \n // Clear caches when data changes\n private func invalidateEncryptionCache(for peerID: String? = nil) {\n if let peerID = peerID {\n encryptionStatusCache.removeValue(forKey: peerID)\n } else {\n encryptionStatusCache.removeAll()\n }\n }\n \n private func invalidateRSSIColorCache() {\n rssiColorCache.removeAll()\n }\n \n // MARK: - Message Batching\n \n private func trimMessagesIfNeeded() {\n if messages.count > maxMessages {\n let removeCount = messages.count - maxMessages\n messages.removeFirst(removeCount)\n }\n }\n \n private func trimPrivateChatMessagesIfNeeded(for peerID: String) {\n if let count = privateChats[peerID]?.count, count > maxMessages {\n let removeCount = count - maxMessages\n privateChats[peerID]?.removeFirst(removeCount)\n }\n }\n \n private func addMessageToBatch(_ message: BitchatMessage) {\n pendingMessages.append(message)\n scheduleBatchFlush()\n }\n \n private func addPrivateMessageToBatch(_ message: BitchatMessage, for peerID: String) {\n if pendingPrivateMessages[peerID] == nil {\n pendingPrivateMessages[peerID] = []\n }\n pendingPrivateMessages[peerID]?.append(message)\n scheduleBatchFlush()\n }\n \n private func scheduleBatchFlush() {\n // Cancel existing timer\n messageBatchTimer?.invalidate()\n \n // Schedule new flush\n messageBatchTimer = Timer.scheduledTimer(withTimeInterval: messageBatchInterval, repeats: false) { [weak self] _ in\n self?.flushMessageBatch()\n }\n }\n \n private func flushMessageBatch() {\n DispatchQueue.main.async { [weak self] in\n guard let self = self else { return }\n \n // Process pending public messages\n if !self.pendingMessages.isEmpty {\n let messagesToAdd = self.pendingMessages\n self.pendingMessages.removeAll()\n \n // Add all messages at once\n self.messages.append(contentsOf: messagesToAdd)\n \n // Sort once after batch addition\n self.messages.sort { $0.timestamp < $1.timestamp }\n \n // Trim once if needed\n self.trimMessagesIfNeeded()\n }\n \n // Process pending private messages\n if !self.pendingPrivateMessages.isEmpty {\n let privateMessageBatches = self.pendingPrivateMessages\n self.pendingPrivateMessages.removeAll()\n \n for (peerID, messagesToAdd) in privateMessageBatches {\n if self.privateChats[peerID] == nil {\n self.privateChats[peerID] = []\n }\n \n // Add all messages for this peer at once\n self.privateChats[peerID]?.append(contentsOf: messagesToAdd)\n \n // Sort once after batch addition\n self.privateChats[peerID]?.sort { $0.timestamp < $1.timestamp }\n \n // Trim once if needed\n self.trimPrivateChatMessagesIfNeeded(for: peerID)\n }\n }\n \n // Single UI update for all changes\n self.objectWillChange.send()\n }\n }\n \n // Force immediate flush for high-priority messages\n private func flushMessageBatchImmediately() {\n messageBatchTimer?.invalidate()\n flushMessageBatch()\n }\n \n // Update encryption status in appropriate places, not during view updates\n private func updateEncryptionStatus(for peerID: String) {\n let noiseService = meshService.getNoiseService()\n \n if noiseService.hasEstablishedSession(with: peerID) {\n if let fingerprint = getFingerprint(for: peerID) {\n if verifiedFingerprints.contains(fingerprint) {\n peerEncryptionStatus[peerID] = .noiseVerified\n } else {\n peerEncryptionStatus[peerID] = .noiseSecured\n }\n } else {\n // Session established but no fingerprint yet\n peerEncryptionStatus[peerID] = .noiseSecured\n }\n } else if noiseService.hasSession(with: peerID) {\n peerEncryptionStatus[peerID] = .noiseHandshaking\n } else {\n peerEncryptionStatus[peerID] = Optional.none\n }\n \n // Invalidate cache when encryption status changes\n invalidateEncryptionCache(for: peerID)\n \n // Trigger UI update\n DispatchQueue.main.async { [weak self] in\n self?.objectWillChange.send()\n }\n }\n \n // MARK: - Fingerprint Management\n \n func showFingerprint(for peerID: String) {\n showingFingerprintFor = peerID\n }\n \n func getFingerprint(for peerID: String) -> String? {\n // Remove debug logging to prevent console spam during view updates\n \n // First try to get fingerprint from mesh service's peer ID rotation mapping\n if let fingerprint = meshService.getFingerprint(for: peerID) {\n return fingerprint\n }\n \n // Fallback to noise service (direct Noise session fingerprint)\n if let fingerprint = meshService.getNoiseService().getPeerFingerprint(peerID) {\n return fingerprint\n }\n \n // Last resort: check local mapping\n if let fingerprint = peerIDToPublicKeyFingerprint[peerID] {\n return fingerprint\n }\n \n return nil\n }\n \n // Helper to resolve nickname for a peer ID through various sources\n func resolveNickname(for peerID: String) -> String {\n // Guard against empty or very short peer IDs\n guard !peerID.isEmpty else {\n return \"unknown\"\n }\n \n // Check if this might already be a nickname (not a hex peer ID)\n // Peer IDs are hex strings, so they only contain 0-9 and a-f\n let isHexID = peerID.allSatisfy { $0.isHexDigit }\n if !isHexID {\n // If it's already a nickname, just return it\n return peerID\n }\n \n // First try direct peer nicknames from mesh service\n let peerNicknames = meshService.getPeerNicknames()\n if let nickname = peerNicknames[peerID] {\n return nickname\n }\n \n // Try to resolve through fingerprint and social identity\n if let fingerprint = getFingerprint(for: peerID) {\n if let identity = SecureIdentityStateManager.shared.getSocialIdentity(for: fingerprint) {\n // Prefer local petname if set\n if let petname = identity.localPetname {\n return petname\n }\n // Otherwise use their claimed nickname\n return identity.claimedNickname\n }\n }\n \n // Fallback to anonymous with shortened peer ID\n // Ensure we have at least 4 characters for the prefix\n let prefixLength = min(4, peerID.count)\n let prefix = String(peerID.prefix(prefixLength))\n \n // Avoid \"anonanon\" by checking if ID already starts with \"anon\"\n if prefix.starts(with: \"anon\") {\n return \"peer\\(prefix)\"\n }\n return \"anon\\(prefix)\"\n }\n \n func getMyFingerprint() -> String {\n let fingerprint = meshService.getNoiseService().getIdentityFingerprint()\n return fingerprint\n }\n \n func verifyFingerprint(for peerID: String) {\n guard let fingerprint = getFingerprint(for: peerID) else { return }\n \n // Update secure storage with verified status\n SecureIdentityStateManager.shared.setVerified(fingerprint: fingerprint, verified: true)\n \n // Update local set for UI\n verifiedFingerprints.insert(fingerprint)\n \n // Update encryption status after verification\n updateEncryptionStatus(for: peerID)\n }\n \n func loadVerifiedFingerprints() {\n // Load verified fingerprints directly from secure storage\n verifiedFingerprints = SecureIdentityStateManager.shared.getVerifiedFingerprints()\n }\n \n private func setupNoiseCallbacks() {\n let noiseService = meshService.getNoiseService()\n \n // Set up authentication callback\n noiseService.onPeerAuthenticated = { [weak self] peerID, fingerprint in\n DispatchQueue.main.async {\n guard let self = self else { return }\n \n SecureLogger.log(\"ChatViewModel: Peer authenticated - \\(peerID), fingerprint: \\(fingerprint)\", category: SecureLogger.security, level: .info)\n \n // Update encryption status\n if self.verifiedFingerprints.contains(fingerprint) {\n self.peerEncryptionStatus[peerID] = .noiseVerified\n SecureLogger.log(\"ChatViewModel: Setting encryption status to noiseVerified for \\(peerID)\", category: SecureLogger.security, level: .info)\n } else {\n self.peerEncryptionStatus[peerID] = .noiseSecured\n SecureLogger.log(\"ChatViewModel: Setting encryption status to noiseSecured for \\(peerID)\", category: SecureLogger.security, level: .info)\n }\n \n // Invalidate cache when encryption status changes\n self.invalidateEncryptionCache(for: peerID)\n \n // Force UI update\n self.objectWillChange.send()\n }\n }\n \n // Set up handshake required callback\n noiseService.onHandshakeRequired = { [weak self] peerID in\n DispatchQueue.main.async {\n guard let self = self else { return }\n self.peerEncryptionStatus[peerID] = .noiseHandshaking\n \n // Invalidate cache when encryption status changes\n self.invalidateEncryptionCache(for: peerID)\n \n // Force UI update\n self.objectWillChange.send()\n }\n }\n }\n}\n\n// MARK: - BitchatDelegate\n\nextension ChatViewModel: BitchatDelegate {\n \n // MARK: - Command Handling\n \n /// Processes IRC-style commands starting with '/'.\n /// - Parameter command: The full command string including the leading slash\n /// - Note: Supports commands like /nick, /msg, /who, /slap, /clear, /help\n private func handleCommand(_ command: String) {\n let parts = command.split(separator: \" \")\n guard let cmd = parts.first else { return }\n \n switch cmd {\n case \"/m\", \"/msg\":\n if parts.count > 1 {\n let targetName = String(parts[1])\n // Remove @ if present\n let nickname = targetName.hasPrefix(\"@\") ? String(targetName.dropFirst()) : targetName\n \n // Find peer ID for this nickname\n if let peerID = getPeerIDForNickname(nickname) {\n startPrivateChat(with: peerID)\n \n // If there's a message after the nickname, send it\n if parts.count > 2 {\n let messageContent = parts[2...].joined(separator: \" \")\n sendPrivateMessage(messageContent, to: peerID)\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"started private chat with \\(nickname)\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"user '\\(nickname)' not found. they may be offline or using a different nickname.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"usage: /m @nickname [message] or /m nickname [message]\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n case \"/w\":\n let peerNicknames = meshService.getPeerNicknames()\n if connectedPeers.isEmpty {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"no one else is online right now.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n } else {\n let onlineList = connectedPeers.compactMap { peerID in\n peerNicknames[peerID]\n }.sorted().joined(separator: \", \")\n \n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"online users: \\(onlineList)\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n case \"/clear\":\n // Clear messages based on current context\n if let peerID = selectedPrivateChatPeer {\n // Clear private chat\n privateChats[peerID]?.removeAll()\n } else {\n // Clear main messages\n messages.removeAll()\n }\n case \"/hug\":\n if parts.count > 1 {\n let targetName = String(parts[1])\n // Remove @ if present\n let nickname = targetName.hasPrefix(\"@\") ? String(targetName.dropFirst()) : targetName\n \n // Check if target exists in connected peers\n if let targetPeerID = getPeerIDForNickname(nickname) {\n // Create hug message\n let hugMessage = BitchatMessage(\n sender: \"system\",\n content: \"🫂 \\(self.nickname) hugs \\(nickname)\",\n timestamp: Date(),\n isRelay: false,\n isPrivate: false,\n recipientNickname: nickname,\n senderPeerID: meshService.myPeerID\n )\n \n // Send as a regular message but it will be displayed as system message due to content\n let hugContent = \"* 🫂 \\(self.nickname) hugs \\(nickname) *\"\n if selectedPrivateChatPeer != nil {\n // In private chat, send as private message\n if let peerNickname = meshService.getPeerNicknames()[targetPeerID] {\n meshService.sendPrivateMessage(\"* 🫂 \\(self.nickname) hugs you *\", to: targetPeerID, recipientNickname: peerNickname)\n }\n } else {\n // In public chat\n meshService.sendMessage(hugContent)\n messages.append(hugMessage)\n }\n } else {\n let errorMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot hug \\(nickname): user not found.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(errorMessage)\n }\n } else {\n let usageMessage = BitchatMessage(\n sender: \"system\",\n content: \"usage: /hug \",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(usageMessage)\n }\n \n case \"/slap\":\n if parts.count > 1 {\n let targetName = String(parts[1])\n // Remove @ if present\n let nickname = targetName.hasPrefix(\"@\") ? String(targetName.dropFirst()) : targetName\n \n // Check if target exists in connected peers\n if let targetPeerID = getPeerIDForNickname(nickname) {\n // Create slap message\n let slapMessage = BitchatMessage(\n sender: \"system\",\n content: \"🐟 \\(self.nickname) slaps \\(nickname) around a bit with a large trout\",\n timestamp: Date(),\n isRelay: false,\n isPrivate: false,\n recipientNickname: nickname,\n senderPeerID: meshService.myPeerID\n )\n \n // Send as a regular message but it will be displayed as system message due to content\n let slapContent = \"* 🐟 \\(self.nickname) slaps \\(nickname) around a bit with a large trout *\"\n if selectedPrivateChatPeer != nil {\n // In private chat, send as private message\n if let peerNickname = meshService.getPeerNicknames()[targetPeerID] {\n meshService.sendPrivateMessage(\"* 🐟 \\(self.nickname) slaps you around a bit with a large trout *\", to: targetPeerID, recipientNickname: peerNickname)\n }\n } else {\n // In public chat\n meshService.sendMessage(slapContent)\n messages.append(slapMessage)\n }\n } else {\n let errorMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot slap \\(nickname): user not found.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(errorMessage)\n }\n } else {\n let usageMessage = BitchatMessage(\n sender: \"system\",\n content: \"usage: /slap \",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(usageMessage)\n }\n \n case \"/block\":\n if parts.count > 1 {\n let targetName = String(parts[1])\n // Remove @ if present\n let nickname = targetName.hasPrefix(\"@\") ? String(targetName.dropFirst()) : targetName\n \n // Find peer ID for this nickname\n if let peerID = getPeerIDForNickname(nickname) {\n // Get fingerprint for persistent blocking\n if let fingerprintStr = meshService.getPeerFingerprint(peerID) {\n \n if SecureIdentityStateManager.shared.isBlocked(fingerprint: fingerprintStr) {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"\\(nickname) is already blocked.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n } else {\n // Update or create social identity with blocked status\n if var identity = SecureIdentityStateManager.shared.getSocialIdentity(for: fingerprintStr) {\n identity.isBlocked = true\n identity.isFavorite = false // Remove from favorites if blocked\n SecureIdentityStateManager.shared.updateSocialIdentity(identity)\n } else {\n let blockedIdentity = SocialIdentity(\n fingerprint: fingerprintStr,\n localPetname: nil,\n claimedNickname: nickname,\n trustLevel: .unknown,\n isFavorite: false,\n isBlocked: true,\n notes: nil\n )\n SecureIdentityStateManager.shared.updateSocialIdentity(blockedIdentity)\n }\n \n // Update local sets for UI\n blockedUsers.insert(fingerprintStr)\n favoritePeers.remove(fingerprintStr)\n \n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"blocked \\(nickname). you will no longer receive messages from them.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot block \\(nickname): unable to verify identity.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot block \\(nickname): user not found.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n // List blocked users\n if blockedUsers.isEmpty {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"no blocked peers.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n } else {\n // Find nicknames for blocked users\n var blockedNicknames: [String] = []\n for (peerID, _) in meshService.getPeerNicknames() {\n if let fingerprintStr = meshService.getPeerFingerprint(peerID) {\n if blockedUsers.contains(fingerprintStr) {\n if let nickname = meshService.getPeerNicknames()[peerID] {\n blockedNicknames.append(nickname)\n }\n }\n }\n }\n \n let blockedList = blockedNicknames.isEmpty ? \"blocked peers (not currently online)\" : blockedNicknames.sorted().joined(separator: \", \")\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"blocked peers: \\(blockedList)\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n }\n \n case \"/unblock\":\n if parts.count > 1 {\n let targetName = String(parts[1])\n // Remove @ if present\n let nickname = targetName.hasPrefix(\"@\") ? String(targetName.dropFirst()) : targetName\n \n // Find peer ID for this nickname\n if let peerID = getPeerIDForNickname(nickname) {\n // Get fingerprint\n if let fingerprintStr = meshService.getPeerFingerprint(peerID) {\n \n if SecureIdentityStateManager.shared.isBlocked(fingerprint: fingerprintStr) {\n // Update social identity to unblock\n SecureIdentityStateManager.shared.setBlocked(fingerprintStr, isBlocked: false)\n \n // Update local set for UI\n blockedUsers.remove(fingerprintStr)\n \n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"unblocked \\(nickname).\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"\\(nickname) is not blocked.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot unblock \\(nickname): unable to verify identity.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"cannot unblock \\(nickname): user not found.\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n } else {\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"usage: /unblock \",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n \n default:\n // Unknown command\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"unknown command: \\(cmd).\",\n timestamp: Date(),\n isRelay: false\n )\n messages.append(systemMessage)\n }\n }\n \n // MARK: - Message Reception\n \n func handleHandshakeRequest(from peerID: String, nickname: String, pendingCount: UInt8) {\n // Create a notification message\n let notificationMessage = BitchatMessage(\n sender: \"system\",\n content: \"📨 \\(nickname) wants to send you \\(pendingCount) message\\(pendingCount == 1 ? \"\" : \"s\"). Open the conversation to receive.\",\n timestamp: Date(),\n isRelay: false,\n originalSender: nil,\n isPrivate: false,\n recipientNickname: nil,\n senderPeerID: \"system\",\n mentions: nil\n )\n \n // Add to messages\n messages.append(notificationMessage)\n trimMessagesIfNeeded()\n \n // Show system notification\n if let fingerprint = getFingerprint(for: peerID) {\n let isFavorite = favoritePeers.contains(fingerprint)\n if isFavorite {\n // Send favorite notification\n NotificationService.shared.sendPrivateMessageNotification(\n from: nickname,\n message: \"\\(pendingCount) message\\(pendingCount == 1 ? \"\" : \"s\") pending\",\n peerID: peerID\n )\n } else {\n // Send regular notification\n NotificationService.shared.sendMentionNotification(\n from: nickname,\n message: \"\\(pendingCount) message\\(pendingCount == 1 ? \"\" : \"s\") pending. Open conversation to receive.\"\n )\n }\n }\n }\n \n func didReceiveMessage(_ message: BitchatMessage) {\n \n \n // Check if sender is blocked (for both private and public messages)\n if let senderPeerID = message.senderPeerID {\n if isPeerBlocked(senderPeerID) {\n // Silently ignore messages from blocked users\n return\n }\n } else if let peerID = getPeerIDForNickname(message.sender) {\n if isPeerBlocked(peerID) {\n // Silently ignore messages from blocked users\n return\n }\n }\n \n if message.isPrivate {\n // Handle private message\n \n // Use the senderPeerID from the message if available\n let senderPeerID = message.senderPeerID ?? getPeerIDForNickname(message.sender)\n \n if let peerID = senderPeerID {\n // Message from someone else\n \n // First check if we need to migrate existing messages from this sender\n let senderNickname = message.sender\n if privateChats[peerID] == nil || privateChats[peerID]?.isEmpty == true {\n // Check if we have messages from this nickname under a different peer ID\n var migratedMessages: [BitchatMessage] = []\n var oldPeerIDsToRemove: [String] = []\n \n for (oldPeerID, messages) in privateChats {\n if oldPeerID != peerID {\n // Check if this chat contains messages with this sender\n let isRelevantChat = messages.contains { msg in\n (msg.sender == senderNickname && msg.sender != nickname) ||\n (msg.sender == nickname && msg.recipientNickname == senderNickname)\n }\n \n if isRelevantChat {\n migratedMessages.append(contentsOf: messages)\n oldPeerIDsToRemove.append(oldPeerID)\n }\n }\n }\n \n // Remove old peer ID entries\n for oldPeerID in oldPeerIDsToRemove {\n privateChats.removeValue(forKey: oldPeerID)\n unreadPrivateMessages.remove(oldPeerID)\n }\n \n // Initialize with migrated messages\n privateChats[peerID] = migratedMessages\n trimPrivateChatMessagesIfNeeded(for: peerID)\n }\n \n if privateChats[peerID] == nil {\n privateChats[peerID] = []\n }\n \n // Fix delivery status for incoming messages\n var messageToStore = message\n if message.sender != nickname {\n // This is an incoming message - it should NOT have \"sending\" status\n if messageToStore.deliveryStatus == nil || messageToStore.deliveryStatus == .sending {\n // Mark it as delivered since we received it\n messageToStore.deliveryStatus = .delivered(to: nickname, at: Date())\n }\n }\n \n // Check if this is an action that should be converted to system message\n let isActionMessage = messageToStore.content.hasPrefix(\"* \") && messageToStore.content.hasSuffix(\" *\") &&\n (messageToStore.content.contains(\"🫂\") || messageToStore.content.contains(\"🐟\") || \n messageToStore.content.contains(\"took a screenshot\"))\n \n if isActionMessage {\n // Convert to system message\n messageToStore = BitchatMessage(\n id: messageToStore.id,\n sender: \"system\",\n content: String(messageToStore.content.dropFirst(2).dropLast(2)), // Remove * * wrapper\n timestamp: messageToStore.timestamp,\n isRelay: messageToStore.isRelay,\n originalSender: messageToStore.originalSender,\n isPrivate: messageToStore.isPrivate,\n recipientNickname: messageToStore.recipientNickname,\n senderPeerID: messageToStore.senderPeerID,\n mentions: messageToStore.mentions,\n deliveryStatus: messageToStore.deliveryStatus\n )\n }\n \n // Use batching for private messages\n addPrivateMessageToBatch(messageToStore, for: peerID)\n \n // Debug logging\n \n // Check if we're in a private chat with this peer's fingerprint\n // This handles reconnections with new peer IDs\n if let chatFingerprint = selectedPrivateChatFingerprint,\n let senderFingerprint = peerIDToPublicKeyFingerprint[peerID],\n chatFingerprint == senderFingerprint && selectedPrivateChatPeer != peerID {\n // Update our private chat peer to the new ID\n selectedPrivateChatPeer = peerID\n }\n \n // Mark as unread if not currently viewing this chat\n if selectedPrivateChatPeer != peerID {\n unreadPrivateMessages.insert(peerID)\n \n } else {\n // We're viewing this chat, make sure unread is cleared\n unreadPrivateMessages.remove(peerID)\n \n // Send read receipt immediately since we're viewing the chat\n // Send to the current peer ID since peer IDs change between sessions\n if !sentReadReceipts.contains(message.id) {\n let receipt = ReadReceipt(\n originalMessageID: message.id,\n readerID: meshService.myPeerID,\n readerNickname: nickname\n )\n meshService.sendReadReceipt(receipt, to: peerID)\n sentReadReceipts.insert(message.id)\n }\n \n // Also check if there are other unread messages from this peer\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in\n self?.markPrivateMessagesAsRead(from: peerID)\n }\n }\n } else if message.sender == nickname {\n // Our own message that was echoed back - ignore it since we already added it locally\n }\n } else {\n // Regular public message (main chat)\n \n // Check if this is an action that should be converted to system message\n let isActionMessage = message.content.hasPrefix(\"* \") && message.content.hasSuffix(\" *\") &&\n (message.content.contains(\"🫂\") || message.content.contains(\"🐟\") || \n message.content.contains(\"took a screenshot\"))\n \n let finalMessage: BitchatMessage\n if isActionMessage {\n // Convert to system message\n finalMessage = BitchatMessage(\n sender: \"system\",\n content: String(message.content.dropFirst(2).dropLast(2)), // Remove * * wrapper\n timestamp: message.timestamp,\n isRelay: message.isRelay,\n originalSender: message.originalSender,\n isPrivate: false,\n recipientNickname: message.recipientNickname,\n senderPeerID: message.senderPeerID,\n mentions: message.mentions\n )\n } else {\n finalMessage = message\n }\n \n // Check if this is our own message being echoed back\n if finalMessage.sender != nickname && finalMessage.sender != \"system\" {\n // Skip empty or whitespace-only messages\n if !finalMessage.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {\n addMessageToBatch(finalMessage)\n }\n } else if finalMessage.sender != \"system\" {\n // Our own message - check if we already have it (by ID and content)\n let messageExists = messages.contains { existingMsg in\n // Check by ID first\n if existingMsg.id == finalMessage.id {\n return true\n }\n // Check by content and sender with time window (within 1 second)\n if existingMsg.content == finalMessage.content && \n existingMsg.sender == finalMessage.sender {\n let timeDiff = abs(existingMsg.timestamp.timeIntervalSince(finalMessage.timestamp))\n return timeDiff < 1.0\n }\n return false\n }\n if !messageExists {\n // This is a message we sent from another device or it's missing locally\n // Skip empty or whitespace-only messages\n if !finalMessage.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {\n addMessageToBatch(finalMessage)\n }\n }\n } else {\n // System message - check for empty content before adding\n if !finalMessage.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {\n addMessageToBatch(finalMessage)\n }\n }\n }\n \n // Check if we're mentioned\n let isMentioned = message.mentions?.contains(nickname) ?? false\n \n // Send notifications for mentions and private messages when app is in background\n if isMentioned && message.sender != nickname {\n NotificationService.shared.sendMentionNotification(from: message.sender, message: message.content)\n } else if message.isPrivate && message.sender != nickname {\n // Only send notification if the private chat is not currently open\n if selectedPrivateChatPeer != message.senderPeerID {\n NotificationService.shared.sendPrivateMessageNotification(from: message.sender, message: message.content, peerID: message.senderPeerID ?? \"\")\n }\n }\n \n #if os(iOS)\n // Haptic feedback for iOS only\n guard UIApplication.shared.applicationState == .active else {\n return\n }\n // Check if this is a hug message directed at the user\n let isHugForMe = message.content.contains(\"🫂\") && \n (message.content.contains(\"hugs \\(nickname)\") ||\n message.content.contains(\"hugs you\"))\n \n // Check if this is a slap message directed at the user\n let isSlapForMe = message.content.contains(\"🐟\") && \n (message.content.contains(\"slaps \\(nickname) around\") ||\n message.content.contains(\"slaps you around\"))\n \n if isHugForMe && message.sender != nickname {\n // Long warm haptic for hugs - continuous gentle vibration\n let impactFeedback = UIImpactFeedbackGenerator(style: .medium)\n impactFeedback.prepare()\n \n // Create a warm, sustained haptic pattern\n for i in 0..<8 {\n DispatchQueue.main.asyncAfter(deadline: .now() + Double(i) * 0.15) {\n impactFeedback.impactOccurred()\n }\n }\n \n // Add a final stronger pulse\n DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {\n let strongFeedback = UIImpactFeedbackGenerator(style: .heavy)\n strongFeedback.prepare()\n strongFeedback.impactOccurred()\n }\n } else if isSlapForMe && message.sender != nickname {\n // Very harsh, fast, strong haptic for slaps - multiple sharp impacts\n let impactFeedback = UIImpactFeedbackGenerator(style: .heavy)\n impactFeedback.prepare()\n \n // Rapid-fire heavy impacts to simulate a hard slap\n impactFeedback.impactOccurred()\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) {\n impactFeedback.impactOccurred()\n }\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.06) {\n impactFeedback.impactOccurred()\n }\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.09) {\n impactFeedback.impactOccurred()\n }\n \n // Final extra heavy impact\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {\n let finalImpact = UIImpactFeedbackGenerator(style: .heavy)\n finalImpact.prepare()\n finalImpact.impactOccurred()\n }\n } else if isMentioned && message.sender != nickname {\n // Very prominent haptic for @mentions - triple tap with heavy impact\n let impactFeedback = UIImpactFeedbackGenerator(style: .heavy)\n impactFeedback.prepare()\n impactFeedback.impactOccurred()\n \n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {\n impactFeedback.impactOccurred()\n }\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {\n impactFeedback.impactOccurred()\n }\n } else if message.isPrivate && message.sender != nickname {\n // Heavy haptic for private messages - more pronounced\n let impactFeedback = UIImpactFeedbackGenerator(style: .heavy)\n impactFeedback.prepare()\n impactFeedback.impactOccurred()\n \n // Double tap for extra emphasis\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {\n impactFeedback.impactOccurred()\n }\n } else if message.sender != nickname {\n // Light haptic for public messages from others\n let impactFeedback = UIImpactFeedbackGenerator(style: .light)\n impactFeedback.impactOccurred()\n }\n #endif\n }\n \n // MARK: - Peer Connection Events\n \n func didConnectToPeer(_ peerID: String) {\n isConnected = true\n \n // Register ephemeral session with identity manager\n SecureIdentityStateManager.shared.registerEphemeralSession(peerID: peerID)\n \n // Resolve nickname using helper\n let displayName = resolveNickname(for: peerID)\n \n // Ensure we have a valid display name\n let finalDisplayName = displayName.isEmpty ? \"peer\" : displayName\n \n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"\\(finalDisplayName) connected\",\n timestamp: Date(),\n isRelay: false,\n originalSender: nil\n )\n // Batch system messages\n addMessageToBatch(systemMessage)\n }\n \n func didDisconnectFromPeer(_ peerID: String) {\n // Remove ephemeral session from identity manager\n SecureIdentityStateManager.shared.removeEphemeralSession(peerID: peerID)\n \n // Clear sent read receipts for this peer since they'll need to be resent after reconnection\n // Only clear receipts for messages from this specific peer\n if let messages = privateChats[peerID] {\n for message in messages {\n // Remove read receipts for messages FROM this peer (not TO this peer)\n if message.senderPeerID == peerID {\n sentReadReceipts.remove(message.id)\n }\n }\n }\n \n // Resolve nickname using helper\n let displayName = resolveNickname(for: peerID)\n \n // Ensure we have a valid display name\n let finalDisplayName = displayName.isEmpty ? \"peer\" : displayName\n \n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"\\(finalDisplayName) disconnected\",\n timestamp: Date(),\n isRelay: false,\n originalSender: nil\n )\n // Batch system messages\n addMessageToBatch(systemMessage)\n }\n \n func didUpdatePeerList(_ peers: [String]) {\n // UI updates must run on the main thread.\n // The delegate callback is not guaranteed to be on the main thread.\n DispatchQueue.main.async {\n self.connectedPeers = peers\n self.isConnected = !peers.isEmpty\n \n // Register ephemeral sessions for all connected peers\n for peerID in peers {\n SecureIdentityStateManager.shared.registerEphemeralSession(peerID: peerID)\n }\n \n // Update encryption status for all peers\n self.updateEncryptionStatusForPeers()\n \n // Invalidate RSSI cache since peer data may have changed\n self.invalidateRSSIColorCache()\n\n // Explicitly notify SwiftUI that the object has changed.\n self.objectWillChange.send()\n \n // Check if we need to update private chat peer after reconnection\n if self.selectedPrivateChatFingerprint != nil {\n self.updatePrivateChatPeerIfNeeded()\n }\n \n // Only end private chat if we can't find the peer by fingerprint\n if let currentChatPeer = self.selectedPrivateChatPeer,\n !peers.contains(currentChatPeer),\n self.selectedPrivateChatFingerprint != nil {\n // Try one more time to find by fingerprint\n if self.getCurrentPeerIDForFingerprint(self.selectedPrivateChatFingerprint!) == nil {\n self.endPrivateChat()\n }\n }\n }\n }\n \n // MARK: - Helper Methods\n \n private func parseMentions(from content: String) -> [String] {\n let pattern = \"@([a-zA-Z0-9_]+)\"\n let regex = try? NSRegularExpression(pattern: pattern, options: [])\n let matches = regex?.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) ?? []\n \n var mentions: [String] = []\n let peerNicknames = meshService.getPeerNicknames()\n let allNicknames = Set(peerNicknames.values).union([nickname]) // Include self\n \n for match in matches {\n if let range = Range(match.range(at: 1), in: content) {\n let mentionedName = String(content[range])\n // Only include if it's a valid nickname\n if allNicknames.contains(mentionedName) {\n mentions.append(mentionedName)\n }\n }\n }\n \n return Array(Set(mentions)) // Remove duplicates\n }\n \n func isFavorite(fingerprint: String) -> Bool {\n return SecureIdentityStateManager.shared.isFavorite(fingerprint: fingerprint)\n }\n \n // MARK: - Delivery Tracking\n \n func didReceiveDeliveryAck(_ ack: DeliveryAck) {\n // Find the message and update its delivery status\n updateMessageDeliveryStatus(ack.originalMessageID, status: .delivered(to: ack.recipientNickname, at: ack.timestamp))\n }\n \n func didReceiveReadReceipt(_ receipt: ReadReceipt) {\n // Find the message and update its read status\n updateMessageDeliveryStatus(receipt.originalMessageID, status: .read(by: receipt.readerNickname, at: receipt.timestamp))\n \n // Clear delivery tracking since the message has been read\n // This prevents the timeout from marking it as failed\n DeliveryTracker.shared.clearDeliveryStatus(for: receipt.originalMessageID)\n }\n \n func didUpdateMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) {\n updateMessageDeliveryStatus(messageID, status: status)\n }\n \n private func updateMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) {\n SecureLogger.log(\"Updating UI delivery status for message \\(messageID): \\(status)\", category: SecureLogger.session, level: .debug)\n \n // Helper function to check if we should skip this update\n func shouldSkipUpdate(currentStatus: DeliveryStatus?, newStatus: DeliveryStatus) -> Bool {\n guard let current = currentStatus else { return false }\n \n // Don't downgrade from read to delivered\n switch (current, newStatus) {\n case (.read, .delivered):\n return true\n case (.read, .sent):\n return true\n default:\n return false\n }\n }\n \n // Update in main messages\n if let index = messages.firstIndex(where: { $0.id == messageID }) {\n let currentStatus = messages[index].deliveryStatus\n if !shouldSkipUpdate(currentStatus: currentStatus, newStatus: status) {\n messages[index].deliveryStatus = status\n }\n }\n \n // Update in private chats\n var updatedPrivateChats = privateChats\n for (peerID, chatMessages) in updatedPrivateChats {\n if let index = chatMessages.firstIndex(where: { $0.id == messageID }) {\n let currentStatus = chatMessages[index].deliveryStatus\n if !shouldSkipUpdate(currentStatus: currentStatus, newStatus: status) {\n chatMessages[index].deliveryStatus = status\n updatedPrivateChats[peerID] = chatMessages\n }\n }\n }\n \n // Force complete reassignment to trigger SwiftUI update\n DispatchQueue.main.async { [weak self] in\n guard let self = self else { return }\n self.privateChats = updatedPrivateChats\n self.objectWillChange.send()\n }\n \n }\n \n \n}\n"], ["/bitchat/bitchat/Services/BluetoothMeshService.swift", "//\n// BluetoothMeshService.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # BluetoothMeshService\n///\n/// The core networking component that manages peer-to-peer Bluetooth LE connections\n/// and implements the BitChat mesh networking protocol.\n///\n/// ## Overview\n/// This service is the heart of BitChat's decentralized architecture. It manages all\n/// Bluetooth LE communications, enabling devices to form an ad-hoc mesh network without\n/// any infrastructure. The service handles:\n/// - Peer discovery and connection management\n/// - Message routing and relay functionality\n/// - Protocol version negotiation\n/// - Connection state tracking and recovery\n/// - Integration with the Noise encryption layer\n///\n/// ## Architecture\n/// The service operates in a dual mode:\n/// - **Central Mode**: Scans for and connects to other BitChat devices\n/// - **Peripheral Mode**: Advertises its presence and accepts connections\n///\n/// This dual-mode operation enables true peer-to-peer connectivity where any device\n/// can initiate or accept connections, forming a resilient mesh topology.\n///\n/// ## Mesh Networking\n/// Messages are relayed through the mesh using a TTL (Time To Live) mechanism:\n/// - Each message has a TTL that decrements at each hop\n/// - Messages are cached to prevent loops (via Bloom filters)\n/// - Store-and-forward ensures delivery to temporarily offline peers\n///\n/// ## Connection Lifecycle\n/// 1. **Discovery**: Devices scan and advertise simultaneously\n/// 2. **Connection**: BLE connection established\n/// 3. **Version Negotiation**: Ensure protocol compatibility\n/// 4. **Authentication**: Noise handshake for encrypted channels\n/// 5. **Message Exchange**: Bidirectional communication\n/// 6. **Disconnection**: Graceful cleanup and state preservation\n///\n/// ## Security Integration\n/// - Coordinates with NoiseEncryptionService for private messages\n/// - Maintains peer identity mappings\n/// - Handles lazy handshake initiation\n/// - Ensures message authenticity\n///\n/// ## Performance Optimizations\n/// - Connection pooling and reuse\n/// - Adaptive scanning based on battery level\n/// - Message batching for efficiency\n/// - Smart retry logic with exponential backoff\n///\n/// ## Thread Safety\n/// All public methods are thread-safe. The service uses:\n/// - Serial queues for Core Bluetooth operations\n/// - Thread-safe collections for peer management\n/// - Atomic operations for state updates\n///\n/// ## Error Handling\n/// - Automatic reconnection for lost connections\n/// - Graceful degradation when Bluetooth is unavailable\n/// - Clear error reporting through BitchatDelegate\n///\n/// ## Usage Example\n/// ```swift\n/// let meshService = BluetoothMeshService()\n/// meshService.delegate = self\n/// meshService.localUserID = \"user123\"\n/// meshService.startMeshService()\n/// ```\n///\n\nimport Foundation\nimport CoreBluetooth\nimport Combine\nimport CryptoKit\nimport os.log\n#if os(macOS)\nimport AppKit\nimport IOKit.ps\n#else\nimport UIKit\n#endif\n\n// Hex encoding/decoding is now in BinaryEncodingUtils.swift\n\n// Extension for TimeInterval to Data conversion\nextension TimeInterval {\n var data: Data {\n var value = self\n return Data(bytes: &value, count: MemoryLayout.size)\n }\n}\n\n// Version negotiation state\nenum VersionNegotiationState {\n case none\n case helloSent\n case ackReceived(version: UInt8)\n case failed(reason: String)\n}\n\n// Peer connection state tracking\nenum PeerConnectionState: CustomStringConvertible {\n case disconnected\n case connecting\n case connected // BLE connected but not authenticated\n case authenticating // Performing handshake\n case authenticated // Handshake complete, ready for messages\n \n var isAvailable: Bool {\n switch self {\n case .authenticated:\n return true\n default:\n return false\n }\n }\n \n var description: String {\n switch self {\n case .disconnected: return \"disconnected\"\n case .connecting: return \"connecting\"\n case .connected: return \"connected\"\n case .authenticating: return \"authenticating\"\n case .authenticated: return \"authenticated\"\n }\n }\n}\n\n/// Manages all Bluetooth LE networking operations for the BitChat mesh network.\n/// This class handles peer discovery, connection management, message routing,\n/// and protocol negotiation. It acts as both a BLE central (scanner) and\n/// peripheral (advertiser) simultaneously to enable true peer-to-peer connectivity.\nclass BluetoothMeshService: NSObject {\n // MARK: - Constants\n \n static let serviceUUID = CBUUID(string: \"F47B5E2D-4A9E-4C5A-9B3F-8E1D2C3A4B5C\")\n static let characteristicUUID = CBUUID(string: \"A1B2C3D4-E5F6-4A5B-8C9D-0E1F2A3B4C5D\")\n \n // MARK: - Core Bluetooth Properties\n \n private var centralManager: CBCentralManager?\n private var peripheralManager: CBPeripheralManager?\n private var discoveredPeripherals: [CBPeripheral] = []\n private var connectedPeripherals: [String: CBPeripheral] = [:]\n private var peripheralCharacteristics: [CBPeripheral: CBCharacteristic] = [:]\n \n // MARK: - Connection Tracking\n \n private var lastConnectionTime: [String: Date] = [:] // Track when peers last connected\n private var lastSuccessfulMessageTime: [String: Date] = [:] // Track last successful message exchange\n private var lastHeardFromPeer: [String: Date] = [:] // Track last time we received ANY packet from peer\n \n // MARK: - Peer Availability\n \n // Peer availability tracking\n private var peerAvailabilityState: [String: Bool] = [:] // true = available, false = unavailable\n private let peerAvailabilityTimeout: TimeInterval = 30.0 // Mark unavailable after 30s of no response\n private var availabilityCheckTimer: Timer?\n \n // MARK: - Peripheral Management\n \n private var characteristic: CBMutableCharacteristic?\n private var subscribedCentrals: [CBCentral] = []\n \n // MARK: - Thread-Safe Collections\n \n private let collectionsQueue = DispatchQueue(label: \"bitchat.collections\", attributes: .concurrent)\n private var peerNicknames: [String: String] = [:]\n private var activePeers: Set = [] // Track all active peers\n private var peerRSSI: [String: NSNumber] = [:] // Track RSSI values for peers\n private var peripheralRSSI: [String: NSNumber] = [:] // Track RSSI by peripheral ID during discovery\n private var rssiRetryCount: [String: Int] = [:] // Track RSSI retry attempts per peripheral\n \n // MARK: - Encryption Queues\n \n // Per-peer encryption queues to prevent nonce desynchronization\n private var peerEncryptionQueues: [String: DispatchQueue] = [:]\n private let encryptionQueuesLock = NSLock()\n \n // MARK: - Peer Identity Rotation\n // Mappings between ephemeral peer IDs and permanent fingerprints\n private var peerIDToFingerprint: [String: String] = [:] // PeerID -> Fingerprint\n private var fingerprintToPeerID: [String: String] = [:] // Fingerprint -> Current PeerID\n private var peerIdentityBindings: [String: PeerIdentityBinding] = [:] // Fingerprint -> Full binding\n private var previousPeerID: String? // Our previous peer ID for grace period\n private var rotationTimestamp: Date? // When we last rotated\n private let rotationGracePeriod: TimeInterval = 60.0 // 1 minute grace period\n private var rotationLocked = false // Prevent rotation during critical operations\n private var rotationTimer: Timer? // Timer for scheduled rotations\n \n // MARK: - Identity Cache\n // In-memory cache for peer public keys to avoid keychain lookups\n private var peerPublicKeyCache: [String: Data] = [:] // PeerID -> Public Key Data\n private var peerSigningKeyCache: [String: Data] = [:] // PeerID -> Signing Key Data\n private let identityCacheTTL: TimeInterval = 3600.0 // 1 hour TTL\n private var identityCacheTimestamps: [String: Date] = [:] // Track when entries were cached\n \n // MARK: - Delegates and Services\n \n weak var delegate: BitchatDelegate?\n private let noiseService = NoiseEncryptionService()\n private let handshakeCoordinator = NoiseHandshakeCoordinator()\n \n // MARK: - Protocol Version Negotiation\n \n // Protocol version negotiation state\n private var versionNegotiationState: [String: VersionNegotiationState] = [:]\n private var negotiatedVersions: [String: UInt8] = [:] // peerID -> agreed version\n \n // MARK: - Write Queue for Disconnected Peripherals\n private struct QueuedWrite {\n let data: Data\n let peripheralID: String\n let peerID: String?\n let timestamp: Date\n let retryCount: Int\n }\n \n private var writeQueue: [String: [QueuedWrite]] = [:] // PeripheralID -> Queue of writes\n private let writeQueueLock = NSLock()\n private let maxWriteQueueSize = 50 // Max queued writes per peripheral\n private let maxWriteRetries = 3\n private let writeQueueTTL: TimeInterval = 60.0 // Expire queued writes after 1 minute\n private var writeQueueTimer: Timer? // Timer for processing expired writes\n \n // MARK: - Connection Pooling\n private let maxConnectedPeripherals = 10 // Limit simultaneous connections\n private let maxScanningDuration: TimeInterval = 5.0 // Stop scanning after 5 seconds to save battery\n \n func getNoiseService() -> NoiseEncryptionService {\n return noiseService\n }\n \n \n private func cleanExpiredIdentityCache() {\n collectionsQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n let now = Date()\n var expiredPeerIDs: [String] = []\n \n for (peerID, timestamp) in self.identityCacheTimestamps {\n if now.timeIntervalSince(timestamp) >= self.identityCacheTTL {\n expiredPeerIDs.append(peerID)\n }\n }\n \n for peerID in expiredPeerIDs {\n self.peerPublicKeyCache.removeValue(forKey: peerID)\n self.peerSigningKeyCache.removeValue(forKey: peerID)\n self.identityCacheTimestamps.removeValue(forKey: peerID)\n }\n \n if !expiredPeerIDs.isEmpty {\n SecureLogger.log(\"Cleaned \\(expiredPeerIDs.count) expired identity cache entries\", \n category: SecureLogger.session, level: .debug)\n }\n }\n }\n \n // MARK: - Write Queue Management\n \n private func writeToPeripheral(_ data: Data, peripheral: CBPeripheral, characteristic: CBCharacteristic, peerID: String? = nil) {\n let peripheralID = peripheral.identifier.uuidString\n \n // Double check the peripheral state to avoid API misuse\n guard peripheral.state == .connected else {\n // Queue write for disconnected peripheral\n queueWrite(data: data, peripheralID: peripheralID, peerID: peerID)\n return\n }\n \n // Verify characteristic is valid and writable\n guard characteristic.properties.contains(.write) || characteristic.properties.contains(.writeWithoutResponse) else {\n SecureLogger.log(\"Characteristic does not support writing for peripheral \\(peripheralID)\", \n category: SecureLogger.session, level: .warning)\n return\n }\n \n // Direct write if connected\n let writeType: CBCharacteristicWriteType = data.count > 512 ? .withResponse : .withoutResponse\n peripheral.writeValue(data, for: characteristic, type: writeType)\n \n // Update activity tracking\n updatePeripheralActivity(peripheralID)\n }\n \n private func queueWrite(data: Data, peripheralID: String, peerID: String?) {\n writeQueueLock.lock()\n defer { writeQueueLock.unlock() }\n \n // Check backpressure - drop oldest if queue is full\n var queue = writeQueue[peripheralID] ?? []\n \n if queue.count >= maxWriteQueueSize {\n // Remove oldest entries\n let removeCount = queue.count - maxWriteQueueSize + 1\n queue.removeFirst(removeCount)\n SecureLogger.log(\"Write queue full for \\(peripheralID), dropped \\(removeCount) oldest writes\", \n category: SecureLogger.session, level: .warning)\n }\n \n let queuedWrite = QueuedWrite(\n data: data,\n peripheralID: peripheralID,\n peerID: peerID,\n timestamp: Date(),\n retryCount: 0\n )\n \n queue.append(queuedWrite)\n writeQueue[peripheralID] = queue\n \n SecureLogger.log(\"Queued write for disconnected peripheral \\(peripheralID), queue size: \\(queue.count)\", \n category: SecureLogger.session, level: .debug)\n }\n \n private func processWriteQueue(for peripheral: CBPeripheral) {\n guard peripheral.state == .connected,\n let characteristic = peripheralCharacteristics[peripheral] else { return }\n \n let peripheralID = peripheral.identifier.uuidString\n \n writeQueueLock.lock()\n let queue = writeQueue[peripheralID] ?? []\n writeQueue[peripheralID] = []\n writeQueueLock.unlock()\n \n if !queue.isEmpty {\n SecureLogger.log(\"Processing \\(queue.count) queued writes for \\(peripheralID)\", \n category: SecureLogger.session, level: .info)\n }\n \n // Process queued writes with small delay between them\n for (index, queuedWrite) in queue.enumerated() {\n DispatchQueue.main.asyncAfter(deadline: .now() + Double(index) * 0.01) { [weak self] in\n guard let self = self,\n peripheral.state == .connected,\n characteristic.properties.contains(.write) || characteristic.properties.contains(.writeWithoutResponse) else { \n return \n }\n \n let writeType: CBCharacteristicWriteType = queuedWrite.data.count > 512 ? .withResponse : .withoutResponse\n peripheral.writeValue(queuedWrite.data, for: characteristic, type: writeType)\n \n // Update activity tracking\n self.updatePeripheralActivity(peripheralID)\n }\n }\n }\n \n private func cleanExpiredWriteQueues() {\n writeQueueLock.lock()\n defer { writeQueueLock.unlock() }\n \n let now = Date()\n var expiredWrites = 0\n \n for (peripheralID, queue) in writeQueue {\n let filteredQueue = queue.filter { write in\n now.timeIntervalSince(write.timestamp) < writeQueueTTL\n }\n \n expiredWrites += queue.count - filteredQueue.count\n \n if filteredQueue.isEmpty {\n writeQueue.removeValue(forKey: peripheralID)\n } else {\n writeQueue[peripheralID] = filteredQueue\n }\n }\n \n if expiredWrites > 0 {\n SecureLogger.log(\"Cleaned \\(expiredWrites) expired queued writes\", \n category: SecureLogger.session, level: .debug)\n }\n }\n // MARK: - Message Processing\n \n private let messageQueue = DispatchQueue(label: \"bitchat.messageQueue\", attributes: .concurrent) // Concurrent queue with barriers\n \n // Message state tracking for better duplicate detection\n private struct MessageState {\n let firstSeen: Date\n var lastSeen: Date\n var seenCount: Int\n var relayed: Bool\n var acknowledged: Bool\n \n mutating func updateSeen() {\n lastSeen = Date()\n seenCount += 1\n }\n }\n \n private var processedMessages = [String: MessageState]() // Track full message state\n private let processedMessagesLock = NSLock()\n private let maxProcessedMessages = 10000\n \n // Special handling for identity announces to prevent duplicates\n private var recentIdentityAnnounces = [String: Date]() // peerID -> last seen time\n private let identityAnnounceDuplicateWindow: TimeInterval = 30.0 // 30 second window\n \n // MARK: - Network State Management\n \n private let maxTTL: UInt8 = 7 // Maximum hops for long-distance delivery\n private var announcedToPeers = Set() // Track which peers we've announced to\n private var announcedPeers = Set() // Track peers who have already been announced\n private var hasNotifiedNetworkAvailable = false // Track if we've notified about network availability\n private var lastNetworkNotificationTime: Date? // Track when we last sent a network notification\n private var networkBecameEmptyTime: Date? // Track when the network became empty\n private let networkNotificationCooldown: TimeInterval = 300 // 5 minutes between notifications\n private let networkEmptyResetDelay: TimeInterval = 60 // 1 minute before resetting notification flag\n private var intentionalDisconnects = Set() // Track peripherals we're disconnecting intentionally\n private var gracefullyLeftPeers = Set() // Track peers that sent leave messages\n private var gracefulLeaveTimestamps: [String: Date] = [:] // Track when peers left\n private let gracefulLeaveExpirationTime: TimeInterval = 300.0 // 5 minutes\n private var peerLastSeenTimestamps = LRUCache(maxSize: 100) // Bounded cache for peer timestamps\n private var cleanupTimer: Timer? // Timer to clean up stale peers\n \n // MARK: - Store-and-Forward Cache\n \n // Store-and-forward message cache\n private struct StoredMessage {\n let packet: BitchatPacket\n let timestamp: Date\n let messageID: String\n let isForFavorite: Bool // Messages for favorites stored indefinitely\n }\n private var messageCache: [StoredMessage] = []\n private let messageCacheTimeout: TimeInterval = 43200 // 12 hours for regular peers\n private let maxCachedMessages = 100 // For regular peers\n private let maxCachedMessagesForFavorites = 1000 // Much larger cache for favorites\n private var favoriteMessageQueue: [String: [StoredMessage]] = [:] // Per-favorite message queues\n private let deliveredMessages = BoundedSet(maxSize: 5000) // Bounded to prevent memory growth\n private var cachedMessagesSentToPeer = Set() // Track which peers have already received cached messages\n private let receivedMessageTimestamps = LRUCache(maxSize: 1000) // Bounded cache\n private let recentlySentMessages = BoundedSet(maxSize: 500) // Short-term bounded cache\n private let lastMessageFromPeer = LRUCache(maxSize: 100) // Bounded cache\n private let processedNoiseMessages = BoundedSet(maxSize: 1000) // Bounded cache\n \n // MARK: - Battery and Performance Optimization\n \n // Battery and range optimizations\n private var scanDutyCycleTimer: Timer?\n private var isActivelyScanning = true\n private var activeScanDuration: TimeInterval = 5.0 // will be adjusted based on battery\n private var scanPauseDuration: TimeInterval = 10.0 // will be adjusted based on battery\n private var lastRSSIUpdate: [String: Date] = [:] // Throttle RSSI updates\n private var batteryMonitorTimer: Timer?\n private var currentBatteryLevel: Float = 1.0 // Default to full battery\n \n // Battery optimizer integration\n private let batteryOptimizer = BatteryOptimizer.shared\n private var batteryOptimizerCancellables = Set()\n \n // Peer list update debouncing\n private var peerListUpdateTimer: Timer?\n private let peerListUpdateDebounceInterval: TimeInterval = 0.1 // 100ms debounce for more responsive updates\n \n // Track when we last sent identity announcements to prevent flooding\n private var lastIdentityAnnounceTimes: [String: Date] = [:]\n private let identityAnnounceMinInterval: TimeInterval = 10.0 // Minimum 10 seconds between announcements per peer\n \n // Track handshake attempts to handle timeouts\n private var handshakeAttemptTimes: [String: Date] = [:]\n private let handshakeTimeout: TimeInterval = 5.0 // 5 seconds before retrying\n \n // Pending private messages waiting for handshake\n private var pendingPrivateMessages: [String: [(content: String, recipientNickname: String, messageID: String)]] = [:]\n \n // MARK: - Noise Protocol State\n \n // Noise session state tracking for lazy handshakes\n private var noiseSessionStates: [String: LazyHandshakeState] = [:]\n \n // MARK: - Cover Traffic\n \n // Cover traffic for privacy\n private var coverTrafficTimer: Timer?\n private let coverTrafficPrefix = \"☂DUMMY☂\" // Prefix to identify dummy messages after decryption\n private var lastCoverTrafficTime = Date()\n \n // MARK: - Connection State\n \n // Connection state tracking\n private var peerConnectionStates: [String: PeerConnectionState] = [:]\n private let connectionStateQueue = DispatchQueue(label: \"chat.bitchat.connectionState\", attributes: .concurrent)\n \n // MARK: - Protocol ACK Tracking\n \n // Protocol-level ACK tracking\n private var pendingAcks: [String: (packet: BitchatPacket, timestamp: Date, retries: Int)] = [:]\n private let ackTimeout: TimeInterval = 5.0 // 5 seconds to receive ACK\n private let maxAckRetries = 3\n private var ackTimer: Timer?\n private var advertisingTimer: Timer? // Timer for interval-based advertising\n private var connectionKeepAliveTimer: Timer? // Timer to send keepalive pings\n private let keepAliveInterval: TimeInterval = 20.0 // Send keepalive every 20 seconds\n \n // MARK: - Timing and Delays\n \n // Timing randomization for privacy (now with exponential distribution)\n private let minMessageDelay: TimeInterval = 0.01 // 10ms minimum for faster sync\n private let maxMessageDelay: TimeInterval = 0.1 // 100ms maximum for faster sync\n \n // MARK: - RSSI Management\n \n // Dynamic RSSI threshold based on network size (smart compromise)\n private var dynamicRSSIThreshold: Int {\n let peerCount = activePeers.count\n if peerCount < 5 {\n return -95 // Maximum range when network is small\n } else if peerCount < 10 {\n return -92 // Slightly reduced range\n } else {\n return -90 // Conservative for larger networks\n }\n }\n \n // MARK: - Fragment Handling\n \n // Fragment handling with security limits\n private var incomingFragments: [String: [Int: Data]] = [:] // fragmentID -> [index: data]\n private var fragmentMetadata: [String: (originalType: UInt8, totalFragments: Int, timestamp: Date)] = [:]\n private let maxFragmentSize = 469 // 512 bytes max MTU - 43 bytes for headers and metadata\n private let maxConcurrentFragmentSessions = 20 // Limit concurrent fragment sessions to prevent DoS\n private let fragmentTimeout: TimeInterval = 30 // 30 seconds timeout for incomplete fragments\n \n // MARK: - Peer Identity\n \n var myPeerID: String\n \n // MARK: - Scaling Optimizations\n \n // Connection pooling\n private var connectionPool: [String: CBPeripheral] = [:]\n private var connectionAttempts: [String: Int] = [:]\n private var connectionBackoff: [String: TimeInterval] = [:]\n private var lastActivityByPeripheralID: [String: Date] = [:] // Track last activity for LRU\n private var peerIDByPeripheralID: [String: String] = [:] // Map peripheral ID to peer ID\n private let maxConnectionAttempts = 3\n private let baseBackoffInterval: TimeInterval = 1.0\n \n // MARK: - Peripheral Mapping\n \n // Simplified peripheral mapping system\n private struct PeripheralMapping {\n let peripheral: CBPeripheral\n var peerID: String? // nil until we receive announce\n var rssi: NSNumber?\n var lastActivity: Date\n \n var isIdentified: Bool { peerID != nil }\n }\n private var peripheralMappings: [String: PeripheralMapping] = [:] // peripheralID -> mapping\n \n // Helper methods for peripheral mapping\n private func registerPeripheral(_ peripheral: CBPeripheral) {\n let peripheralID = peripheral.identifier.uuidString\n peripheralMappings[peripheralID] = PeripheralMapping(\n peripheral: peripheral,\n peerID: nil,\n rssi: nil,\n lastActivity: Date()\n )\n }\n \n private func updatePeripheralMapping(peripheralID: String, peerID: String) {\n guard var mapping = peripheralMappings[peripheralID] else { return }\n \n // Remove old temp mapping if it exists\n let tempID = peripheralID\n if connectedPeripherals[tempID] != nil {\n connectedPeripherals.removeValue(forKey: tempID)\n }\n \n mapping.peerID = peerID\n mapping.lastActivity = Date()\n peripheralMappings[peripheralID] = mapping\n \n // Update legacy mappings\n peerIDByPeripheralID[peripheralID] = peerID\n connectedPeripherals[peerID] = mapping.peripheral\n \n // Transfer RSSI\n if let rssi = mapping.rssi {\n peerRSSI[peerID] = rssi\n }\n }\n \n private func updatePeripheralRSSI(peripheralID: String, rssi: NSNumber) {\n guard var mapping = peripheralMappings[peripheralID] else { return }\n mapping.rssi = rssi\n mapping.lastActivity = Date()\n peripheralMappings[peripheralID] = mapping\n \n // Update peer RSSI if we have the peer ID\n if let peerID = mapping.peerID {\n peerRSSI[peerID] = rssi\n }\n }\n \n private func findPeripheralForPeerID(_ peerID: String) -> CBPeripheral? {\n for (_, mapping) in peripheralMappings {\n if mapping.peerID == peerID {\n return mapping.peripheral\n }\n }\n return nil\n }\n \n // MARK: - Probabilistic Flooding\n \n // Probabilistic flooding\n private var relayProbability: Double = 1.0 // Start at 100%, decrease with peer count\n private let minRelayProbability: Double = 0.4 // Minimum 40% relay chance - ensures coverage\n \n // MARK: - Message Aggregation\n \n // Message aggregation\n private var pendingMessages: [(message: BitchatPacket, destination: String?)] = []\n private var aggregationTimer: Timer?\n private var aggregationWindow: TimeInterval = 0.1 // 100ms window\n private let maxAggregatedMessages = 5\n \n // MARK: - Bloom Filter\n \n // Optimized Bloom filter for efficient duplicate detection\n private var messageBloomFilter = OptimizedBloomFilter(expectedItems: 2000, falsePositiveRate: 0.01)\n private var bloomFilterResetTimer: Timer?\n \n // MARK: - Network Size Estimation\n \n // Network size estimation\n private var estimatedNetworkSize: Int {\n return max(activePeers.count, connectedPeripherals.count)\n }\n \n // Adaptive parameters based on network size\n private var adaptiveTTL: UInt8 {\n // Keep TTL high enough for messages to travel far\n let networkSize = estimatedNetworkSize\n if networkSize <= 20 {\n return 6 // Small networks: max distance\n } else if networkSize <= 50 {\n return 5 // Medium networks: still good reach\n } else if networkSize <= 100 {\n return 4 // Large networks: reasonable reach\n } else {\n return 3 // Very large networks: minimum viable\n }\n }\n \n private var adaptiveRelayProbability: Double {\n // Adjust relay probability based on network size\n // Small networks don't need 100% relay - RSSI will handle edge nodes\n let networkSize = estimatedNetworkSize\n if networkSize <= 2 {\n return 0.0 // 0% for 2 nodes - no relay needed with only 2 peers\n } else if networkSize <= 5 {\n return 0.5 // 50% for very small networks\n } else if networkSize <= 10 {\n return 0.6 // 60% for small networks\n } else if networkSize <= 30 {\n return 0.7 // 70% for medium networks\n } else if networkSize <= 50 {\n return 0.6 // 60% for larger networks\n } else if networkSize <= 100 {\n return 0.5 // 50% for big networks\n } else {\n return 0.4 // 40% minimum for very large networks\n }\n }\n \n // MARK: - Relay Cancellation\n \n // Relay cancellation mechanism to prevent duplicate relays\n private var pendingRelays: [String: DispatchWorkItem] = [:] // messageID -> relay task\n private let pendingRelaysLock = NSLock()\n private let relayCancellationWindow: TimeInterval = 0.05 // 50ms window to detect other relays\n \n // MARK: - Memory Management\n \n // Global memory limits to prevent unbounded growth\n private let maxPendingPrivateMessages = 100\n private let maxCachedMessagesSentToPeer = 1000\n private let maxMemoryUsageBytes = 50 * 1024 * 1024 // 50MB limit\n private var memoryCleanupTimer: Timer?\n \n // Track acknowledged packets to prevent unnecessary retries\n private var acknowledgedPackets = Set()\n private let acknowledgedPacketsLock = NSLock()\n \n // MARK: - Rate Limiting\n \n // Rate limiting for flood control with separate limits for different message types\n private var messageRateLimiter: [String: [Date]] = [:] // peerID -> recent message timestamps\n private var protocolMessageRateLimiter: [String: [Date]] = [:] // peerID -> protocol msg timestamps\n private let rateLimiterLock = NSLock()\n private let rateLimitWindow: TimeInterval = 60.0 // 1 minute window\n private let maxChatMessagesPerPeerPerMinute = 300 // Allow fast typing (5 msgs/sec)\n private let maxProtocolMessagesPerPeerPerMinute = 100 // Protocol messages\n private let maxTotalMessagesPerMinute = 2000 // Increased for legitimate use\n private var totalMessageTimestamps: [Date] = []\n \n // MARK: - BLE Advertisement\n \n // BLE advertisement for lightweight presence\n private var advertisementData: [String: Any] = [:]\n private var isAdvertising = false\n \n // MARK: - Message Aggregation Implementation\n \n private func startAggregationTimer() {\n aggregationTimer?.invalidate()\n aggregationTimer = Timer.scheduledTimer(withTimeInterval: aggregationWindow, repeats: false) { [weak self] _ in\n self?.flushPendingMessages()\n }\n }\n \n private func flushPendingMessages() {\n guard !pendingMessages.isEmpty else { return }\n \n messageQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Group messages by destination\n var messagesByDestination: [String?: [BitchatPacket]] = [:]\n \n for (message, destination) in self.pendingMessages {\n if messagesByDestination[destination] == nil {\n messagesByDestination[destination] = []\n }\n messagesByDestination[destination]?.append(message)\n }\n \n // Send aggregated messages\n for (destination, messages) in messagesByDestination {\n if messages.count == 1 {\n // Single message, send normally\n if destination == nil {\n self.broadcastPacket(messages[0])\n } else if let dest = destination,\n let peripheral = self.connectedPeripherals[dest],\n let characteristic = self.peripheralCharacteristics[peripheral] {\n if let data = messages[0].toBinaryData() {\n self.writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: dest)\n }\n }\n } else {\n // Multiple messages - could aggregate into a single packet\n // For now, send with minimal delay between them\n for (index, message) in messages.enumerated() {\n let delay = Double(index) * 0.02 // 20ms between messages\n DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in\n if destination == nil {\n self?.broadcastPacket(message)\n } else if let dest = destination,\n let peripheral = self?.connectedPeripherals[dest],\n peripheral.state == .connected,\n let characteristic = self?.peripheralCharacteristics[peripheral] {\n if let data = message.toBinaryData() {\n self?.writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: dest)\n }\n }\n }\n }\n }\n }\n \n // Clear pending messages\n self.pendingMessages.removeAll()\n }\n }\n \n // Removed getPublicKeyFingerprint - no longer needed with Noise\n \n // MARK: - Peer Identity Mapping\n \n /// Retrieves the cryptographic fingerprint for a given peer.\n /// - Parameter peerID: The ephemeral peer ID\n /// - Returns: The peer's Noise static key fingerprint if known, nil otherwise\n /// - Note: This fingerprint remains stable across peer ID rotations\n func getPeerFingerprint(_ peerID: String) -> String? {\n return noiseService.getPeerFingerprint(peerID)\n }\n \n // Get fingerprint for a peer ID\n func getFingerprint(for peerID: String) -> String? {\n return collectionsQueue.sync {\n peerIDToFingerprint[peerID]\n }\n }\n \n /// Checks if a given peer ID belongs to the local device.\n /// - Parameter peerID: The peer ID to check\n /// - Returns: true if this is our current or recent peer ID, false otherwise\n /// - Note: Accounts for grace period during peer ID rotation\n func isPeerIDOurs(_ peerID: String) -> Bool {\n if peerID == myPeerID {\n return true\n }\n \n // Check if it's our previous ID within grace period\n if let previousID = previousPeerID,\n peerID == previousID,\n let rotationTime = rotationTimestamp,\n Date().timeIntervalSince(rotationTime) < rotationGracePeriod {\n return true\n }\n \n return false\n }\n \n /// Updates the identity binding for a peer when they rotate their ephemeral ID.\n /// - Parameters:\n /// - newPeerID: The peer's new ephemeral ID\n /// - fingerprint: The peer's stable cryptographic fingerprint\n /// - binding: The complete identity binding information\n /// - Note: This maintains continuity of identity across peer ID rotations\n func updatePeerBinding(_ newPeerID: String, fingerprint: String, binding: PeerIdentityBinding) {\n // Use async to ensure we're not blocking during view updates\n collectionsQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n var oldPeerID: String? = nil\n \n // Remove old peer ID mapping if exists\n if let existingPeerID = self.fingerprintToPeerID[fingerprint], existingPeerID != newPeerID {\n oldPeerID = existingPeerID\n SecureLogger.log(\"Peer ID rotation detected: \\(existingPeerID) -> \\(newPeerID) for fingerprint \\(fingerprint)\", category: SecureLogger.security, level: .info)\n \n // Transfer gracefullyLeftPeers state from old to new peer ID\n if self.gracefullyLeftPeers.contains(existingPeerID) {\n self.gracefullyLeftPeers.remove(existingPeerID)\n self.gracefullyLeftPeers.insert(newPeerID)\n SecureLogger.log(\"Transferred gracefullyLeft state from \\(existingPeerID) to \\(newPeerID)\", \n category: SecureLogger.session, level: .debug)\n }\n \n self.peerIDToFingerprint.removeValue(forKey: existingPeerID)\n \n // Transfer nickname if known\n if let nickname = self.peerNicknames[existingPeerID] {\n self.peerNicknames[newPeerID] = nickname\n self.peerNicknames.removeValue(forKey: existingPeerID)\n }\n \n // Update active peers set - always remove old peer ID\n self.activePeers.remove(existingPeerID)\n // Don't pre-insert the new peer ID - let the announce packet handle it\n // This ensures the connect message logic works properly\n \n // Transfer any connected peripherals\n if let peripheral = self.connectedPeripherals[existingPeerID] {\n self.connectedPeripherals.removeValue(forKey: existingPeerID)\n self.connectedPeripherals[newPeerID] = peripheral\n }\n \n // Transfer RSSI data\n if let rssi = self.peerRSSI[existingPeerID] {\n self.peerRSSI.removeValue(forKey: existingPeerID)\n self.peerRSSI[newPeerID] = rssi\n }\n \n // Transfer lastHeardFromPeer tracking\n if let lastHeard = self.lastHeardFromPeer[existingPeerID] {\n self.lastHeardFromPeer.removeValue(forKey: existingPeerID)\n self.lastHeardFromPeer[newPeerID] = lastHeard\n }\n \n // Clean up connection state for old peer ID\n self.peerConnectionStates.removeValue(forKey: existingPeerID)\n // Don't transfer connection state - let it be re-established naturally\n \n // Clean up any pending messages for old peer ID\n self.pendingPrivateMessages.removeValue(forKey: existingPeerID)\n // Don't transfer pending messages - they would be stale anyway\n }\n \n // Add new mapping\n self.peerIDToFingerprint[newPeerID] = fingerprint\n self.fingerprintToPeerID[fingerprint] = newPeerID\n self.peerIdentityBindings[fingerprint] = binding\n \n // Cache public keys to avoid keychain lookups\n self.peerPublicKeyCache[newPeerID] = binding.publicKey\n self.peerSigningKeyCache[newPeerID] = binding.signingPublicKey\n self.identityCacheTimestamps[newPeerID] = Date()\n \n // Also update nickname from binding\n self.peerNicknames[newPeerID] = binding.nickname\n \n // Notify about the change if it's a rotation\n if let oldID = oldPeerID {\n // Clear the old session instead of migrating it\n // This ensures both peers do a fresh handshake after ID rotation\n self.cleanupPeerCryptoState(oldID)\n self.handshakeCoordinator.resetHandshakeState(for: newPeerID)\n \n // Log the peer ID rotation\n SecureLogger.log(\"Cleared session for peer ID rotation: \\(oldID) -> \\(newPeerID), will establish fresh handshake\", \n category: SecureLogger.handshake, level: .info)\n \n self.notifyPeerIDChange(oldPeerID: oldID, newPeerID: newPeerID, fingerprint: fingerprint)\n \n // Lazy handshake: No longer initiate handshake on peer ID rotation\n // Handshake will be initiated when first private message is sent\n }\n }\n }\n \n // Public method to get current peer ID for a fingerprint\n func getCurrentPeerIDForFingerprint(_ fingerprint: String) -> String? {\n return collectionsQueue.sync {\n return fingerprintToPeerID[fingerprint]\n }\n }\n \n // Public method to get all current peer IDs for known fingerprints\n func getCurrentPeerIDs() -> [String: String] {\n return collectionsQueue.sync {\n return fingerprintToPeerID\n }\n }\n \n // Notify delegate when peer ID changes\n private func notifyPeerIDChange(oldPeerID: String, newPeerID: String, fingerprint: String) {\n DispatchQueue.main.async { [weak self] in\n // Remove old peer ID from active peers and announcedPeers\n self?.collectionsQueue.sync(flags: .barrier) {\n _ = self?.activePeers.remove(oldPeerID)\n // Don't pre-insert the new peer ID - let the announce packet handle it\n // This ensures the connect message logic works properly\n }\n \n // Also remove from announcedPeers so the new ID can trigger a connect message\n self?.announcedPeers.remove(oldPeerID)\n \n // Update peer list\n self?.notifyPeerListUpdate(immediate: true)\n \n // Don't send disconnect/connect messages for peer ID rotation\n // The peer didn't actually disconnect, they just rotated their ID\n // This prevents confusing messages like \"3a7e1c2c0d8943b9 disconnected\"\n \n // Instead, notify the delegate about the peer ID change if needed\n // (Could add a new delegate method for this in the future)\n }\n }\n \n // MARK: - Peer Connection Management\n \n func getCachedPublicKey(for peerID: String) -> Data? {\n return collectionsQueue.sync {\n // Check if cache entry exists and is not expired\n if let timestamp = identityCacheTimestamps[peerID],\n Date().timeIntervalSince(timestamp) < identityCacheTTL {\n return peerPublicKeyCache[peerID]\n }\n return nil\n }\n }\n \n func getCachedSigningKey(for peerID: String) -> Data? {\n return collectionsQueue.sync {\n // Check if cache entry exists and is not expired\n if let timestamp = identityCacheTimestamps[peerID],\n Date().timeIntervalSince(timestamp) < identityCacheTTL {\n return peerSigningKeyCache[peerID]\n }\n return nil\n }\n }\n \n private func updatePeerConnectionState(_ peerID: String, state: PeerConnectionState) {\n connectionStateQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n let previousState = self.peerConnectionStates[peerID]\n self.peerConnectionStates[peerID] = state\n \n SecureLogger.log(\"Peer \\(peerID) connection state: \\(previousState?.description ?? \"nil\") -> \\(state)\", \n category: SecureLogger.session, level: .debug)\n \n // Update activePeers based on authentication state\n self.collectionsQueue.async(flags: .barrier) {\n switch state {\n case .authenticated:\n if !self.activePeers.contains(peerID) {\n self.activePeers.insert(peerID)\n SecureLogger.log(\"Added \\(peerID) to activePeers (authenticated)\", \n category: SecureLogger.session, level: .info)\n }\n case .disconnected:\n if self.activePeers.contains(peerID) {\n self.activePeers.remove(peerID)\n SecureLogger.log(\"Removed \\(peerID) from activePeers (disconnected)\", \n category: SecureLogger.session, level: .info)\n }\n default:\n break\n }\n \n // Always notify peer list update when connection state changes\n DispatchQueue.main.async {\n self.notifyPeerListUpdate(immediate: true)\n }\n }\n }\n }\n \n // Get peer connection state\n func getPeerConnectionState(_ peerID: String) -> PeerConnectionState {\n return connectionStateQueue.sync {\n peerConnectionStates[peerID] ?? .disconnected\n }\n }\n \n // MARK: - Peer ID Rotation\n \n private func generateNewPeerID() -> String {\n // Generate 8 random bytes (64 bits) for strong collision resistance\n var randomBytes = [UInt8](repeating: 0, count: 8)\n let result = SecRandomCopyBytes(kSecRandomDefault, 8, &randomBytes)\n \n // If SecRandomCopyBytes fails, use alternative randomization\n if result != errSecSuccess {\n for i in 0..<8 {\n randomBytes[i] = UInt8.random(in: 0...255)\n }\n }\n \n // Add timestamp entropy to ensure uniqueness\n // Use lower 32 bits of timestamp in milliseconds to avoid overflow\n let timestampMs = UInt64(Date().timeIntervalSince1970 * 1000)\n let timestamp = UInt32(timestampMs & 0xFFFFFFFF)\n randomBytes[4] = UInt8((timestamp >> 24) & 0xFF)\n randomBytes[5] = UInt8((timestamp >> 16) & 0xFF)\n randomBytes[6] = UInt8((timestamp >> 8) & 0xFF)\n randomBytes[7] = UInt8(timestamp & 0xFF)\n \n return randomBytes.map { String(format: \"%02x\", $0) }.joined()\n }\n \n func rotatePeerID() {\n guard !rotationLocked else {\n // Schedule rotation for later\n scheduleRotation(delay: 30.0)\n return\n }\n \n collectionsQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n // Save current peer ID as previous\n let oldID = self.myPeerID\n self.previousPeerID = oldID\n self.rotationTimestamp = Date()\n \n // Generate new peer ID\n self.myPeerID = self.generateNewPeerID()\n \n SecureLogger.log(\"Peer ID rotated from \\(oldID) to \\(self.myPeerID)\", category: SecureLogger.security, level: .info)\n \n // Update advertising with new peer ID\n DispatchQueue.main.async { [weak self] in\n self?.updateAdvertisement()\n }\n \n // Send identity announcement with new peer ID\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n self?.sendNoiseIdentityAnnounce()\n }\n \n // Schedule next rotation\n self.scheduleNextRotation()\n }\n }\n \n private func scheduleRotation(delay: TimeInterval) {\n DispatchQueue.main.async { [weak self] in\n self?.rotationTimer?.invalidate()\n self?.rotationTimer = Timer.scheduledTimer(withTimeInterval: delay, repeats: false) { _ in\n self?.rotatePeerID()\n }\n }\n }\n \n private func scheduleNextRotation() {\n // Base interval: 1-6 hours\n let baseInterval = TimeInterval.random(in: 3600...21600)\n \n // Add jitter: ±30 minutes\n let jitter = TimeInterval.random(in: -1800...1800)\n \n // Additional random delay to prevent synchronization\n let networkDelay = TimeInterval.random(in: 0...300) // 0-5 minutes\n \n let nextRotation = baseInterval + jitter + networkDelay\n \n scheduleRotation(delay: nextRotation)\n }\n \n private func updateAdvertisement() {\n guard isAdvertising else { return }\n \n peripheralManager?.stopAdvertising()\n \n // Update advertisement data with new peer ID\n advertisementData = [\n CBAdvertisementDataServiceUUIDsKey: [BluetoothMeshService.serviceUUID],\n CBAdvertisementDataLocalNameKey: myPeerID\n ]\n \n peripheralManager?.startAdvertising(advertisementData)\n }\n \n func lockRotation() {\n rotationLocked = true\n }\n \n func unlockRotation() {\n rotationLocked = false\n }\n \n // MARK: - Initialization\n \n override init() {\n // Generate ephemeral peer ID for each session to prevent tracking\n self.myPeerID = \"\"\n super.init()\n self.myPeerID = generateNewPeerID()\n \n centralManager = CBCentralManager(delegate: self, queue: nil)\n peripheralManager = CBPeripheralManager(delegate: self, queue: nil)\n \n // Start bloom filter reset timer (reset every 5 minutes)\n bloomFilterResetTimer = Timer.scheduledTimer(withTimeInterval: 300.0, repeats: true) { [weak self] _ in\n self?.messageQueue.async(flags: .barrier) {\n guard let self = self else { return }\n \n // Adapt Bloom filter size based on network size\n let networkSize = self.estimatedNetworkSize\n self.messageBloomFilter = OptimizedBloomFilter.adaptive(for: networkSize)\n \n // Clear other duplicate detection sets\n self.processedMessagesLock.lock()\n self.processedMessages.removeAll()\n self.processedMessagesLock.unlock()\n \n }\n }\n \n // Start stale peer cleanup timer (every 30 seconds)\n cleanupTimer = Timer.scheduledTimer(withTimeInterval: 60.0, repeats: true) { [weak self] _ in\n self?.cleanupStalePeers()\n }\n \n // Start ACK timeout checking timer (every 2 seconds for timely retries)\n Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { [weak self] _ in\n self?.checkAckTimeouts()\n }\n \n // Start peer availability checking timer (every 15 seconds)\n availabilityCheckTimer = Timer.scheduledTimer(withTimeInterval: 15.0, repeats: true) { [weak self] _ in\n self?.checkPeerAvailability()\n }\n \n // Start RSSI update timer (every 10 seconds)\n Timer.scheduledTimer(withTimeInterval: 10.0, repeats: true) { [weak self] _ in\n self?.updateAllPeripheralRSSI()\n }\n \n // Start write queue cleanup timer (every 30 seconds)\n writeQueueTimer = Timer.scheduledTimer(withTimeInterval: 30.0, repeats: true) { [weak self] _ in\n self?.cleanExpiredWriteQueues()\n }\n \n // Start identity cache cleanup timer (every hour)\n Timer.scheduledTimer(withTimeInterval: 3600.0, repeats: true) { [weak self] _ in\n self?.cleanExpiredIdentityCache()\n }\n \n // Start memory cleanup timer (every minute)\n startMemoryCleanupTimer()\n \n // Start connection keep-alive timer to prevent iOS BLE timeouts\n connectionKeepAliveTimer = Timer.scheduledTimer(withTimeInterval: keepAliveInterval, repeats: true) { [weak self] _ in\n self?.sendKeepAlivePings()\n }\n \n // Log handshake states periodically for debugging and clean up stale states\n #if DEBUG\n Timer.scheduledTimer(withTimeInterval: 30.0, repeats: true) { [weak self] _ in\n guard let self = self else { return }\n \n // Clean up stale handshakes\n let stalePeerIDs = self.handshakeCoordinator.cleanupStaleHandshakes()\n if !stalePeerIDs.isEmpty {\n for peerID in stalePeerIDs {\n // Also remove from noise service\n self.cleanupPeerCryptoState(peerID)\n SecureLogger.log(\"Cleaned up stale handshake for \\(peerID)\", category: SecureLogger.handshake, level: .info)\n }\n }\n \n self.handshakeCoordinator.logHandshakeStates()\n }\n #endif\n \n // Schedule first peer ID rotation\n scheduleNextRotation()\n \n // Setup noise callbacks\n noiseService.onPeerAuthenticated = { [weak self] peerID, fingerprint in\n // Get peer's public key data from noise service\n if let publicKeyData = self?.noiseService.getPeerPublicKeyData(peerID) {\n // Register with ChatViewModel for verification tracking\n DispatchQueue.main.async {\n (self?.delegate as? ChatViewModel)?.registerPeerPublicKey(peerID: peerID, publicKeyData: publicKeyData)\n \n // Force UI to update encryption status for this specific peer\n (self?.delegate as? ChatViewModel)?.updateEncryptionStatusForPeer(peerID)\n }\n }\n \n // Send regular announce packet when authenticated to trigger connect message\n // This covers the case where we're the responder in the handshake\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in\n self?.sendAnnouncementToPeer(peerID)\n }\n }\n \n // Register for app termination notifications\n #if os(macOS)\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillTerminate),\n name: NSApplication.willTerminateNotification,\n object: nil\n )\n #else\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(appWillTerminate),\n name: UIApplication.willTerminateNotification,\n object: nil\n )\n #endif\n }\n \n // MARK: - Deinitialization and Cleanup\n \n deinit {\n cleanup()\n scanDutyCycleTimer?.invalidate()\n batteryMonitorTimer?.invalidate()\n coverTrafficTimer?.invalidate()\n bloomFilterResetTimer?.invalidate()\n aggregationTimer?.invalidate()\n cleanupTimer?.invalidate()\n rotationTimer?.invalidate()\n memoryCleanupTimer?.invalidate()\n connectionKeepAliveTimer?.invalidate()\n availabilityCheckTimer?.invalidate()\n }\n \n @objc private func appWillTerminate() {\n cleanup()\n }\n \n private func cleanup() {\n // Send leave announcement before disconnecting\n sendLeaveAnnouncement()\n \n // Give the leave message time to send\n Thread.sleep(forTimeInterval: 0.2)\n \n // First, disconnect all peripherals which will trigger disconnect delegates\n for (_, peripheral) in connectedPeripherals {\n centralManager?.cancelPeripheralConnection(peripheral)\n }\n \n // Stop advertising\n if peripheralManager?.isAdvertising == true {\n peripheralManager?.stopAdvertising()\n }\n \n // Stop scanning\n centralManager?.stopScan()\n \n // Remove all services - this will disconnect any connected centrals\n if peripheralManager?.state == .poweredOn {\n peripheralManager?.removeAllServices()\n }\n \n // Clear all tracking\n connectedPeripherals.removeAll()\n subscribedCentrals.removeAll()\n collectionsQueue.sync(flags: .barrier) {\n activePeers.removeAll()\n }\n announcedPeers.removeAll()\n // For normal disconnect, respect the timing\n networkBecameEmptyTime = Date()\n \n // Clear announcement tracking\n announcedToPeers.removeAll()\n \n // Clear last seen timestamps\n peerLastSeenTimestamps.removeAll()\n \n // Clear all encryption queues\n encryptionQueuesLock.lock()\n peerEncryptionQueues.removeAll()\n encryptionQueuesLock.unlock()\n \n // Clear peer tracking\n lastHeardFromPeer.removeAll()\n }\n \n // MARK: - Service Management\n \n /// Starts the Bluetooth mesh networking services.\n /// This initializes both central (scanning) and peripheral (advertising) modes,\n /// enabling the device to both discover peers and be discovered.\n /// Call this method after setting the delegate and localUserID.\n func startServices() {\n // Starting services\n // Start both central and peripheral services\n if centralManager?.state == .poweredOn {\n startScanning()\n }\n if peripheralManager?.state == .poweredOn {\n setupPeripheral()\n startAdvertising()\n }\n \n // Send initial announces after services are ready\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [weak self] in\n self?.sendBroadcastAnnounce()\n }\n \n // Setup battery optimizer\n setupBatteryOptimizer()\n \n // Start cover traffic for privacy (disabled by default for now)\n // TODO: Make this configurable in settings\n let coverTrafficEnabled = true\n if coverTrafficEnabled {\n SecureLogger.log(\"Cover traffic enabled\", category: SecureLogger.security, level: .info)\n startCoverTraffic()\n }\n }\n \n // MARK: - Message Sending\n \n func sendBroadcastAnnounce() {\n guard let vm = delegate as? ChatViewModel else { return }\n \n \n let announcePacket = BitchatPacket(\n type: MessageType.announce.rawValue,\n ttl: 3, // Increase TTL so announce reaches all peers\n senderID: myPeerID,\n payload: Data(vm.nickname.utf8) )\n \n \n // Single send with smart collision avoidance\n let initialDelay = self.smartCollisionAvoidanceDelay(baseDelay: self.randomDelay())\n DispatchQueue.main.asyncAfter(deadline: .now() + initialDelay) { [weak self] in\n self?.broadcastPacket(announcePacket)\n \n // Don't automatically send identity announcement on startup\n // Let it happen naturally when peers connect\n }\n }\n \n func startAdvertising() {\n guard peripheralManager?.state == .poweredOn else { \n return \n }\n \n // Use generic advertising to avoid identification\n // No identifying prefixes or app names for activist safety\n \n // Only use allowed advertisement keys\n advertisementData = [\n CBAdvertisementDataServiceUUIDsKey: [BluetoothMeshService.serviceUUID],\n // Use only peer ID without any identifying prefix\n CBAdvertisementDataLocalNameKey: myPeerID\n ]\n \n isAdvertising = true\n peripheralManager?.startAdvertising(advertisementData)\n }\n \n func startScanning() {\n guard centralManager?.state == .poweredOn else { \n return \n }\n \n // Enable duplicate detection for RSSI tracking\n let scanOptions: [String: Any] = [\n CBCentralManagerScanOptionAllowDuplicatesKey: true\n ]\n \n centralManager?.scanForPeripherals(\n withServices: [BluetoothMeshService.serviceUUID],\n options: scanOptions\n )\n \n // Update scan parameters based on battery before starting\n updateScanParametersForBattery()\n \n // Implement scan duty cycling for battery efficiency\n scheduleScanDutyCycle()\n }\n \n private func scheduleScanDutyCycle() {\n guard scanDutyCycleTimer == nil else { return }\n \n // Start with active scanning\n isActivelyScanning = true\n \n scanDutyCycleTimer = Timer.scheduledTimer(withTimeInterval: activeScanDuration, repeats: true) { [weak self] _ in\n guard let self = self else { return }\n \n if self.isActivelyScanning {\n // Pause scanning to save battery\n self.centralManager?.stopScan()\n self.isActivelyScanning = false\n \n // Schedule resume\n DispatchQueue.main.asyncAfter(deadline: .now() + self.scanPauseDuration) { [weak self] in\n guard let self = self else { return }\n if self.centralManager?.state == .poweredOn {\n self.centralManager?.scanForPeripherals(\n withServices: [BluetoothMeshService.serviceUUID],\n options: [CBCentralManagerScanOptionAllowDuplicatesKey: true]\n )\n self.isActivelyScanning = true\n }\n }\n }\n }\n }\n \n private func setupPeripheral() {\n let characteristic = CBMutableCharacteristic(\n type: BluetoothMeshService.characteristicUUID,\n properties: [.read, .write, .writeWithoutResponse, .notify],\n value: nil,\n permissions: [.readable, .writeable]\n )\n \n let service = CBMutableService(type: BluetoothMeshService.serviceUUID, primary: true)\n service.characteristics = [characteristic]\n \n peripheralManager?.add(service)\n self.characteristic = characteristic\n }\n \n /// Sends a message through the mesh network.\n /// - Parameters:\n /// - content: The message content to send\n /// - mentions: Array of user IDs being mentioned in the message\n /// - recipientID: Optional recipient ID for directed messages (nil for broadcast)\n /// - messageID: Optional custom message ID (auto-generated if nil)\n /// - timestamp: Optional custom timestamp (current time if nil)\n /// - Note: Messages are automatically routed through the mesh using TTL-based forwarding\n func sendMessage(_ content: String, mentions: [String] = [], to recipientID: String? = nil, messageID: String? = nil, timestamp: Date? = nil) {\n // Defensive check for empty content\n guard !content.isEmpty else { return }\n messageQueue.async { [weak self] in\n guard let self = self else { return }\n \n let nickname = self.delegate as? ChatViewModel\n let senderNick = nickname?.nickname ?? self.myPeerID\n \n let message = BitchatMessage(\n id: messageID,\n sender: senderNick,\n content: content,\n timestamp: timestamp ?? Date(),\n isRelay: false,\n originalSender: nil,\n isPrivate: false,\n recipientNickname: nil,\n senderPeerID: self.myPeerID,\n mentions: mentions.isEmpty ? nil : mentions\n )\n \n if let messageData = message.toBinaryPayload() {\n \n \n // Use unified message type with broadcast recipient\n let packet = BitchatPacket(\n type: MessageType.message.rawValue,\n senderID: Data(hexString: self.myPeerID) ?? Data(),\n recipientID: SpecialRecipients.broadcast, // Special broadcast ID\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000), // milliseconds\n payload: messageData,\n signature: nil,\n ttl: self.adaptiveTTL )\n \n // Track this message to prevent duplicate sends\n let msgID = \"\\(packet.timestamp)-\\(self.myPeerID)-\\(packet.payload.prefix(32).hashValue)\"\n \n let shouldSend = !self.recentlySentMessages.contains(msgID)\n if shouldSend {\n self.recentlySentMessages.insert(msgID)\n }\n \n if shouldSend {\n // Clean up old entries after 10 seconds\n self.messageQueue.asyncAfter(deadline: .now() + 10.0) { [weak self] in\n guard let self = self else { return }\n self.recentlySentMessages.remove(msgID)\n }\n \n // Single send with smart collision avoidance\n let initialDelay = self.smartCollisionAvoidanceDelay(baseDelay: self.randomDelay())\n DispatchQueue.main.asyncAfter(deadline: .now() + initialDelay) { [weak self] in\n self?.broadcastPacket(packet)\n }\n }\n }\n }\n }\n \n \n /// Sends an end-to-end encrypted private message to a specific peer.\n /// - Parameters:\n /// - content: The message content to encrypt and send\n /// - recipientPeerID: The peer ID of the recipient\n /// - recipientNickname: The nickname of the recipient (for UI display)\n /// - messageID: Optional custom message ID (auto-generated if nil)\n /// - Note: This method automatically handles Noise handshake if not already established\n func sendPrivateMessage(_ content: String, to recipientPeerID: String, recipientNickname: String, messageID: String? = nil) {\n // Defensive checks\n guard !content.isEmpty, !recipientPeerID.isEmpty, !recipientNickname.isEmpty else { \n return \n }\n \n let msgID = messageID ?? UUID().uuidString\n \n messageQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Check if this is an old peer ID that has rotated\n var targetPeerID = recipientPeerID\n \n // If we have a fingerprint for this peer ID, check if there's a newer peer ID\n if let fingerprint = self.collectionsQueue.sync(execute: { self.peerIDToFingerprint[recipientPeerID] }),\n let currentPeerID = self.collectionsQueue.sync(execute: { self.fingerprintToPeerID[fingerprint] }),\n currentPeerID != recipientPeerID {\n // Use the current peer ID instead\n targetPeerID = currentPeerID\n }\n \n // Always use Noise encryption\n self.sendPrivateMessageViaNoise(content, to: targetPeerID, recipientNickname: recipientNickname, messageID: msgID)\n }\n }\n \n func sendDeliveryAck(_ ack: DeliveryAck, to recipientID: String) {\n // Use per-peer encryption queue to prevent nonce desynchronization\n let encryptionQueue = getEncryptionQueue(for: recipientID)\n \n encryptionQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Encode the ACK\n let ackData = ack.toBinaryData()\n \n // Check if we have a Noise session with this peer\n // Use noiseService directly\n if self.noiseService.hasEstablishedSession(with: recipientID) {\n // Use Noise encryption - encrypt only the ACK payload directly\n do {\n // Create a special payload that indicates this is a delivery ACK\n // Format: [1 byte type marker] + [ACK JSON data]\n var ackPayload = Data()\n ackPayload.append(MessageType.deliveryAck.rawValue) // Type marker\n ackPayload.append(ackData) // ACK JSON\n \n // Encrypt only the payload (not a full packet)\n let encryptedPayload = try noiseService.encrypt(ackPayload, for: recipientID)\n \n // Create outer Noise packet with the encrypted payload\n let outerPacket = BitchatPacket(\n type: MessageType.noiseEncrypted.rawValue,\n senderID: Data(hexString: self.myPeerID) ?? Data(),\n recipientID: Data(hexString: recipientID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: encryptedPayload,\n signature: nil,\n ttl: 3 )\n \n // Try direct delivery first for delivery ACKs\n if !self.sendDirectToRecipient(outerPacket, recipientPeerID: recipientID) {\n // Recipient not directly connected, use selective relay\n SecureLogger.log(\"Recipient \\(recipientID) not directly connected for delivery ACK, using relay\", \n category: SecureLogger.session, level: .info)\n self.sendViaSelectiveRelay(outerPacket, recipientPeerID: recipientID)\n }\n } catch {\n SecureLogger.logError(error, context: \"Failed to encrypt delivery ACK via Noise for \\(recipientID)\", category: SecureLogger.encryption)\n }\n } else {\n // Lazy handshake: No session available, drop the ACK\n SecureLogger.log(\"No Noise session with \\(recipientID) for delivery ACK - dropping (lazy handshake mode)\", \n category: SecureLogger.noise, level: .info)\n }\n }\n }\n \n private func getEncryptionQueue(for peerID: String) -> DispatchQueue {\n encryptionQueuesLock.lock()\n defer { encryptionQueuesLock.unlock() }\n \n if let queue = peerEncryptionQueues[peerID] {\n return queue\n }\n \n let queue = DispatchQueue(label: \"bitchat.encryption.\\(peerID)\", qos: .userInitiated)\n peerEncryptionQueues[peerID] = queue\n return queue\n }\n \n private func removeEncryptionQueue(for peerID: String) {\n encryptionQueuesLock.lock()\n defer { encryptionQueuesLock.unlock() }\n \n peerEncryptionQueues.removeValue(forKey: peerID)\n }\n \n // Centralized cleanup for peer crypto state\n private func cleanupPeerCryptoState(_ peerID: String) {\n noiseService.removePeer(peerID)\n handshakeCoordinator.resetHandshakeState(for: peerID)\n removeEncryptionQueue(for: peerID)\n }\n \n func sendReadReceipt(_ receipt: ReadReceipt, to recipientID: String) {\n // Use per-peer encryption queue to prevent nonce desynchronization\n let encryptionQueue = getEncryptionQueue(for: recipientID)\n \n encryptionQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Encode the receipt\n let receiptData = receipt.toBinaryData()\n \n // Check if we have a Noise session with this peer\n // Use noiseService directly\n if self.noiseService.hasEstablishedSession(with: recipientID) {\n // Use Noise encryption - encrypt only the receipt payload directly\n do {\n // Create a special payload that indicates this is a read receipt\n // Format: [1 byte type marker] + [receipt binary data]\n var receiptPayload = Data()\n receiptPayload.append(MessageType.readReceipt.rawValue) // Type marker\n receiptPayload.append(receiptData) // Receipt binary data\n \n // Encrypt only the payload (not a full packet)\n let encryptedPayload = try noiseService.encrypt(receiptPayload, for: recipientID)\n \n // Create outer Noise packet with the encrypted payload\n let outerPacket = BitchatPacket(\n type: MessageType.noiseEncrypted.rawValue,\n senderID: Data(hexString: self.myPeerID) ?? Data(),\n recipientID: Data(hexString: recipientID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: encryptedPayload,\n signature: nil,\n ttl: 3 )\n \n SecureLogger.log(\"Sending encrypted read receipt for message \\(receipt.originalMessageID) to \\(recipientID)\", category: SecureLogger.noise, level: .info)\n \n // Try direct delivery first for read receipts\n if !self.sendDirectToRecipient(outerPacket, recipientPeerID: recipientID) {\n // Recipient not directly connected, use selective relay\n SecureLogger.log(\"Recipient \\(recipientID) not directly connected for read receipt, using relay\", \n category: SecureLogger.session, level: .info)\n self.sendViaSelectiveRelay(outerPacket, recipientPeerID: recipientID)\n }\n } catch {\n SecureLogger.logError(error, context: \"Failed to encrypt read receipt via Noise for \\(recipientID)\", category: SecureLogger.encryption)\n }\n } else {\n // Lazy handshake: No session available, drop the read receipt\n SecureLogger.log(\"No Noise session with \\(recipientID) for read receipt - dropping (lazy handshake mode)\", \n category: SecureLogger.noise, level: .info)\n }\n }\n }\n \n \n \n \n \n private func sendAnnouncementToPeer(_ peerID: String) {\n guard let vm = delegate as? ChatViewModel else { return }\n \n \n // Always send announce, don't check if already announced\n // This ensures peers get our nickname even if they reconnect\n \n let packet = BitchatPacket(\n type: MessageType.announce.rawValue,\n ttl: 3, // Allow relay for better reach\n senderID: myPeerID,\n payload: Data(vm.nickname.utf8) )\n \n if let data = packet.toBinaryData() {\n // Try both broadcast and targeted send\n broadcastPacket(packet)\n \n // Also try targeted send if we have the peripheral\n if let peripheral = connectedPeripherals[peerID],\n peripheral.state == .connected,\n let characteristic = peripheral.services?.first(where: { $0.uuid == BluetoothMeshService.serviceUUID })?.characteristics?.first(where: { $0.uuid == BluetoothMeshService.characteristicUUID }) {\n writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: peerID)\n } else {\n }\n } else {\n }\n \n announcedToPeers.insert(peerID)\n }\n \n private func sendLeaveAnnouncement() {\n guard let vm = delegate as? ChatViewModel else { return }\n \n let packet = BitchatPacket(\n type: MessageType.leave.rawValue,\n ttl: 1, // Don't relay leave messages\n senderID: myPeerID,\n payload: Data(vm.nickname.utf8) )\n \n broadcastPacket(packet)\n }\n \n // Get Noise session state for UI display\n func getNoiseSessionState(for peerID: String) -> LazyHandshakeState {\n return collectionsQueue.sync {\n // First check our tracked state\n if let state = noiseSessionStates[peerID] {\n return state\n }\n \n // If no tracked state, check if we have an established session\n if noiseService.hasEstablishedSession(with: peerID) {\n return .established\n }\n \n // Default to none\n return .none\n }\n }\n \n // Trigger handshake with a peer (for UI)\n func triggerHandshake(with peerID: String) {\n SecureLogger.log(\"UI triggered handshake with \\(peerID)\", category: SecureLogger.noise, level: .info)\n \n // Check if we already have a session\n if noiseService.hasEstablishedSession(with: peerID) {\n SecureLogger.log(\"Already have session with \\(peerID), skipping handshake\", category: SecureLogger.noise, level: .debug)\n return\n }\n \n // Update state to handshakeQueued\n collectionsQueue.sync(flags: .barrier) {\n noiseSessionStates[peerID] = .handshakeQueued\n }\n \n // Always initiate handshake when triggered by UI\n // This ensures immediate handshake when opening PM\n initiateNoiseHandshake(with: peerID)\n }\n \n func getPeerNicknames() -> [String: String] {\n return collectionsQueue.sync {\n return peerNicknames\n }\n }\n \n func getPeerRSSI() -> [String: NSNumber] {\n var rssiValues = peerRSSI\n \n \n // Log connectedPeripherals state\n SecureLogger.log(\"connectedPeripherals has \\(connectedPeripherals.count) entries:\", category: SecureLogger.session, level: .debug)\n for (peerID, peripheral) in connectedPeripherals {\n SecureLogger.log(\" connectedPeripherals[\\(peerID)] = \\(peripheral.identifier.uuidString)\", category: SecureLogger.session, level: .debug)\n }\n \n \n // Also check peripheralRSSI for any connected peripherals\n // This handles cases where RSSI is stored under temp IDs\n for (peerID, peripheral) in connectedPeripherals {\n // Skip temp IDs when iterating\n if peerID.count != 16 {\n continue\n }\n \n // If we don't have RSSI for this peer ID\n if rssiValues[peerID] == nil {\n \n // Check if we have RSSI stored by peripheral ID\n let peripheralID = peripheral.identifier.uuidString\n if let rssi = peripheralRSSI[peripheralID] {\n rssiValues[peerID] = rssi\n }\n // Also check if RSSI is stored under the peer ID as a temp ID\n else if let rssi = peripheralRSSI[peerID] {\n rssiValues[peerID] = rssi\n }\n }\n }\n \n // Also check for any known peers that might have RSSI in peerRSSI but not in connectedPeripherals\n for (peerID, _) in peerNicknames {\n if rssiValues[peerID] == nil && peerID.count == 16 {\n // Check if we have RSSI stored directly\n if let rssi = peerRSSI[peerID] {\n rssiValues[peerID] = rssi\n } else if let rssi = peripheralRSSI[peerID] {\n rssiValues[peerID] = rssi\n }\n }\n }\n \n \n return rssiValues\n }\n \n // Emergency disconnect for panic situations\n func emergencyDisconnectAll() {\n SecureLogger.log(\"Emergency disconnect triggered\", category: SecureLogger.security, level: .warning)\n \n // Stop advertising immediately\n if peripheralManager?.isAdvertising == true {\n peripheralManager?.stopAdvertising()\n }\n \n // Stop scanning\n centralManager?.stopScan()\n scanDutyCycleTimer?.invalidate()\n scanDutyCycleTimer = nil\n \n // Disconnect all peripherals\n for (peerID, peripheral) in connectedPeripherals {\n SecureLogger.log(\"Emergency disconnect peer: \\(peerID)\", category: SecureLogger.session, level: .warning)\n centralManager?.cancelPeripheralConnection(peripheral)\n }\n \n // Clear all peer data\n connectedPeripherals.removeAll()\n peripheralCharacteristics.removeAll()\n discoveredPeripherals.removeAll()\n subscribedCentrals.removeAll()\n peerNicknames.removeAll()\n activePeers.removeAll()\n peerRSSI.removeAll()\n peripheralRSSI.removeAll()\n rssiRetryCount.removeAll()\n announcedToPeers.removeAll()\n announcedPeers.removeAll()\n // For emergency/panic, reset immediately\n hasNotifiedNetworkAvailable = false\n networkBecameEmptyTime = nil\n lastNetworkNotificationTime = nil\n processedMessagesLock.lock()\n processedMessages.removeAll()\n processedMessagesLock.unlock()\n incomingFragments.removeAll()\n \n // Clear all encryption queues\n encryptionQueuesLock.lock()\n peerEncryptionQueues.removeAll()\n encryptionQueuesLock.unlock()\n fragmentMetadata.removeAll()\n \n // Cancel all pending relays\n pendingRelaysLock.lock()\n for (_, relay) in pendingRelays {\n relay.cancel()\n }\n pendingRelays.removeAll()\n pendingRelaysLock.unlock()\n \n // Clear peer tracking\n lastHeardFromPeer.removeAll()\n \n // Clear persistent identity\n noiseService.clearPersistentIdentity()\n \n // Clear all handshake coordinator states\n handshakeCoordinator.clearAllHandshakeStates()\n \n // Clear handshake attempt times\n handshakeAttemptTimes.removeAll()\n \n // Notify UI that all peers are disconnected\n DispatchQueue.main.async { [weak self] in\n self?.delegate?.didUpdatePeerList([])\n }\n }\n \n private func getAllConnectedPeerIDs() -> [String] {\n // Return all valid active peers\n let peersCopy = collectionsQueue.sync {\n return activePeers\n }\n \n \n let validPeers = peersCopy.filter { peerID in\n // Ensure peerID is valid and not self\n let isEmpty = peerID.isEmpty\n let isUnknown = peerID == \"unknown\"\n let isSelf = peerID == self.myPeerID\n \n return !isEmpty && !isUnknown && !isSelf\n }\n \n let result = Array(validPeers).sorted()\n return result\n }\n \n // Debounced peer list update notification\n private func notifyPeerListUpdate(immediate: Bool = false) {\n if immediate {\n // For initial connections, update immediately\n let connectedPeerIDs = self.getAllConnectedPeerIDs()\n \n DispatchQueue.main.async {\n self.delegate?.didUpdatePeerList(connectedPeerIDs)\n }\n } else {\n // Must schedule timer on main thread\n DispatchQueue.main.async { [weak self] in\n guard let self = self else { return }\n \n // Cancel any pending update\n self.peerListUpdateTimer?.invalidate()\n \n // Schedule a new update after debounce interval\n self.peerListUpdateTimer = Timer.scheduledTimer(withTimeInterval: self.peerListUpdateDebounceInterval, repeats: false) { [weak self] _ in\n guard let self = self else { return }\n \n let connectedPeerIDs = self.getAllConnectedPeerIDs()\n \n self.delegate?.didUpdatePeerList(connectedPeerIDs)\n }\n }\n }\n }\n \n // Clean up stale peers that haven't been seen in a while\n private func cleanupStalePeers() {\n let staleThreshold: TimeInterval = 180.0 // 3 minutes - increased for better stability\n let now = Date()\n \n // Clean up expired gracefully left peers\n let expiredGracefulPeers = gracefulLeaveTimestamps.filter { (_, timestamp) in\n now.timeIntervalSince(timestamp) > gracefulLeaveExpirationTime\n }.map { $0.key }\n \n for peerID in expiredGracefulPeers {\n gracefullyLeftPeers.remove(peerID)\n gracefulLeaveTimestamps.removeValue(forKey: peerID)\n SecureLogger.log(\"Cleaned up expired gracefullyLeft entry for \\(peerID)\", \n category: SecureLogger.session, level: .debug)\n }\n \n let peersToRemove = collectionsQueue.sync(flags: .barrier) {\n let toRemove = activePeers.filter { peerID in\n if let lastSeen = peerLastSeenTimestamps.get(peerID) {\n return now.timeIntervalSince(lastSeen) > staleThreshold\n }\n return false // Keep peers we haven't tracked yet\n }\n \n var actuallyRemoved: [String] = []\n \n for peerID in toRemove {\n // Check if this peer has an active peripheral connection\n if let peripheral = connectedPeripherals[peerID], peripheral.state == .connected {\n // Skipping removal - still has active connection\n // Update last seen time to prevent immediate re-removal\n peerLastSeenTimestamps.set(peerID, value: Date())\n continue\n }\n \n let nickname = peerNicknames[peerID] ?? \"unknown\"\n activePeers.remove(peerID)\n peerLastSeenTimestamps.remove(peerID)\n SecureLogger.log(\"📴 Removed stale peer from network: \\(peerID) (\\(nickname))\", category: SecureLogger.session, level: .info)\n \n // Clean up all associated data\n connectedPeripherals.removeValue(forKey: peerID)\n peerRSSI.removeValue(forKey: peerID)\n announcedPeers.remove(peerID)\n announcedToPeers.remove(peerID)\n peerNicknames.removeValue(forKey: peerID)\n lastHeardFromPeer.removeValue(forKey: peerID)\n \n actuallyRemoved.append(peerID)\n // Removed stale peer\n }\n return actuallyRemoved\n }\n \n if !peersToRemove.isEmpty {\n notifyPeerListUpdate()\n \n // Mark when network became empty, but don't reset flag immediately\n let currentNetworkSize = collectionsQueue.sync { activePeers.count }\n if currentNetworkSize == 0 && networkBecameEmptyTime == nil {\n networkBecameEmptyTime = Date()\n }\n }\n \n // Check if we should reset the notification flag\n if let emptyTime = networkBecameEmptyTime {\n let currentNetworkSize = collectionsQueue.sync { activePeers.count }\n if currentNetworkSize == 0 {\n // Network is still empty, check if enough time has passed\n let timeSinceEmpty = Date().timeIntervalSince(emptyTime)\n if timeSinceEmpty >= networkEmptyResetDelay {\n // Reset the flag after network has been empty for the delay period\n hasNotifiedNetworkAvailable = false\n // Keep the empty time set so we don't immediately notify again\n }\n } else {\n // Network is no longer empty, clear the empty time\n networkBecameEmptyTime = nil\n }\n }\n }\n \n // MARK: - Store-and-Forward Methods\n \n private func cacheMessage(_ packet: BitchatPacket, messageID: String) {\n messageQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n // Don't cache certain message types\n guard packet.type != MessageType.announce.rawValue,\n packet.type != MessageType.leave.rawValue,\n packet.type != MessageType.fragmentStart.rawValue,\n packet.type != MessageType.fragmentContinue.rawValue,\n packet.type != MessageType.fragmentEnd.rawValue else {\n return\n }\n \n // Don't cache broadcast messages\n if let recipientID = packet.recipientID,\n recipientID == SpecialRecipients.broadcast {\n return // Never cache broadcast messages\n }\n \n // Check if this is a private message for a favorite\n var isForFavorite = false\n if packet.type == MessageType.message.rawValue,\n let recipientID = packet.recipientID {\n let recipientPeerID = recipientID.hexEncodedString()\n // Check if recipient is a favorite via their public key fingerprint\n if let fingerprint = self.noiseService.getPeerFingerprint(recipientPeerID) {\n isForFavorite = self.delegate?.isFavorite(fingerprint: fingerprint) ?? false\n }\n }\n \n // Create stored message with original packet timestamp preserved\n let storedMessage = StoredMessage(\n packet: packet,\n timestamp: Date(timeIntervalSince1970: TimeInterval(packet.timestamp) / 1000.0), // convert from milliseconds\n messageID: messageID,\n isForFavorite: isForFavorite\n )\n \n \n if isForFavorite {\n if let recipientID = packet.recipientID {\n let recipientPeerID = recipientID.hexEncodedString()\n if self.favoriteMessageQueue[recipientPeerID] == nil {\n self.favoriteMessageQueue[recipientPeerID] = []\n }\n self.favoriteMessageQueue[recipientPeerID]?.append(storedMessage)\n \n // Limit favorite queue size\n if let count = self.favoriteMessageQueue[recipientPeerID]?.count,\n count > self.maxCachedMessagesForFavorites {\n self.favoriteMessageQueue[recipientPeerID]?.removeFirst()\n }\n \n }\n } else {\n // Clean up old messages first (only for regular cache)\n self.cleanupMessageCache()\n \n // Add to regular cache\n self.messageCache.append(storedMessage)\n \n // Limit cache size\n if self.messageCache.count > self.maxCachedMessages {\n self.messageCache.removeFirst()\n }\n \n }\n }\n }\n \n private func cleanupMessageCache() {\n let cutoffTime = Date().addingTimeInterval(-messageCacheTimeout)\n // Only remove non-favorite messages that are older than timeout\n messageCache.removeAll { !$0.isForFavorite && $0.timestamp < cutoffTime }\n \n // Clean up delivered messages set periodically (keep recent 1000 entries)\n if deliveredMessages.count > 1000 {\n // Clear older entries while keeping recent ones\n deliveredMessages.removeAll()\n }\n }\n \n private func sendCachedMessages(to peerID: String) {\n messageQueue.async { [weak self] in\n guard let self = self,\n let peripheral = self.connectedPeripherals[peerID],\n let characteristic = self.peripheralCharacteristics[peripheral] else {\n return\n }\n \n \n // Check if we've already sent cached messages to this peer in this session\n if self.cachedMessagesSentToPeer.contains(peerID) {\n return // Already sent cached messages to this peer in this session\n }\n \n // Mark that we're sending cached messages to this peer\n self.cachedMessagesSentToPeer.insert(peerID)\n \n // Clean up old messages first\n self.cleanupMessageCache()\n \n var messagesToSend: [StoredMessage] = []\n \n // First, check if this peer has any favorite messages waiting\n if let favoriteMessages = self.favoriteMessageQueue[peerID] {\n // Filter out already delivered messages\n let undeliveredFavoriteMessages = favoriteMessages.filter { !self.deliveredMessages.contains($0.messageID) }\n messagesToSend.append(contentsOf: undeliveredFavoriteMessages)\n // Clear the favorite queue after adding to send list\n self.favoriteMessageQueue[peerID] = nil\n }\n \n // Filter regular cached messages for this specific recipient\n let recipientMessages = self.messageCache.filter { storedMessage in\n if self.deliveredMessages.contains(storedMessage.messageID) {\n return false\n }\n if let recipientID = storedMessage.packet.recipientID {\n let recipientPeerID = recipientID.hexEncodedString()\n return recipientPeerID == peerID\n }\n return false // Don't forward broadcast messages\n }\n messagesToSend.append(contentsOf: recipientMessages)\n \n \n // Sort messages by timestamp to ensure proper ordering\n messagesToSend.sort { $0.timestamp < $1.timestamp }\n \n if !messagesToSend.isEmpty {\n }\n \n // Mark messages as delivered immediately to prevent duplicates\n let messageIDsToRemove = messagesToSend.map { $0.messageID }\n for messageID in messageIDsToRemove {\n self.deliveredMessages.insert(messageID)\n }\n \n // Send cached messages with slight delay between each\n for (index, storedMessage) in messagesToSend.enumerated() {\n let delay = Double(index) * 0.02 // 20ms between messages for faster sync\n \n DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self, weak peripheral] in\n guard let peripheral = peripheral,\n peripheral.state == .connected else {\n return\n }\n \n // Send the original packet with preserved timestamp\n let packetToSend = storedMessage.packet\n \n if let data = packetToSend.toBinaryData(),\n characteristic.properties.contains(.writeWithoutResponse) {\n self?.writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: peerID)\n }\n }\n }\n \n // Remove sent messages immediately\n if !messageIDsToRemove.isEmpty {\n self.messageQueue.async(flags: .barrier) {\n // Remove only the messages we sent to this specific peer\n self.messageCache.removeAll { message in\n messageIDsToRemove.contains(message.messageID)\n }\n \n // Also remove from favorite queue if any\n if var favoriteQueue = self.favoriteMessageQueue[peerID] {\n favoriteQueue.removeAll { message in\n messageIDsToRemove.contains(message.messageID)\n }\n self.favoriteMessageQueue[peerID] = favoriteQueue.isEmpty ? nil : favoriteQueue\n }\n }\n }\n }\n }\n \n private func estimateDistance(rssi: Int) -> Int {\n // Rough distance estimation based on RSSI\n // Using path loss formula: RSSI = TxPower - 10 * n * log10(distance)\n // Assuming TxPower = -59 dBm at 1m, n = 2.0 (free space)\n let txPower = -59.0\n let pathLossExponent = 2.0\n \n let ratio = (txPower - Double(rssi)) / (10.0 * pathLossExponent)\n let distance = pow(10.0, ratio)\n \n return Int(distance)\n }\n \n private func broadcastPacket(_ packet: BitchatPacket) {\n // CRITICAL CHECK: Never send unencrypted JSON\n if packet.type == MessageType.deliveryAck.rawValue {\n // Check if payload looks like JSON\n if let jsonCheck = String(data: packet.payload.prefix(1), encoding: .utf8), jsonCheck == \"{\" {\n // Block unencrypted JSON in delivery ACKs\n return\n }\n }\n \n \n guard let data = packet.toBinaryData() else { \n // Failed to convert packet - add to retry queue if it's our message\n let senderID = packet.senderID.hexEncodedString()\n if senderID == self.myPeerID,\n packet.type == MessageType.message.rawValue,\n let message = BitchatMessage.fromBinaryPayload(packet.payload) {\n MessageRetryService.shared.addMessageForRetry(\n content: message.content,\n mentions: message.mentions,\n isPrivate: message.isPrivate,\n recipientPeerID: nil,\n recipientNickname: message.recipientNickname,\n originalMessageID: message.id,\n originalTimestamp: message.timestamp\n )\n }\n return \n }\n \n // Check if fragmentation is needed for large packets\n if data.count > 512 && packet.type != MessageType.fragmentStart.rawValue && \n packet.type != MessageType.fragmentContinue.rawValue && \n packet.type != MessageType.fragmentEnd.rawValue {\n sendFragmentedPacket(packet)\n return\n }\n \n // Track which peers we've sent to (to avoid duplicates)\n var sentToPeers = Set()\n \n // Send to connected peripherals (as central)\n var sentToPeripherals = 0\n \n // Log if this is a private message being broadcast\n if packet.type == MessageType.noiseEncrypted.rawValue,\n let recipientID = packet.recipientID?.hexEncodedString(),\n !recipientID.isEmpty {\n SecureLogger.log(\"WARNING: Broadcasting private message intended for \\(recipientID) to all peers\", \n category: SecureLogger.session, level: .warning)\n }\n \n // Broadcasting to connected peripherals\n for (peerID, peripheral) in connectedPeripherals {\n if let characteristic = peripheralCharacteristics[peripheral] {\n // Check if peripheral is connected before writing\n if peripheral.state == .connected {\n // Additional safety check for characteristic properties\n if characteristic.properties.contains(.write) || \n characteristic.properties.contains(.writeWithoutResponse) {\n // Writing packet to peripheral\n writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: peerID)\n sentToPeripherals += 1\n sentToPeers.insert(peerID)\n }\n } else {\n if let peerID = connectedPeripherals.first(where: { $0.value == peripheral })?.key {\n connectedPeripherals.removeValue(forKey: peerID)\n peripheralCharacteristics.removeValue(forKey: peripheral)\n }\n }\n }\n }\n \n // Send to subscribed centrals (as peripheral) - but only if we didn't already send via peripheral connections\n var sentToCentrals = 0\n if let char = characteristic, !subscribedCentrals.isEmpty && sentToPeripherals == 0 {\n // Only send to centrals if we haven't sent via peripheral connections\n // This prevents duplicate sends in 2-peer networks where peers connect both ways\n // Broadcasting to subscribed centrals\n let success = peripheralManager?.updateValue(data, for: char, onSubscribedCentrals: nil) ?? false\n if success {\n sentToCentrals = subscribedCentrals.count\n }\n } else if sentToPeripherals > 0 && !subscribedCentrals.isEmpty {\n // Skip central broadcast - already sent via peripherals\n }\n \n // If no peers received the message, add to retry queue ONLY if it's our own message\n if sentToPeripherals == 0 && sentToCentrals == 0 {\n // Check if this packet originated from us\n let senderID = packet.senderID.hexEncodedString()\n if senderID == self.myPeerID {\n // This is our own message that failed to send\n if packet.type == MessageType.message.rawValue,\n let message = BitchatMessage.fromBinaryPayload(packet.payload) {\n MessageRetryService.shared.addMessageForRetry(\n content: message.content,\n mentions: message.mentions,\n isPrivate: message.isPrivate,\n recipientPeerID: nil,\n recipientNickname: message.recipientNickname,\n originalMessageID: message.id,\n originalTimestamp: message.timestamp\n )\n }\n }\n }\n }\n \n private func handleReceivedPacket(_ packet: BitchatPacket, from peerID: String, peripheral: CBPeripheral? = nil) {\n messageQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n // Track that we heard from this peer\n let senderID = packet.senderID.hexEncodedString()\n if !senderID.isEmpty && senderID != self.myPeerID {\n // Update peer availability\n self.updatePeerAvailability(senderID)\n \n // IMPORTANT: Update peripheral mapping for ALL message types including handshakes\n // This ensures disconnect messages work even if peer disconnects right after handshake\n if let peripheral = peripheral {\n let peripheralID = peripheral.identifier.uuidString\n \n // Check if we need to update the mapping\n if peerIDByPeripheralID[peripheralID] != senderID {\n SecureLogger.log(\"Updating peripheral mapping: \\(peripheralID) -> \\(senderID)\", \n category: SecureLogger.session, level: .debug)\n peerIDByPeripheralID[peripheralID] = senderID\n \n // Also ensure connectedPeripherals has the correct mapping\n // Remove any temp ID mapping if it exists\n let tempIDToRemove = connectedPeripherals.first(where: { $0.value == peripheral && $0.key != senderID })?.key\n if let tempID = tempIDToRemove {\n connectedPeripherals.removeValue(forKey: tempID)\n }\n connectedPeripherals[senderID] = peripheral\n }\n }\n \n // Check if this is a reconnection after a long silence\n let wasReconnection: Bool\n if let lastHeard = self.lastHeardFromPeer[senderID] {\n let timeSinceLastHeard = Date().timeIntervalSince(lastHeard)\n wasReconnection = timeSinceLastHeard > 30.0\n } else {\n // First time hearing from this peer\n wasReconnection = true\n }\n \n self.lastHeardFromPeer[senderID] = Date()\n \n // If this is a reconnection, send our identity announcement\n if wasReconnection && packet.type != MessageType.noiseIdentityAnnounce.rawValue {\n SecureLogger.log(\"Detected reconnection from \\(senderID) after silence, sending identity announcement\", category: SecureLogger.noise, level: .info)\n DispatchQueue.main.async { [weak self] in\n self?.sendNoiseIdentityAnnounce(to: senderID)\n }\n }\n }\n \n \n // Log specific Noise packet types\n \n guard packet.ttl > 0 else { \n return \n }\n \n // Validate packet has payload\n guard !packet.payload.isEmpty else {\n return\n }\n \n // Update last seen timestamp for this peer\n if senderID != \"unknown\" && senderID != self.myPeerID {\n peerLastSeenTimestamps.set(senderID, value: Date())\n }\n \n // Replay attack protection: Check timestamp is within reasonable window (5 minutes)\n let currentTime = UInt64(Date().timeIntervalSince1970 * 1000) // milliseconds\n let timeDiff = abs(Int64(currentTime) - Int64(packet.timestamp))\n if timeDiff > 300000 { // 5 minutes in milliseconds\n SecureLogger.log(\"Replay attack detected - timestamp from \\(senderID)\", category: SecureLogger.security, level: .warning)\n SecureLogger.log(\"Dropped message with stale timestamp. Age: \\(timeDiff/1000)s from \\(senderID)\", category: SecureLogger.security, level: .warning)\n return\n }\n \n // Log message type for debugging\n let messageTypeName: String\n switch MessageType(rawValue: packet.type) {\n case .message:\n messageTypeName = \"MESSAGE\"\n case .protocolAck:\n messageTypeName = \"PROTOCOL_ACK\"\n case .protocolNack:\n messageTypeName = \"PROTOCOL_NACK\"\n case .noiseHandshakeInit:\n messageTypeName = \"NOISE_HANDSHAKE_INIT\"\n case .noiseHandshakeResp:\n messageTypeName = \"NOISE_HANDSHAKE_RESP\"\n case .noiseIdentityAnnounce:\n messageTypeName = \"NOISE_IDENTITY_ANNOUNCE\"\n case .noiseEncrypted:\n messageTypeName = \"NOISE_ENCRYPTED\"\n case .leave:\n messageTypeName = \"LEAVE\"\n case .readReceipt:\n messageTypeName = \"READ_RECEIPT\"\n case .versionHello:\n messageTypeName = \"VERSION_HELLO\"\n case .versionAck:\n messageTypeName = \"VERSION_ACK\"\n case .systemValidation:\n messageTypeName = \"SYSTEM_VALIDATION\"\n case .handshakeRequest:\n messageTypeName = \"HANDSHAKE_REQUEST\"\n default:\n messageTypeName = \"UNKNOWN(\\(packet.type))\"\n }\n \n // Processing packet\n \n // Rate limiting check with message type awareness\n let isHighPriority = [MessageType.protocolAck.rawValue,\n MessageType.protocolNack.rawValue,\n MessageType.noiseHandshakeInit.rawValue,\n MessageType.noiseHandshakeResp.rawValue,\n MessageType.noiseIdentityAnnounce.rawValue,\n MessageType.leave.rawValue].contains(packet.type)\n \n \n if senderID != self.myPeerID && isRateLimited(peerID: senderID, messageType: packet.type) {\n if !isHighPriority {\n SecureLogger.log(\"RATE_LIMITED: Dropped \\(messageTypeName) from \\(senderID)\", \n category: SecureLogger.security, level: .warning)\n return\n } else {\n SecureLogger.log(\"RATE_LIMITED: Allowing high-priority \\(messageTypeName) from \\(senderID)\", \n category: SecureLogger.security, level: .info)\n }\n }\n \n // Record message for rate limiting based on type\n if senderID != self.myPeerID && !isHighPriority {\n recordMessage(from: senderID, messageType: packet.type)\n }\n \n // Content-based duplicate detection using packet ID\n let messageID = generatePacketID(for: packet)\n \n // Check if we've seen this exact message before\n processedMessagesLock.lock()\n if let existingState = processedMessages[messageID] {\n // Update the state\n var updatedState = existingState\n updatedState.updateSeen()\n processedMessages[messageID] = updatedState\n processedMessagesLock.unlock()\n \n SecureLogger.log(\"Dropped duplicate message from \\(senderID) (seen \\(updatedState.seenCount) times)\", category: SecureLogger.security, level: .debug)\n // Cancel any pending relay for this message\n cancelPendingRelay(messageID: messageID)\n return\n }\n processedMessagesLock.unlock()\n \n // Use bloom filter for efficient duplicate detection\n if messageBloomFilter.contains(messageID) {\n // Double check with exact set (bloom filter can have false positives)\n processedMessagesLock.lock()\n let isProcessed = processedMessages[messageID] != nil\n processedMessagesLock.unlock()\n if !isProcessed {\n SecureLogger.log(\"Bloom filter false positive for message: \\(messageID)\", category: SecureLogger.security, level: .debug)\n }\n }\n \n // Record this message as processed\n messageBloomFilter.insert(messageID)\n processedMessagesLock.lock()\n processedMessages[messageID] = MessageState(\n firstSeen: Date(),\n lastSeen: Date(),\n seenCount: 1,\n relayed: false,\n acknowledged: false\n )\n \n // Prune old entries if needed\n if processedMessages.count > maxProcessedMessages {\n // Remove oldest entries\n let sortedByFirstSeen = processedMessages.sorted { $0.value.firstSeen < $1.value.firstSeen }\n let toRemove = sortedByFirstSeen.prefix(processedMessages.count - maxProcessedMessages + 1000)\n for (key, _) in toRemove {\n processedMessages.removeValue(forKey: key)\n }\n }\n processedMessagesLock.unlock()\n \n \n // Log statistics periodically\n if messageBloomFilter.insertCount % 100 == 0 {\n _ = messageBloomFilter.estimatedFalsePositiveRate\n }\n \n // Bloom filter will be reset by timer, processedMessages is now bounded\n \n // let _ = packet.senderID.hexEncodedString()\n \n \n // Note: We'll decode messages in the switch statement below, not here\n \n switch MessageType(rawValue: packet.type) {\n case .message:\n // Unified message handler for both broadcast and private messages\n // Convert binary senderID back to hex string\n let senderID = packet.senderID.hexEncodedString()\n if senderID.isEmpty {\n return\n }\n \n \n // Ignore our own messages\n if senderID == myPeerID {\n return\n }\n \n // Check if this is a broadcast or private message\n if let recipientID = packet.recipientID {\n if recipientID == SpecialRecipients.broadcast {\n // BROADCAST MESSAGE\n \n // No signature verification - broadcasts are not authenticated\n \n // Parse broadcast message (not encrypted)\n if let message = BitchatMessage.fromBinaryPayload(packet.payload) {\n \n // Store nickname mapping\n collectionsQueue.sync(flags: .barrier) {\n self.peerNicknames[senderID] = message.sender\n }\n \n let finalContent = message.content\n \n let messageWithPeerID = BitchatMessage(\n id: message.id, // Preserve the original message ID\n sender: message.sender,\n content: finalContent,\n timestamp: message.timestamp,\n isRelay: message.isRelay,\n originalSender: message.originalSender,\n isPrivate: false,\n recipientNickname: nil,\n senderPeerID: senderID,\n mentions: message.mentions\n )\n \n // Track last message time from this peer\n let peerID = packet.senderID.hexEncodedString()\n self.lastMessageFromPeer.set(peerID, value: Date())\n \n DispatchQueue.main.async {\n self.delegate?.didReceiveMessage(messageWithPeerID)\n }\n \n }\n \n // Relay broadcast messages\n var relayPacket = packet\n relayPacket.ttl -= 1\n if relayPacket.ttl > 0 {\n // RSSI-based relay probability\n let rssiValue = peerRSSI[senderID]?.intValue ?? -70\n let relayProb = self.calculateRelayProbability(baseProb: self.adaptiveRelayProbability, rssi: rssiValue)\n \n // Relay based on probability only - no TTL boost if base probability is 0\n let effectiveProb = relayProb > 0 ? relayProb : 0.0\n let shouldRelay = effectiveProb > 0 && Double.random(in: 0...1) < effectiveProb\n \n if shouldRelay {\n // Relaying broadcast\n // High priority messages relay immediately, others use exponential delay\n if self.isHighPriorityMessage(type: relayPacket.type) {\n self.broadcastPacket(relayPacket)\n } else {\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n } else {\n // Dropped broadcast relay\n }\n }\n \n } else if isPeerIDOurs(recipientID.hexEncodedString()) {\n // PRIVATE MESSAGE FOR US\n \n \n // No signature verification - broadcasts are not authenticated\n \n // Private messages should only come through Noise now\n // If we're getting a private message here, it must already be decrypted from Noise\n let decryptedPayload = packet.payload\n \n // Parse the message\n if let message = BitchatMessage.fromBinaryPayload(decryptedPayload) {\n \n // Check if this is a dummy message for cover traffic\n if message.content.hasPrefix(self.coverTrafficPrefix) {\n return // Silently discard dummy messages\n }\n \n // Check if we've seen this exact message recently (within 5 seconds)\n let messageKey = \"\\(senderID)-\\(message.content)-\\(message.timestamp)\"\n if let lastReceived = self.receivedMessageTimestamps.get(messageKey) {\n let timeSinceLastReceived = Date().timeIntervalSince(lastReceived)\n if timeSinceLastReceived < 5.0 {\n }\n }\n self.receivedMessageTimestamps.set(messageKey, value: Date())\n \n // LRU cache handles cleanup automatically\n \n collectionsQueue.sync(flags: .barrier) {\n if self.peerNicknames[senderID] == nil {\n self.peerNicknames[senderID] = message.sender\n }\n }\n \n let messageWithPeerID = BitchatMessage(\n id: message.id, // Preserve the original message ID\n sender: message.sender,\n content: message.content,\n timestamp: message.timestamp,\n isRelay: message.isRelay,\n originalSender: message.originalSender,\n isPrivate: message.isPrivate,\n recipientNickname: message.recipientNickname,\n senderPeerID: senderID,\n mentions: message.mentions,\n deliveryStatus: nil // Will be set to .delivered in ChatViewModel\n )\n \n // Track last message time from this peer\n let peerID = packet.senderID.hexEncodedString()\n self.lastMessageFromPeer.set(peerID, value: Date())\n \n DispatchQueue.main.async {\n self.delegate?.didReceiveMessage(messageWithPeerID)\n }\n \n // Generate and send ACK for private messages\n let viewModel = self.delegate as? ChatViewModel\n let myNickname = viewModel?.nickname ?? self.myPeerID\n if let ack = DeliveryTracker.shared.generateAck(\n for: messageWithPeerID,\n myPeerID: self.myPeerID,\n myNickname: myNickname,\n hopCount: UInt8(self.maxTTL - packet.ttl)\n ) {\n self.sendDeliveryAck(ack, to: senderID)\n }\n } else {\n SecureLogger.log(\"Failed to parse private message from binary, size: \\(decryptedPayload.count)\", category: SecureLogger.encryption, level: .error)\n }\n \n } else if packet.ttl > 0 {\n // RELAY PRIVATE MESSAGE (not for us)\n var relayPacket = packet\n relayPacket.ttl -= 1\n \n // Check if this message is for an offline favorite and cache it\n let recipientIDString = recipientID.hexEncodedString()\n if let fingerprint = self.noiseService.getPeerFingerprint(recipientIDString) {\n // Only cache if recipient is a favorite AND is currently offline\n if (self.delegate?.isFavorite(fingerprint: fingerprint) ?? false) && !self.activePeers.contains(recipientIDString) {\n self.cacheMessage(relayPacket, messageID: messageID)\n }\n }\n \n // Private messages are important - use RSSI-based relay with boost\n let rssiValue = peerRSSI[senderID]?.intValue ?? -70\n let baseProb = min(self.adaptiveRelayProbability + 0.15, 1.0) // Boost by 15%\n let relayProb = self.calculateRelayProbability(baseProb: baseProb, rssi: rssiValue)\n \n // Relay based on probability only - no forced relay for small networks\n let shouldRelay = Double.random(in: 0...1) < relayProb\n \n if shouldRelay {\n // High priority messages relay immediately, others use exponential delay\n if self.isHighPriorityMessage(type: relayPacket.type) {\n self.broadcastPacket(relayPacket)\n } else {\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n }\n } else {\n // Message has recipient ID but not for us and TTL is 0\n // Message not for us - will be relayed if TTL > 0\n }\n } else {\n // No recipient ID - this shouldn't happen for messages\n SecureLogger.log(\"Message packet with no recipient ID from \\(senderID)\", category: SecureLogger.security, level: .warning)\n }\n \n // Note: 0x02 was legacy keyExchange - removed\n \n case .announce:\n if let rawNickname = String(data: packet.payload, encoding: .utf8) {\n // Trim whitespace from received nickname\n let nickname = rawNickname.trimmingCharacters(in: .whitespacesAndNewlines)\n let senderID = packet.senderID.hexEncodedString()\n \n SecureLogger.log(\"handleReceivedPacket: Received announce from \\(senderID), peripheral is \\(peripheral != nil ? \"present\" : \"nil\")\", category: SecureLogger.session, level: .debug)\n \n // Ignore if it's from ourselves (including previous peer IDs)\n if isPeerIDOurs(senderID) {\n return\n }\n \n // Check if we've already announced this peer\n let isFirstAnnounce = !announcedPeers.contains(senderID)\n \n // Clean up stale peer IDs with the same nickname\n collectionsQueue.sync(flags: .barrier) {\n var stalePeerIDs: [String] = []\n for (existingPeerID, existingNickname) in self.peerNicknames {\n if existingNickname == nickname && existingPeerID != senderID {\n // Check if this peer was seen very recently (within 10 seconds)\n let wasRecentlySeen = self.peerLastSeenTimestamps.get(existingPeerID).map { Date().timeIntervalSince($0) < 10.0 } ?? false\n if !wasRecentlySeen {\n // Found a stale peer ID with the same nickname\n stalePeerIDs.append(existingPeerID)\n // Found stale peer ID\n } else {\n // Peer was seen recently, keeping both\n }\n }\n }\n \n // Remove stale peer IDs\n for stalePeerID in stalePeerIDs {\n // Removing stale peer\n self.peerNicknames.removeValue(forKey: stalePeerID)\n \n // Also remove from active peers\n self.activePeers.remove(stalePeerID)\n \n // Remove from announced peers\n self.announcedPeers.remove(stalePeerID)\n self.announcedToPeers.remove(stalePeerID)\n \n // Clear tracking data\n self.lastHeardFromPeer.removeValue(forKey: stalePeerID)\n \n // Disconnect any peripherals associated with stale ID\n if let peripheral = self.connectedPeripherals[stalePeerID] {\n self.intentionalDisconnects.insert(peripheral.identifier.uuidString)\n self.centralManager?.cancelPeripheralConnection(peripheral)\n self.connectedPeripherals.removeValue(forKey: stalePeerID)\n self.peripheralCharacteristics.removeValue(forKey: peripheral)\n }\n \n // Remove RSSI data\n self.peerRSSI.removeValue(forKey: stalePeerID)\n \n // Clear cached messages tracking\n self.cachedMessagesSentToPeer.remove(stalePeerID)\n \n // Remove from last seen timestamps\n self.peerLastSeenTimestamps.remove(stalePeerID)\n \n // No longer tracking key exchanges\n }\n \n // If we had stale peers, notify the UI immediately\n if !stalePeerIDs.isEmpty {\n DispatchQueue.main.async { [weak self] in\n self?.notifyPeerListUpdate(immediate: true)\n }\n }\n \n // Now add the new peer ID with the nickname\n self.peerNicknames[senderID] = nickname\n }\n \n // Update peripheral mapping if we have it\n // If peripheral is nil (e.g., from relay), try to find it\n var peripheralToUpdate = peripheral\n if peripheralToUpdate == nil {\n // Look for any peripheral that might be this peer\n // First check if we already have a mapping for this peer ID\n peripheralToUpdate = self.connectedPeripherals[senderID]\n \n if peripheralToUpdate == nil {\n SecureLogger.log(\"handleReceivedPacket: No peripheral passed and no existing mapping for \\(senderID)\", category: SecureLogger.session, level: .debug)\n \n // Try to find an unidentified peripheral that might be this peer\n // This handles case where announce is relayed and we need to update RSSI mapping\n var unmappedPeripherals: [(String, CBPeripheral)] = []\n for (tempID, peripheral) in self.connectedPeripherals {\n // Check if this is a temp ID (UUID format, not a peer ID)\n if tempID.count == 36 && tempID.contains(\"-\") { // UUID length with dashes\n unmappedPeripherals.append((tempID, peripheral))\n SecureLogger.log(\"handleReceivedPacket: Found unmapped peripheral with temp ID \\(tempID)\", category: SecureLogger.session, level: .debug)\n }\n }\n \n // If we have exactly one unmapped peripheral, it's likely this one\n if unmappedPeripherals.count == 1 {\n let (tempID, peripheral) = unmappedPeripherals[0]\n SecureLogger.log(\"handleReceivedPacket: Single unmapped peripheral \\(tempID), mapping to \\(senderID)\", category: SecureLogger.session, level: .info)\n peripheralToUpdate = peripheral\n \n // Remove temp mapping and add real mapping\n self.connectedPeripherals.removeValue(forKey: tempID)\n self.connectedPeripherals[senderID] = peripheral\n \n // Transfer RSSI if available\n if let rssi = self.peripheralRSSI[tempID] {\n self.peripheralRSSI.removeValue(forKey: tempID)\n self.peripheralRSSI[senderID] = rssi\n self.peerRSSI[senderID] = rssi\n }\n \n // Also check the peripheral's UUID-based RSSI\n let peripheralUUID = peripheral.identifier.uuidString\n if peripheralUUID == tempID && peripheralRSSI[peripheralUUID] != nil {\n // Already handled above\n } else if let rssi = self.peripheralRSSI[peripheralUUID] {\n self.peerRSSI[senderID] = rssi\n }\n } else if unmappedPeripherals.count > 1 {\n SecureLogger.log(\"handleReceivedPacket: Multiple unmapped peripherals (\\(unmappedPeripherals.count)), cannot determine which is \\(senderID)\", category: SecureLogger.session, level: .debug)\n // TODO: Could use timing heuristics or other methods to match\n }\n }\n }\n \n if let peripheral = peripheralToUpdate {\n let peripheralID = peripheral.identifier.uuidString\n SecureLogger.log(\"Updating peripheral \\(peripheralID) mapping to peer ID \\(senderID)\", \n category: SecureLogger.session, level: .info)\n \n // Update simplified mapping\n updatePeripheralMapping(peripheralID: peripheralID, peerID: senderID)\n \n // Find and remove any temp ID mapping for this peripheral\n var tempIDToRemove: String? = nil\n for (id, per) in self.connectedPeripherals {\n if per == peripheral && id != senderID && id == peripheralID {\n tempIDToRemove = id\n break\n }\n }\n \n if let tempID = tempIDToRemove {\n // RSSI transfer is handled by updatePeripheralMapping\n self.peripheralRSSI.removeValue(forKey: tempID)\n \n // IMPORTANT: Remove old peer ID from activePeers to prevent duplicates\n collectionsQueue.sync(flags: .barrier) {\n if self.activePeers.contains(tempID) {\n _ = self.activePeers.remove(tempID)\n }\n }\n \n // Don't notify about disconnect - this is just cleanup of temporary ID\n } else {\n SecureLogger.log(\"handleReceivedPacket: No temp ID found for peripheral, directly mapping \\(senderID)\", category: SecureLogger.session, level: .debug)\n // No temp ID found, just add the mapping\n self.connectedPeripherals[senderID] = peripheral\n self.peerIDByPeripheralID[peripheral.identifier.uuidString] = senderID\n \n // Check if RSSI is stored under peripheral UUID and transfer it\n let peripheralUUID = peripheral.identifier.uuidString\n if let peripheralStoredRSSI = self.peripheralRSSI[peripheralUUID] {\n self.peerRSSI[senderID] = peripheralStoredRSSI\n }\n }\n }\n \n // Add to active peers if not already there\n if senderID != \"unknown\" && senderID != self.myPeerID {\n // Check for duplicate nicknames and remove old peer IDs\n collectionsQueue.sync(flags: .barrier) {\n // Find any existing peers with the same nickname\n var oldPeerIDsToRemove: [String] = []\n for existingPeerID in self.activePeers {\n if existingPeerID != senderID {\n let existingNickname = self.peerNicknames[existingPeerID] ?? \"\"\n if existingNickname == nickname && !existingNickname.isEmpty && existingNickname != \"unknown\" {\n oldPeerIDsToRemove.append(existingPeerID)\n }\n }\n }\n \n // Remove old peer IDs with same nickname\n for oldPeerID in oldPeerIDsToRemove {\n self.activePeers.remove(oldPeerID)\n self.peerNicknames.removeValue(forKey: oldPeerID)\n self.connectedPeripherals.removeValue(forKey: oldPeerID)\n \n // Don't notify about disconnect - this is just cleanup of duplicate\n }\n }\n \n let wasInserted = collectionsQueue.sync(flags: .barrier) {\n // Final safety check\n if senderID == self.myPeerID {\n SecureLogger.log(\"Blocked self from being added to activePeers\", category: SecureLogger.noise, level: .error)\n return false\n }\n let result = self.activePeers.insert(senderID).inserted\n return result\n }\n if wasInserted {\n SecureLogger.log(\"📡 Peer joined network: \\(senderID) (\\(nickname))\", category: SecureLogger.session, level: .info)\n }\n \n // Show join message only for first announce AND if we actually added the peer\n if isFirstAnnounce && wasInserted {\n announcedPeers.insert(senderID)\n \n // Delay the connect message slightly to allow identity announcement to be processed\n // This helps ensure fingerprint mappings are available for nickname resolution\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {\n self.delegate?.didConnectToPeer(senderID)\n }\n self.notifyPeerListUpdate(immediate: true)\n \n // Send network available notification if appropriate\n let currentNetworkSize = collectionsQueue.sync { self.activePeers.count }\n if currentNetworkSize > 0 {\n // Clear empty time since network is active\n networkBecameEmptyTime = nil\n \n if !hasNotifiedNetworkAvailable {\n // Check if enough time has passed since last notification\n let now = Date()\n var shouldSendNotification = true\n \n if let lastNotification = lastNetworkNotificationTime {\n let timeSinceLastNotification = now.timeIntervalSince(lastNotification)\n if timeSinceLastNotification < networkNotificationCooldown {\n // Too soon to send another notification\n shouldSendNotification = false\n }\n }\n \n if shouldSendNotification {\n hasNotifiedNetworkAvailable = true\n lastNetworkNotificationTime = now\n NotificationService.shared.sendNetworkAvailableNotification(peerCount: currentNetworkSize)\n }\n }\n }\n \n DispatchQueue.main.async {\n // Check if this is a favorite peer and send notification\n // Note: This might not work immediately if key exchange hasn't happened yet\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n guard let self = self else { return }\n \n // Check if this is a favorite using their public key fingerprint\n if let fingerprint = self.noiseService.getPeerFingerprint(senderID) {\n if self.delegate?.isFavorite(fingerprint: fingerprint) ?? false {\n NotificationService.shared.sendFavoriteOnlineNotification(nickname: nickname)\n \n // Send any cached messages for this favorite\n self.sendCachedMessages(to: senderID)\n }\n }\n }\n }\n } else {\n // Just update the peer list\n self.notifyPeerListUpdate()\n }\n }\n \n // Relay announce if TTL > 0\n if packet.ttl > 1 {\n var relayPacket = packet\n relayPacket.ttl -= 1\n \n // Add small delay to prevent collision\n let delay = Double.random(in: 0.1...0.3)\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n }\n \n case .leave:\n let senderID = packet.senderID.hexEncodedString()\n // Legacy peer disconnect (keeping for backwards compatibility)\n if String(data: packet.payload, encoding: .utf8) != nil {\n // Remove from active peers with proper locking\n collectionsQueue.sync(flags: .barrier) {\n let wasRemoved = self.activePeers.remove(senderID) != nil\n let nickname = self.peerNicknames.removeValue(forKey: senderID) ?? \"unknown\"\n \n if wasRemoved {\n // Mark as gracefully left to prevent duplicate disconnect message\n self.gracefullyLeftPeers.insert(senderID)\n self.gracefulLeaveTimestamps[senderID] = Date()\n \n SecureLogger.log(\"📴 Peer left network: \\(senderID) (\\(nickname)) - marked as gracefully left\", category: SecureLogger.session, level: .info)\n }\n }\n \n announcedPeers.remove(senderID)\n \n // Show disconnect message immediately when peer leaves\n DispatchQueue.main.async {\n self.delegate?.didDisconnectFromPeer(senderID)\n }\n self.notifyPeerListUpdate()\n }\n \n case .fragmentStart, .fragmentContinue, .fragmentEnd:\n // let fragmentTypeStr = packet.type == MessageType.fragmentStart.rawValue ? \"START\" : \n // (packet.type == MessageType.fragmentContinue.rawValue ? \"CONTINUE\" : \"END\")\n \n // Validate fragment has minimum required size\n if packet.payload.count < 13 {\n return\n }\n \n handleFragment(packet, from: peerID)\n \n // Relay fragments if TTL > 0\n var relayPacket = packet\n relayPacket.ttl -= 1\n if relayPacket.ttl > 0 {\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n \n \n case .deliveryAck:\n // Handle delivery acknowledgment\n if let recipientIDData = packet.recipientID,\n isPeerIDOurs(recipientIDData.hexEncodedString()) {\n // This ACK is for us\n let senderID = packet.senderID.hexEncodedString()\n // Check if payload is already decrypted (came through Noise)\n if let ack = DeliveryAck.fromBinaryData(packet.payload) {\n // Already decrypted - process directly\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n } else if let ack = DeliveryAck.decode(from: packet.payload) {\n // Fallback to JSON for backward compatibility\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n } else {\n // Try legacy decryption\n do {\n let decryptedData = try noiseService.decrypt(packet.payload, from: senderID)\n if let ack = DeliveryAck.fromBinaryData(decryptedData) {\n // Process the ACK\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n } else if let ack = DeliveryAck.decode(from: decryptedData) {\n // Fallback to JSON\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n }\n } catch {\n SecureLogger.log(\"Failed to decrypt delivery ACK from \\(senderID): \\(error)\", \n category: SecureLogger.encryption, level: .error)\n }\n }\n } else if packet.ttl > 0 {\n // Relay the ACK if not for us\n \n // SAFETY CHECK: Never relay unencrypted JSON\n if let jsonCheck = String(data: packet.payload.prefix(1), encoding: .utf8), jsonCheck == \"{\" {\n return\n }\n \n var relayPacket = packet\n relayPacket.ttl -= 1\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n \n case .readReceipt:\n // Handle read receipt\n if let recipientIDData = packet.recipientID,\n isPeerIDOurs(recipientIDData.hexEncodedString()) {\n // This read receipt is for us\n let senderID = packet.senderID.hexEncodedString()\n // Received read receipt\n // Check if payload is already decrypted (came through Noise)\n if let receipt = ReadReceipt.fromBinaryData(packet.payload) {\n // Already decrypted - process directly\n // Processing read receipt\n DispatchQueue.main.async {\n self.delegate?.didReceiveReadReceipt(receipt)\n }\n } else if let receipt = ReadReceipt.decode(from: packet.payload) {\n // Fallback to JSON for backward compatibility\n // Processing read receipt (JSON)\n DispatchQueue.main.async {\n self.delegate?.didReceiveReadReceipt(receipt)\n }\n } else {\n // Try legacy decryption\n do {\n let decryptedData = try noiseService.decrypt(packet.payload, from: senderID)\n if let receipt = ReadReceipt.fromBinaryData(decryptedData) {\n // Process the read receipt\n DispatchQueue.main.async {\n self.delegate?.didReceiveReadReceipt(receipt)\n }\n } else if let receipt = ReadReceipt.decode(from: decryptedData) {\n // Fallback to JSON\n DispatchQueue.main.async {\n self.delegate?.didReceiveReadReceipt(receipt)\n }\n }\n } catch {\n // Failed to decrypt read receipt - might be from unknown sender\n }\n }\n } else if packet.ttl > 0 {\n // Relay the read receipt if not for us\n var relayPacket = packet\n relayPacket.ttl -= 1\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n \n case .noiseIdentityAnnounce:\n // Handle Noise identity announcement\n let senderID = packet.senderID.hexEncodedString()\n \n // Check if this identity announce is targeted to someone else\n if let recipientID = packet.recipientID,\n !isPeerIDOurs(recipientID.hexEncodedString()) {\n // Not for us, relay if TTL > 0\n if packet.ttl > 0 {\n // Relay identity announce\n var relayPacket = packet\n relayPacket.ttl -= 1\n let delay = self.exponentialRelayDelay()\n self.scheduleRelay(relayPacket, messageID: messageID, delay: delay)\n }\n return\n }\n \n // Special duplicate detection for identity announces\n processedMessagesLock.lock()\n if let lastSeenTime = recentIdentityAnnounces[senderID] {\n let timeSince = Date().timeIntervalSince(lastSeenTime)\n if timeSince < identityAnnounceDuplicateWindow {\n processedMessagesLock.unlock()\n SecureLogger.log(\"Dropped duplicate identity announce from \\(senderID) (last seen \\(timeSince)s ago)\", \n category: SecureLogger.security, level: .debug)\n return\n }\n }\n recentIdentityAnnounces[senderID] = Date()\n processedMessagesLock.unlock()\n \n if senderID != myPeerID && !isPeerIDOurs(senderID) {\n // Create defensive copy and validate\n let payloadCopy = Data(packet.payload)\n \n guard !payloadCopy.isEmpty else {\n SecureLogger.log(\"Received empty NoiseIdentityAnnouncement from \\(senderID)\", category: SecureLogger.noise, level: .error)\n return\n }\n \n // Decode the announcement\n let announcement: NoiseIdentityAnnouncement?\n if let firstByte = payloadCopy.first, firstByte == 0x7B { // '{' character - JSON\n announcement = NoiseIdentityAnnouncement.decode(from: payloadCopy) ?? NoiseIdentityAnnouncement.fromBinaryData(payloadCopy)\n } else {\n announcement = NoiseIdentityAnnouncement.fromBinaryData(payloadCopy) ?? NoiseIdentityAnnouncement.decode(from: payloadCopy)\n }\n \n guard let announcement = announcement else {\n SecureLogger.log(\"Failed to decode NoiseIdentityAnnouncement from \\(senderID), size: \\(payloadCopy.count)\", category: SecureLogger.noise, level: .error)\n return\n }\n \n // Verify the signature using the signing public key\n let timestampData = String(Int64(announcement.timestamp.timeIntervalSince1970 * 1000)).data(using: .utf8)!\n let bindingData = announcement.peerID.data(using: .utf8)! + announcement.publicKey + timestampData\n if !noiseService.verifySignature(announcement.signature, for: bindingData, publicKey: announcement.signingPublicKey) {\n SecureLogger.log(\"Signature verification failed for \\(senderID)\", category: SecureLogger.noise, level: .warning)\n return // Reject announcements with invalid signatures\n }\n \n // Calculate fingerprint from public key\n let hash = SHA256.hash(data: announcement.publicKey)\n let fingerprint = hash.map { String(format: \"%02x\", $0) }.joined()\n \n // Log receipt of identity announce\n SecureLogger.log(\"Received identity announce from \\(announcement.peerID) (\\(announcement.nickname))\", \n category: SecureLogger.noise, level: .info)\n \n // Create the binding\n let binding = PeerIdentityBinding(\n currentPeerID: announcement.peerID,\n fingerprint: fingerprint,\n publicKey: announcement.publicKey,\n signingPublicKey: announcement.signingPublicKey,\n nickname: announcement.nickname,\n bindingTimestamp: announcement.timestamp,\n signature: announcement.signature\n )\n \n SecureLogger.log(\"Creating identity binding for \\(announcement.peerID) -> \\(fingerprint)\", category: SecureLogger.security, level: .info)\n \n // Handle peer ID rotation if previousPeerID is provided\n if let previousID = announcement.previousPeerID, previousID != announcement.peerID {\n SecureLogger.log(\"Peer announced rotation from \\(previousID) to \\(announcement.peerID)\", \n category: SecureLogger.security, level: .info)\n \n // Transfer states from previous ID\n collectionsQueue.sync(flags: .barrier) {\n // Transfer gracefullyLeft state\n if self.gracefullyLeftPeers.contains(previousID) {\n self.gracefullyLeftPeers.remove(previousID)\n self.gracefullyLeftPeers.insert(announcement.peerID)\n }\n \n // Clean up the old peer ID from active peers\n if self.activePeers.contains(previousID) {\n self.activePeers.remove(previousID)\n // Don't add new ID yet - let normal flow handle it\n }\n }\n }\n \n // Update our mappings\n updatePeerBinding(announcement.peerID, fingerprint: fingerprint, binding: binding)\n \n // Update connection state only if we're not already authenticated\n let currentState = peerConnectionStates[announcement.peerID] ?? .disconnected\n if currentState != .authenticated {\n updatePeerConnectionState(announcement.peerID, state: .connected)\n }\n \n // Register the peer's public key with ChatViewModel for verification tracking\n DispatchQueue.main.async { [weak self] in\n (self?.delegate as? ChatViewModel)?.registerPeerPublicKey(peerID: announcement.peerID, publicKeyData: announcement.publicKey)\n }\n \n // Lazy handshake: No longer initiate handshake on identity announcement\n // Just respond with our own identity announcement\n if !noiseService.hasEstablishedSession(with: announcement.peerID) {\n // Send our identity back so they know we're here\n SecureLogger.log(\"Responding to identity announce from \\(announcement.peerID) with our own (lazy handshake mode)\", \n category: SecureLogger.noise, level: .info)\n sendNoiseIdentityAnnounce(to: announcement.peerID)\n } else {\n // We already have a session, ensure ChatViewModel knows about the fingerprint\n // This handles the case where handshake completed before identity announcement\n DispatchQueue.main.async { [weak self] in\n if let publicKeyData = self?.noiseService.getPeerPublicKeyData(announcement.peerID) {\n (self?.delegate as? ChatViewModel)?.registerPeerPublicKey(peerID: announcement.peerID, publicKeyData: publicKeyData)\n }\n }\n }\n }\n \n case .noiseHandshakeInit:\n // Handle incoming Noise handshake initiation\n let senderID = packet.senderID.hexEncodedString()\n SecureLogger.logHandshake(\"initiation received\", peerID: senderID, success: true)\n \n // Check if this handshake is for us or broadcast\n if let recipientID = packet.recipientID,\n !isPeerIDOurs(recipientID.hexEncodedString()) {\n // Not for us, relay if TTL > 0\n if packet.ttl > 0 {\n // Relay handshake init\n var relayPacket = packet\n relayPacket.ttl -= 1\n broadcastPacket(relayPacket)\n }\n return\n }\n if !isPeerIDOurs(senderID) {\n // Check if we already have an established session\n if noiseService.hasEstablishedSession(with: senderID) {\n // Determine who should be initiator based on peer ID comparison\n let shouldBeInitiator = myPeerID < senderID\n \n if shouldBeInitiator {\n // We should be initiator but peer is initiating - likely they had a session failure\n SecureLogger.log(\"Received handshake init from \\(senderID) who should be responder - likely session mismatch, clearing and accepting\", category: SecureLogger.noise, level: .warning)\n cleanupPeerCryptoState(senderID)\n } else {\n // Check if we've heard from this peer recently\n let lastHeard = lastHeardFromPeer[senderID] ?? Date.distantPast\n let timeSinceLastHeard = Date().timeIntervalSince(lastHeard)\n \n // Check session validity before clearing\n let lastSuccess = lastSuccessfulMessageTime[senderID] ?? Date.distantPast\n let sessionAge = Date().timeIntervalSince(lastSuccess)\n \n // If the peer is initiating a handshake despite us having a valid session,\n // they must have cleared their session for a good reason (e.g., decryption failure).\n // We should always accept the handshake to re-establish encryption.\n SecureLogger.log(\"Received handshake init from \\(senderID) with existing session (age: \\(Int(sessionAge))s, last heard: \\(Int(timeSinceLastHeard))s ago) - accepting to re-establish encryption\", \n category: SecureLogger.handshake, level: .info)\n cleanupPeerCryptoState(senderID)\n }\n }\n \n // If we have a handshaking session, reset it to allow new handshake\n if noiseService.hasSession(with: senderID) && !noiseService.hasEstablishedSession(with: senderID) {\n SecureLogger.log(\"Received handshake init from \\(senderID) while already handshaking - resetting to allow new handshake\", category: SecureLogger.noise, level: .info)\n cleanupPeerCryptoState(senderID)\n }\n \n // Check if we've completed version negotiation with this peer\n if negotiatedVersions[senderID] == nil {\n // Legacy peer - assume version 1 for backward compatibility\n SecureLogger.log(\"Received Noise handshake from \\(senderID) without version negotiation, assuming v1\", \n category: SecureLogger.session, level: .debug)\n negotiatedVersions[senderID] = 1\n versionNegotiationState[senderID] = .ackReceived(version: 1)\n }\n handleNoiseHandshakeMessage(from: senderID, message: packet.payload, isInitiation: true)\n \n // Send protocol ACK for successfully processed handshake initiation\n sendProtocolAck(for: packet, to: senderID)\n }\n \n case .noiseHandshakeResp:\n // Handle Noise handshake response\n let senderID = packet.senderID.hexEncodedString()\n SecureLogger.logHandshake(\"response received\", peerID: senderID, success: true)\n \n // Check if this handshake response is for us\n if let recipientID = packet.recipientID {\n let recipientIDStr = recipientID.hexEncodedString()\n SecureLogger.log(\"Response targeted to: \\(recipientIDStr), is us: \\(isPeerIDOurs(recipientIDStr))\", category: SecureLogger.noise, level: .debug)\n if !isPeerIDOurs(recipientIDStr) {\n // Not for us, relay if TTL > 0\n if packet.ttl > 0 {\n // Relay handshake response\n var relayPacket = packet\n relayPacket.ttl -= 1\n broadcastPacket(relayPacket)\n }\n return\n }\n }\n \n if !isPeerIDOurs(senderID) {\n // Check our current handshake state\n let currentState = handshakeCoordinator.getHandshakeState(for: senderID)\n SecureLogger.log(\"Processing handshake response from \\(senderID), current state: \\(currentState)\", category: SecureLogger.noise, level: .info)\n \n // Process the response - this could be message 2 or message 3 in the XX pattern\n handleNoiseHandshakeMessage(from: senderID, message: packet.payload, isInitiation: false)\n \n // Send protocol ACK for successfully processed handshake response\n sendProtocolAck(for: packet, to: senderID)\n }\n \n case .noiseEncrypted:\n // Handle Noise encrypted message\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n let recipientID = packet.recipientID?.hexEncodedString() ?? \"\"\n \n // Check if this message is for us\n if isPeerIDOurs(recipientID) {\n // Message is for us, try to decrypt\n handleNoiseEncryptedMessage(from: senderID, encryptedData: packet.payload, originalPacket: packet, peripheral: peripheral)\n } else if packet.ttl > 1 {\n // Message is not for us but has TTL > 1, consider relaying\n // Only relay if we think we might be able to reach the recipient\n \n // Check if recipient is directly connected to us\n let canReachDirectly = connectedPeripherals[recipientID] != nil\n \n // Check if we've seen this recipient recently (might be reachable via relay)\n let seenRecently = collectionsQueue.sync {\n if let lastSeen = self.peerLastSeenTimestamps.get(recipientID) {\n return Date().timeIntervalSince(lastSeen) < 180.0 // Seen in last 3 minutes\n }\n return false\n }\n \n if canReachDirectly || seenRecently {\n // Relay the message with reduced TTL\n var relayPacket = packet\n relayPacket.ttl = min(packet.ttl - 1, 2) // Decrement TTL, max 2 for relayed private messages\n \n SecureLogger.log(\"Relaying private message from \\(senderID) to \\(recipientID) (TTL: \\(relayPacket.ttl))\", \n category: SecureLogger.session, level: .debug)\n \n if canReachDirectly {\n // Send directly to recipient\n _ = sendDirectToRecipient(relayPacket, recipientPeerID: recipientID)\n } else {\n // Use selective relay\n sendViaSelectiveRelay(relayPacket, recipientPeerID: recipientID)\n }\n } else {\n SecureLogger.log(\"Not relaying private message to \\(recipientID) - recipient not reachable\", \n category: SecureLogger.session, level: .debug)\n }\n } else {\n // recipientID is empty or invalid, try to decrypt anyway (backwards compatibility)\n handleNoiseEncryptedMessage(from: senderID, encryptedData: packet.payload, originalPacket: packet, peripheral: peripheral)\n }\n }\n \n case .versionHello:\n // Handle version negotiation hello\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n handleVersionHello(from: senderID, data: packet.payload, peripheral: peripheral)\n }\n \n case .versionAck:\n // Handle version negotiation acknowledgment\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n handleVersionAck(from: senderID, data: packet.payload)\n }\n \n case .protocolAck:\n // Handle protocol-level acknowledgment\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n handleProtocolAck(from: senderID, data: packet.payload)\n }\n \n case .protocolNack:\n // Handle protocol-level negative acknowledgment\n let senderID = packet.senderID.hexEncodedString()\n if let recipientIDData = packet.recipientID,\n isPeerIDOurs(recipientIDData.hexEncodedString())\n && !isPeerIDOurs(senderID) {\n handleProtocolNack(from: senderID, data: packet.payload)\n }\n \n case .systemValidation:\n // Handle system validation ping (for session sync verification)\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n // Try to decrypt the validation ping\n do {\n let decrypted = try noiseService.decrypt(packet.payload, from: senderID)\n SecureLogger.log(\"Successfully validated session with \\(senderID) - ping: \\(String(data: decrypted, encoding: .utf8) ?? \"?\")\", \n category: SecureLogger.session, level: .debug)\n \n // Session is valid, update last successful message time\n lastSuccessfulMessageTime[senderID] = Date()\n } catch {\n // Validation failed - session is out of sync\n SecureLogger.log(\"Session validation failed with \\(senderID): \\(error)\", \n category: SecureLogger.session, level: .warning)\n \n // Send NACK to trigger session re-establishment\n sendProtocolNack(for: packet, to: senderID, \n reason: \"Session validation failed\", \n errorCode: .decryptionFailed)\n }\n }\n \n case .handshakeRequest:\n // Handle handshake request for pending messages\n let senderID = packet.senderID.hexEncodedString()\n if !isPeerIDOurs(senderID) {\n handleHandshakeRequest(from: senderID, data: packet.payload)\n }\n \n default:\n break\n }\n }\n }\n \n private func sendFragmentedPacket(_ packet: BitchatPacket) {\n guard let fullData = packet.toBinaryData() else { return }\n \n // Generate a fixed 8-byte fragment ID\n var fragmentID = Data(count: 8)\n fragmentID.withUnsafeMutableBytes { bytes in\n arc4random_buf(bytes.baseAddress, 8)\n }\n \n let fragments = stride(from: 0, to: fullData.count, by: maxFragmentSize).map { offset in\n fullData[offset..> 8) & 0xFF))\n fragmentPayload.append(UInt8(index & 0xFF))\n fragmentPayload.append(UInt8((fragments.count >> 8) & 0xFF))\n fragmentPayload.append(UInt8(fragments.count & 0xFF))\n fragmentPayload.append(packet.type)\n fragmentPayload.append(fragmentData)\n \n let fragmentType: MessageType\n if index == 0 {\n fragmentType = .fragmentStart\n } else if index == fragments.count - 1 {\n fragmentType = .fragmentEnd\n } else {\n fragmentType = .fragmentContinue\n }\n \n let fragmentPacket = BitchatPacket(\n type: fragmentType.rawValue,\n senderID: packet.senderID, // Use original packet's senderID (already Data)\n recipientID: packet.recipientID, // Preserve recipient if any\n timestamp: packet.timestamp, // Use original timestamp\n payload: fragmentPayload,\n signature: nil, // Fragments don't need signatures\n ttl: packet.ttl )\n \n // Send fragments with linear delay\n let totalDelay = Double(index) * delayBetweenFragments\n \n // Send fragments on background queue with calculated delay\n messageQueue.asyncAfter(deadline: .now() + totalDelay) { [weak self] in\n self?.broadcastPacket(fragmentPacket)\n }\n }\n \n let _ = Double(fragments.count - 1) * delayBetweenFragments\n }\n \n private func handleFragment(_ packet: BitchatPacket, from peerID: String) {\n // Handling fragment\n \n guard packet.payload.count >= 13 else { \n return \n }\n \n // Convert to array for safer access\n let payloadArray = Array(packet.payload)\n var offset = 0\n \n // Extract fragment ID as binary data (8 bytes)\n guard payloadArray.count >= 8 else {\n return\n }\n \n let fragmentIDData = Data(payloadArray[0..<8])\n let fragmentID = fragmentIDData.hexEncodedString()\n offset = 8\n \n // Safely extract index\n guard payloadArray.count >= offset + 2 else { \n // Not enough data for index\n return \n }\n let index = Int(payloadArray[offset]) << 8 | Int(payloadArray[offset + 1])\n offset += 2\n \n // Safely extract total\n guard payloadArray.count >= offset + 2 else { \n // Not enough data for total\n return \n }\n let total = Int(payloadArray[offset]) << 8 | Int(payloadArray[offset + 1])\n offset += 2\n \n // Safely extract original type\n guard payloadArray.count >= offset + 1 else { \n // Not enough data for type\n return \n }\n let originalType = payloadArray[offset]\n offset += 1\n \n // Extract fragment data\n let fragmentData: Data\n if payloadArray.count > offset {\n fragmentData = Data(payloadArray[offset...])\n } else {\n fragmentData = Data()\n }\n \n \n // Initialize fragment collection if needed\n if incomingFragments[fragmentID] == nil {\n // Check if we've reached the concurrent session limit\n if incomingFragments.count >= maxConcurrentFragmentSessions {\n // Clean up oldest fragments first\n cleanupOldFragments()\n \n // If still at limit, reject new session to prevent DoS\n if incomingFragments.count >= maxConcurrentFragmentSessions {\n return\n }\n }\n \n incomingFragments[fragmentID] = [:]\n fragmentMetadata[fragmentID] = (originalType, total, Date())\n }\n \n incomingFragments[fragmentID]?[index] = fragmentData\n \n \n // Check if we have all fragments\n if let fragments = incomingFragments[fragmentID],\n fragments.count == total {\n \n // Reassemble the original packet\n var reassembledData = Data()\n for i in 0.. maxFragmentBytes {\n // Remove oldest fragments until under limit\n let sortedFragments = fragmentMetadata.sorted { $0.value.timestamp < $1.value.timestamp }\n for (fragID, _) in sortedFragments {\n incomingFragments.removeValue(forKey: fragID)\n fragmentMetadata.removeValue(forKey: fragID)\n \n // Recalculate total\n totalFragmentBytes = 0\n for (_, fragments) in incomingFragments {\n for (_, data) in fragments {\n totalFragmentBytes += data.count\n }\n }\n \n if totalFragmentBytes <= maxFragmentBytes {\n break\n }\n }\n }\n }\n} // End of BluetoothMeshService class\n\nextension BluetoothMeshService: CBCentralManagerDelegate {\n // MARK: - CBCentralManagerDelegate\n \n func centralManagerDidUpdateState(_ central: CBCentralManager) {\n // Central manager state updated\n switch central.state {\n case .unknown: break\n case .resetting: break\n case .unsupported: break\n case .unauthorized: break\n case .poweredOff: break\n case .poweredOn: break\n @unknown default: break\n }\n \n if central.state == .unsupported {\n } else if central.state == .unauthorized {\n } else if central.state == .poweredOff {\n } else if central.state == .poweredOn {\n startScanning()\n \n // Send announces when central manager is ready\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n self?.sendBroadcastAnnounce()\n }\n }\n }\n \n func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {\n // Optimize for 300m range - only connect to strong enough signals\n let rssiValue = RSSI.intValue\n \n // Dynamic RSSI threshold based on peer count (smart compromise)\n let rssiThreshold = dynamicRSSIThreshold\n guard rssiValue > rssiThreshold else { \n // Ignoring peripheral due to weak signal (threshold: \\(rssiThreshold) dBm)\n return \n }\n \n // Throttle RSSI updates to save CPU\n let peripheralID = peripheral.identifier.uuidString\n if let lastUpdate = lastRSSIUpdate[peripheralID],\n Date().timeIntervalSince(lastUpdate) < 1.0 {\n return // Skip update if less than 1 second since last update\n }\n lastRSSIUpdate[peripheralID] = Date()\n \n // Store RSSI by peripheral ID for later use\n peripheralRSSI[peripheralID] = RSSI\n \n // Extract peer ID from name (no prefix for stealth)\n // Peer IDs are 8 bytes = 16 hex characters\n if let name = peripheral.name, name.count == 16 {\n // Assume 16-character hex names are peer IDs\n let peerID = name\n SecureLogger.log(\"Discovery: Found peer ID \\(peerID) from peripheral name\", category: SecureLogger.session, level: .debug)\n \n // Don't process our own advertisements (including previous peer IDs)\n if isPeerIDOurs(peerID) {\n SecureLogger.log(\"Discovery: Ignoring our own peer ID \\(peerID)\", category: SecureLogger.session, level: .debug)\n return\n }\n \n // Validate RSSI before storing\n let rssiValue = RSSI.intValue\n if rssiValue != 127 && rssiValue >= -100 && rssiValue <= 0 {\n peerRSSI[peerID] = RSSI\n }\n // Discovered potential peer\n SecureLogger.log(\"Discovered peer with ID: \\(peerID), self ID: \\(myPeerID)\", category: SecureLogger.noise, level: .debug)\n }\n \n // Connection pooling with exponential backoff\n // peripheralID already declared above\n \n // Check if we should attempt connection (considering backoff)\n if let backoffTime = connectionBackoff[peripheralID],\n Date().timeIntervalSince1970 < backoffTime {\n // Still in backoff period, skip connection\n return\n }\n \n // Check if we already have this peripheral in our pool\n if let pooledPeripheral = connectionPool[peripheralID] {\n // Reuse existing peripheral from pool\n if pooledPeripheral.state == CBPeripheralState.disconnected {\n // Reconnect if disconnected with optimized parameters\n let connectionOptions: [String: Any] = [\n CBConnectPeripheralOptionNotifyOnConnectionKey: true,\n CBConnectPeripheralOptionNotifyOnDisconnectionKey: true,\n CBConnectPeripheralOptionNotifyOnNotificationKey: true\n ]\n \n // Smart compromise: would set low latency for small networks if API supported it\n // iOS/macOS don't expose connection interval control in public API\n \n central.connect(pooledPeripheral, options: connectionOptions)\n }\n return\n }\n \n // New peripheral - add to pool and connect\n if !discoveredPeripherals.contains(peripheral) {\n // Check connection pool limits\n let connectedCount = connectionPool.values.filter { $0.state == .connected }.count\n if connectedCount >= maxConnectedPeripherals {\n // Connection pool is full - find least recently used peripheral to disconnect\n if let lruPeripheralID = findLeastRecentlyUsedPeripheral() {\n if let lruPeripheral = connectionPool[lruPeripheralID] {\n SecureLogger.log(\"Connection pool full, disconnecting LRU peripheral: \\(lruPeripheralID)\", \n category: SecureLogger.session, level: .debug)\n central.cancelPeripheralConnection(lruPeripheral)\n connectionPool.removeValue(forKey: lruPeripheralID)\n }\n }\n }\n \n discoveredPeripherals.append(peripheral)\n peripheral.delegate = self\n connectionPool[peripheralID] = peripheral\n \n // Track connection attempts\n let attempts = connectionAttempts[peripheralID] ?? 0\n connectionAttempts[peripheralID] = attempts + 1\n \n // Only attempt if under max attempts\n if attempts < maxConnectionAttempts {\n // Use optimized connection parameters based on peer count\n let connectionOptions: [String: Any] = [\n CBConnectPeripheralOptionNotifyOnConnectionKey: true,\n CBConnectPeripheralOptionNotifyOnDisconnectionKey: true,\n CBConnectPeripheralOptionNotifyOnNotificationKey: true\n ]\n \n // Smart compromise: would set low latency for small networks if API supported it\n // iOS/macOS don't expose connection interval control in public API\n \n central.connect(peripheral, options: connectionOptions)\n }\n }\n }\n \n func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {\n let peripheralID = peripheral.identifier.uuidString\n \n peripheral.delegate = self\n peripheral.discoverServices([BluetoothMeshService.serviceUUID])\n \n // Register peripheral in simplified mapping system\n registerPeripheral(peripheral)\n \n // Store peripheral temporarily until we get the real peer ID\n connectedPeripherals[peripheralID] = peripheral\n \n SecureLogger.log(\"Connected to peripheral \\(peripheralID) - awaiting peer ID\", \n category: SecureLogger.session, level: .debug)\n \n // Update connection state to connected (but not authenticated yet)\n // We don't know the real peer ID yet, so we can't update the state\n \n // Don't show connected message yet - wait for key exchange\n // This prevents the connect/disconnect/connect pattern\n \n // Request RSSI reading\n peripheral.readRSSI()\n \n // iOS 11+ BLE 5.0: Request 2M PHY for better range and speed\n if #available(iOS 11.0, macOS 10.14, *) {\n // 2M PHY provides better range than 1M PHY\n // This is a hint - system will use best available\n }\n }\n \n func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {\n let peripheralID = peripheral.identifier.uuidString\n \n // Clean up RSSI retry count\n rssiRetryCount.removeValue(forKey: peripheralID)\n \n // Check if this was an intentional disconnect\n if intentionalDisconnects.contains(peripheralID) {\n intentionalDisconnects.remove(peripheralID)\n SecureLogger.log(\"Intentional disconnect: \\(peripheralID)\", category: SecureLogger.session, level: .debug)\n // Don't process this disconnect further\n return\n }\n \n // Log disconnect with error if present\n if let error = error {\n SecureLogger.logError(error, context: \"Peripheral disconnected: \\(peripheralID)\", category: SecureLogger.session)\n } else {\n SecureLogger.log(\"Peripheral disconnected normally: \\(peripheralID)\", category: SecureLogger.session, level: .info)\n }\n \n // Find the real peer ID using simplified mapping\n var realPeerID: String? = nil\n \n if let mapping = peripheralMappings[peripheralID], let peerID = mapping.peerID {\n realPeerID = peerID\n SecureLogger.log(\"Found peer ID \\(peerID) for peripheral \\(peripheralID)\", \n category: SecureLogger.session, level: .debug)\n } else if let peerID = peerIDByPeripheralID[peripheralID] {\n // Fallback to legacy mapping\n realPeerID = peerID\n SecureLogger.log(\"Found peer ID \\(peerID) from legacy mapping for peripheral \\(peripheralID)\", \n category: SecureLogger.session, level: .debug)\n } else {\n SecureLogger.log(\"No peer ID mapping found for peripheral \\(peripheralID)\", \n category: SecureLogger.session, level: .debug)\n \n // Fallback: check if we have a direct mapping from peripheral to peer ID\n for (peerID, connectedPeripheral) in connectedPeripherals {\n if connectedPeripheral.identifier == peripheral.identifier {\n // Check if this is a real peer ID (16 hex chars) not a temp ID\n if peerID.count == 16 && peerID.allSatisfy({ $0.isHexDigit }) {\n realPeerID = peerID\n SecureLogger.log(\"Found peer ID \\(peerID) from connectedPeripherals fallback\", \n category: SecureLogger.session, level: .debug)\n break\n } else {\n SecureLogger.log(\"Skipping non-peer ID '\\(peerID)' (length: \\(peerID.count))\", \n category: SecureLogger.session, level: .debug)\n }\n }\n }\n }\n \n // Update connection state immediately if we have a real peer ID\n if let peerID = realPeerID {\n // Update peer connection state\n updatePeerConnectionState(peerID, state: .disconnected)\n \n // Clear pending messages for disconnected peer to prevent retry loops\n collectionsQueue.async(flags: .barrier) { [weak self] in\n if let pendingCount = self?.pendingPrivateMessages[peerID]?.count, pendingCount > 0 {\n SecureLogger.log(\"Clearing \\(pendingCount) pending messages for disconnected peer \\(peerID)\", \n category: SecureLogger.session, level: .info)\n self?.pendingPrivateMessages[peerID]?.removeAll()\n }\n }\n \n // Reset handshake state to prevent stuck handshakes\n handshakeCoordinator.resetHandshakeState(for: peerID)\n \n // Check if peer gracefully left and notify delegate\n let shouldNotifyDisconnect = collectionsQueue.sync {\n let isGracefullyLeft = self.gracefullyLeftPeers.contains(peerID)\n if isGracefullyLeft {\n SecureLogger.log(\"Physical disconnect for \\(peerID) - was gracefully left, NOT notifying delegate\", category: SecureLogger.session, level: .info)\n } else {\n SecureLogger.log(\"Physical disconnect for \\(peerID) - was NOT gracefully left, will notify delegate\", category: SecureLogger.session, level: .info)\n }\n return !isGracefullyLeft\n }\n \n if shouldNotifyDisconnect {\n DispatchQueue.main.async {\n self.delegate?.didDisconnectFromPeer(peerID)\n }\n }\n }\n \n // Implement exponential backoff for failed connections\n if error != nil {\n let attempts = connectionAttempts[peripheralID] ?? 0\n if attempts >= maxConnectionAttempts {\n // Max attempts reached, apply long backoff\n let backoffDuration = baseBackoffInterval * pow(2.0, Double(attempts))\n connectionBackoff[peripheralID] = Date().timeIntervalSince1970 + backoffDuration\n }\n } else {\n // Clean disconnect, reset attempts\n connectionAttempts[peripheralID] = 0\n connectionBackoff.removeValue(forKey: peripheralID)\n }\n \n // Clean up peripheral tracking\n peripheralMappings.removeValue(forKey: peripheralID)\n peerIDByPeripheralID.removeValue(forKey: peripheralID)\n lastActivityByPeripheralID.removeValue(forKey: peripheralID)\n \n // Find peer ID for this peripheral (could be temp ID or real ID)\n var foundPeerID: String? = nil\n for (id, per) in connectedPeripherals {\n if per == peripheral {\n foundPeerID = id\n break\n }\n }\n \n if let peerID = foundPeerID {\n connectedPeripherals.removeValue(forKey: peerID)\n peripheralCharacteristics.removeValue(forKey: peripheral)\n \n // Don't clear Noise session on disconnect - sessions should survive disconnects\n // The Noise protocol is designed to maintain sessions across network interruptions\n // Only clear sessions on authentication failure\n if peerID.count == 16 { // Real peer ID\n // Clear connection time and last heard tracking on disconnect to properly detect stale sessions\n lastConnectionTime.removeValue(forKey: peerID)\n lastHeardFromPeer.removeValue(forKey: peerID)\n // Keep lastSuccessfulMessageTime to validate session on reconnect\n let lastSuccess = lastSuccessfulMessageTime[peerID] ?? Date.distantPast\n let sessionAge = Date().timeIntervalSince(lastSuccess)\n SecureLogger.log(\"Peer disconnected: \\(peerID), keeping Noise session (age: \\(Int(sessionAge))s)\", category: SecureLogger.noise, level: .info)\n }\n \n // Only remove from active peers if it's not a temp ID\n // Temp IDs shouldn't be in activePeers anyway\n let (removed, _) = collectionsQueue.sync(flags: .barrier) {\n var removed = false\n if peerID.count == 16 { // Real peer ID (8 bytes = 16 hex chars)\n removed = activePeers.remove(peerID) != nil\n if removed {\n // Only log disconnect if peer didn't gracefully leave\n if !self.gracefullyLeftPeers.contains(peerID) {\n let nickname = self.peerNicknames[peerID] ?? \"unknown\"\n SecureLogger.log(\"📴 Peer disconnected from network: \\(peerID) (\\(nickname))\", category: SecureLogger.session, level: .info)\n } else {\n // Peer gracefully left, just clean up the tracking\n self.gracefullyLeftPeers.remove(peerID)\n self.gracefulLeaveTimestamps.removeValue(forKey: peerID)\n SecureLogger.log(\"Cleaning up gracefullyLeftPeers for \\(peerID)\", category: SecureLogger.session, level: .debug)\n }\n }\n \n _ = announcedPeers.remove(peerID)\n _ = announcedToPeers.remove(peerID)\n } else {\n }\n \n // Clear cached messages tracking for this peer to allow re-sending if they reconnect\n cachedMessagesSentToPeer.remove(peerID)\n \n // Clear version negotiation state\n versionNegotiationState.removeValue(forKey: peerID)\n negotiatedVersions.removeValue(forKey: peerID)\n \n // Peer disconnected\n \n return (removed, peerNicknames[peerID])\n }\n \n // Always notify peer list update on disconnect, regardless of whether peer was in activePeers\n // This ensures UI stays in sync even if there was a state mismatch\n self.notifyPeerListUpdate(immediate: true)\n \n if removed {\n // Mark when network became empty, but don't reset flag immediately\n let currentNetworkSize = collectionsQueue.sync { activePeers.count }\n if currentNetworkSize == 0 && networkBecameEmptyTime == nil {\n networkBecameEmptyTime = Date()\n }\n }\n }\n \n // Keep in pool but remove from discovered list\n discoveredPeripherals.removeAll { $0 == peripheral }\n \n // Continue scanning for reconnection\n if centralManager?.state == .poweredOn {\n // Stop and restart to ensure clean state\n centralManager?.stopScan()\n centralManager?.scanForPeripherals(withServices: [BluetoothMeshService.serviceUUID], options: [CBCentralManagerScanOptionAllowDuplicatesKey: false])\n }\n }\n}\n\nextension BluetoothMeshService: CBPeripheralDelegate {\n // MARK: - CBPeripheralDelegate\n \n func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {\n if let error = error {\n SecureLogger.log(\"Error discovering services: \\(error)\", \n category: SecureLogger.encryption, level: .error)\n return\n }\n \n guard let services = peripheral.services else { return }\n \n \n for service in services {\n peripheral.discoverCharacteristics([BluetoothMeshService.characteristicUUID], for: service)\n }\n }\n \n func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {\n if let error = error {\n SecureLogger.log(\"Error discovering characteristics: \\(error)\", \n category: SecureLogger.encryption, level: .error)\n return\n }\n \n guard let characteristics = service.characteristics else { return }\n \n \n for characteristic in characteristics {\n if characteristic.uuid == BluetoothMeshService.characteristicUUID {\n peripheral.setNotifyValue(true, for: characteristic)\n peripheralCharacteristics[peripheral] = characteristic\n \n // Request maximum MTU for faster data transfer\n // iOS supports up to 512 bytes with BLE 5.0\n peripheral.maximumWriteValueLength(for: .withoutResponse)\n \n // Start version negotiation instead of immediately sending Noise identity\n self.sendVersionHello(to: peripheral)\n \n // Send announce packet after version negotiation completes\n if let vm = self.delegate as? ChatViewModel {\n // Send single announce with slight delay\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in\n guard let self = self else { return }\n let announcePacket = BitchatPacket(\n type: MessageType.announce.rawValue,\n ttl: 3,\n senderID: self.myPeerID,\n payload: Data(vm.nickname.utf8) )\n self.broadcastPacket(announcePacket)\n }\n \n // Also send targeted announce to this specific peripheral\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [weak self, weak peripheral] in\n guard let self = self,\n let peripheral = peripheral,\n peripheral.state == .connected,\n let characteristic = peripheral.services?.first(where: { $0.uuid == BluetoothMeshService.serviceUUID })?.characteristics?.first(where: { $0.uuid == BluetoothMeshService.characteristicUUID }) else { return }\n \n let announcePacket = BitchatPacket(\n type: MessageType.announce.rawValue,\n ttl: 3,\n senderID: self.myPeerID,\n payload: Data(vm.nickname.utf8) )\n if let data = announcePacket.toBinaryData() {\n self.writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: nil)\n }\n }\n }\n }\n }\n }\n \n func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {\n guard let data = characteristic.value else {\n return\n }\n \n // Update activity tracking for this peripheral\n updatePeripheralActivity(peripheral.identifier.uuidString)\n \n \n guard let packet = BitchatPacket.from(data) else { \n return \n }\n \n \n // Use the sender ID from the packet, not our local mapping which might still be a temp ID\n let _ = connectedPeripherals.first(where: { $0.value == peripheral })?.key ?? \"unknown\"\n let packetSenderID = packet.senderID.hexEncodedString()\n \n \n // Always handle received packets\n handleReceivedPacket(packet, from: packetSenderID, peripheral: peripheral)\n }\n \n func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {\n if let error = error {\n // Log error but don't spam for common errors\n let errorCode = (error as NSError).code\n if errorCode != 242 { // Don't log the common \"Unknown ATT error\"\n }\n } else {\n }\n }\n \n func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {\n peripheral.discoverServices([BluetoothMeshService.serviceUUID])\n }\n \n func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {\n // Handle notification state updates if needed\n }\n \n func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {\n let peripheralID = peripheral.identifier.uuidString\n \n if error != nil {\n return\n }\n \n // Validate RSSI value - 127 means no RSSI available\n let rssiValue = RSSI.intValue\n \n // Only store valid RSSI values\n if rssiValue == 127 || rssiValue < -100 || rssiValue > 0 {\n // Track retry count\n let retryCount = rssiRetryCount[peripheralID] ?? 0\n rssiRetryCount[peripheralID] = retryCount + 1\n \n \n // Retry up to 5 times with exponential backoff\n if retryCount < 5 {\n let delay = min(0.2 * pow(2.0, Double(retryCount)), 2.0) // 0.2s, 0.4s, 0.8s, 1.6s, 2.0s max\n DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self, weak peripheral] in\n guard let peripheral = peripheral, peripheral.state == .connected else { \n self?.rssiRetryCount.removeValue(forKey: peripheralID)\n return \n }\n peripheral.readRSSI()\n }\n } else {\n // Give up after 5 retries, reset counter\n rssiRetryCount.removeValue(forKey: peripheralID)\n }\n return\n }\n \n // Valid RSSI received, reset retry count\n rssiRetryCount.removeValue(forKey: peripheralID)\n \n // Update RSSI in simplified mapping\n updatePeripheralRSSI(peripheralID: peripheralID, rssi: RSSI)\n \n // Also store in legacy mapping for compatibility\n peripheralRSSI[peripheralID] = RSSI\n \n // If we have a peer ID, update peer RSSI (handled in updatePeripheralRSSI)\n if let mapping = peripheralMappings[peripheralID], mapping.isIdentified {\n // Force UI update when we have a real peer ID\n DispatchQueue.main.async { [weak self] in\n self?.notifyPeerListUpdate()\n }\n } else {\n // Keep trying to read RSSI until we get real peer ID\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak peripheral] in\n guard let peripheral = peripheral, peripheral.state == .connected else { return }\n peripheral.readRSSI()\n }\n }\n \n // Periodically update RSSI\n DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) { [weak peripheral] in\n guard let peripheral = peripheral, peripheral.state == .connected else { return }\n peripheral.readRSSI()\n }\n }\n}\n\nextension BluetoothMeshService: CBPeripheralManagerDelegate {\n // MARK: - CBPeripheralManagerDelegate\n \n func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {\n // Peripheral manager state updated\n switch peripheral.state {\n case .unknown: break\n case .resetting: break\n case .unsupported: break\n case .unauthorized: break\n case .poweredOff: break\n case .poweredOn: break\n @unknown default: break\n }\n \n switch peripheral.state {\n case .unsupported:\n break\n case .unauthorized:\n break\n case .poweredOff:\n break\n case .poweredOn:\n setupPeripheral()\n startAdvertising()\n \n // Send announces when peripheral manager is ready\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n self?.sendBroadcastAnnounce()\n }\n default:\n break\n }\n }\n \n func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) {\n // Service added\n }\n \n func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) {\n // Advertising state changed\n }\n \n func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {\n for request in requests {\n if let data = request.value {\n \n if let packet = BitchatPacket.from(data) {\n \n // Log specific Noise packet types\n switch packet.type {\n case MessageType.noiseHandshakeInit.rawValue:\n break\n case MessageType.noiseHandshakeResp.rawValue:\n break\n case MessageType.noiseEncrypted.rawValue:\n break\n default:\n break\n }\n \n // Try to identify peer from packet\n let peerID = packet.senderID.hexEncodedString()\n \n // Store the central for updates\n if !subscribedCentrals.contains(request.central) {\n subscribedCentrals.append(request.central)\n }\n \n // Track this peer as connected\n if peerID != \"unknown\" && peerID != myPeerID {\n // Double-check we're not adding ourselves\n if peerID == self.myPeerID {\n SecureLogger.log(\"Preventing self from being added as peer (peripheral manager)\", category: SecureLogger.noise, level: .warning)\n peripheral.respond(to: request, withResult: .success)\n return\n }\n \n // Note: Legacy keyExchange (0x02) no longer handled\n \n self.notifyPeerListUpdate()\n }\n \n handleReceivedPacket(packet, from: peerID)\n peripheral.respond(to: request, withResult: .success)\n } else {\n peripheral.respond(to: request, withResult: .invalidPdu)\n }\n } else {\n peripheral.respond(to: request, withResult: .invalidPdu)\n }\n }\n }\n \n func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {\n if !subscribedCentrals.contains(central) {\n subscribedCentrals.append(central)\n \n // Only send identity announcement if we haven't recently\n // This reduces spam when multiple centrals connect quickly\n // sendNoiseIdentityAnnounce() will check rate limits internally\n \n // Update peer list to show we're connected (even without peer ID yet)\n self.notifyPeerListUpdate()\n }\n }\n \n func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) {\n subscribedCentrals.removeAll { $0 == central }\n \n // Don't aggressively remove peers when centrals unsubscribe\n // Peers may be connected through multiple paths\n \n // Ensure advertising continues for reconnection\n if peripheralManager?.state == .poweredOn && peripheralManager?.isAdvertising == false {\n startAdvertising()\n }\n }\n \n // MARK: - Battery Monitoring\n \n private func setupBatteryOptimizer() {\n // Subscribe to power mode changes\n batteryOptimizer.$currentPowerMode\n .sink { [weak self] powerMode in\n self?.handlePowerModeChange(powerMode)\n }\n .store(in: &batteryOptimizerCancellables)\n \n // Subscribe to battery level changes\n batteryOptimizer.$batteryLevel\n .sink { [weak self] level in\n self?.currentBatteryLevel = level\n }\n .store(in: &batteryOptimizerCancellables)\n \n // Initial update\n handlePowerModeChange(batteryOptimizer.currentPowerMode)\n }\n \n private func handlePowerModeChange(_ powerMode: PowerMode) {\n let params = batteryOptimizer.scanParameters\n activeScanDuration = params.duration\n scanPauseDuration = params.pause\n \n // Update max connections\n let maxConnections = powerMode.maxConnections\n \n // If we have too many connections, disconnect from the least important ones\n if connectedPeripherals.count > maxConnections {\n disconnectLeastImportantPeripherals(keepCount: maxConnections)\n }\n \n // Update message aggregation window\n aggregationWindow = powerMode.messageAggregationWindow\n \n // If we're currently scanning, restart with new parameters\n if scanDutyCycleTimer != nil {\n scanDutyCycleTimer?.invalidate()\n scheduleScanDutyCycle()\n }\n \n // Handle advertising intervals\n if powerMode.advertisingInterval > 0 {\n // Stop continuous advertising and use interval-based\n scheduleAdvertisingCycle(interval: powerMode.advertisingInterval)\n } else {\n // Continuous advertising for performance mode\n startAdvertising()\n }\n }\n \n private func disconnectLeastImportantPeripherals(keepCount: Int) {\n // Disconnect peripherals with lowest activity/importance\n let sortedPeripherals = connectedPeripherals.values\n .sorted { peer1, peer2 in\n // Keep peripherals we've recently communicated with\n let peer1Activity = lastMessageFromPeer.get(peer1.identifier.uuidString) ?? Date.distantPast\n let peer2Activity = lastMessageFromPeer.get(peer2.identifier.uuidString) ?? Date.distantPast\n return peer1Activity > peer2Activity\n }\n \n // Disconnect the least active ones\n let toDisconnect = sortedPeripherals.dropFirst(keepCount)\n for peripheral in toDisconnect {\n centralManager?.cancelPeripheralConnection(peripheral)\n }\n }\n \n private func scheduleAdvertisingCycle(interval: TimeInterval) {\n advertisingTimer?.invalidate()\n \n // Stop advertising\n if isAdvertising {\n peripheralManager?.stopAdvertising()\n isAdvertising = false\n }\n \n // Schedule next advertising burst\n advertisingTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in\n self?.advertiseBurst()\n }\n }\n \n private func advertiseBurst() {\n guard batteryOptimizer.currentPowerMode != .ultraLowPower || !batteryOptimizer.isInBackground else {\n return // Skip advertising in ultra low power + background\n }\n \n startAdvertising()\n \n // Stop advertising after a short burst (1 second)\n DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in\n if self?.batteryOptimizer.currentPowerMode.advertisingInterval ?? 0 > 0 {\n self?.peripheralManager?.stopAdvertising()\n self?.isAdvertising = false\n }\n }\n }\n \n // Legacy battery monitoring methods - kept for compatibility\n // Now handled by BatteryOptimizer\n private func updateBatteryLevel() {\n // This method is now handled by BatteryOptimizer\n // Keeping empty implementation for compatibility\n }\n \n private func updateScanParametersForBattery() {\n // This method is now handled by BatteryOptimizer through handlePowerModeChange\n // Keeping empty implementation for compatibility\n }\n \n // MARK: - Privacy Utilities\n \n private func randomDelay() -> TimeInterval {\n // Generate random delay between min and max for timing obfuscation\n return TimeInterval.random(in: minMessageDelay...maxMessageDelay)\n }\n \n // MARK: - Range Optimization Methods\n \n // Calculate relay probability based on RSSI (edge nodes relay more)\n private func calculateRelayProbability(baseProb: Double, rssi: Int) -> Double {\n // RSSI typically ranges from -30 (very close) to -90 (far)\n // We want edge nodes (weak RSSI) to relay more aggressively\n let rssiFactor = Double(100 + rssi) / 100.0 // -90 = 0.1, -70 = 0.3, -50 = 0.5\n \n // Invert the factor so weak signals relay more\n let edgeFactor = max(0.5, 2.0 - rssiFactor)\n \n return min(1.0, baseProb * edgeFactor)\n }\n \n // Exponential delay distribution to prevent synchronized collision storms\n private func exponentialRelayDelay() -> TimeInterval {\n // Use exponential distribution with mean of (min + max) / 2\n let meanDelay = (minMessageDelay + maxMessageDelay) / 2.0\n let lambda = 1.0 / meanDelay\n \n // Generate exponential random value\n let u = Double.random(in: 0..<1)\n let exponentialDelay = -log(1.0 - u) / lambda\n \n // Clamp to our bounds\n return min(maxMessageDelay, max(minMessageDelay, exponentialDelay))\n }\n \n // Check if message type is high priority (should bypass aggregation)\n private func isHighPriorityMessage(type: UInt8) -> Bool {\n switch MessageType(rawValue: type) {\n case .noiseHandshakeInit, .noiseHandshakeResp, .protocolAck,\n .versionHello, .versionAck, .deliveryAck, .systemValidation,\n .handshakeRequest:\n return true\n case .message, .announce, .leave, .readReceipt, .deliveryStatusRequest,\n .fragmentStart, .fragmentContinue, .fragmentEnd,\n .noiseIdentityAnnounce, .noiseEncrypted, .protocolNack, .none:\n return false\n }\n }\n \n // Calculate exponential backoff for retries\n private func calculateExponentialBackoff(retry: Int) -> TimeInterval {\n // Start with 1s, double each time: 1s, 2s, 4s, 8s, 16s, max 30s\n let baseDelay = 1.0\n let maxDelay = 30.0\n let delay = min(maxDelay, baseDelay * pow(2.0, Double(retry - 1)))\n \n // Add 10% jitter to prevent synchronized retries\n let jitter = delay * 0.1 * (Double.random(in: -1...1))\n return delay + jitter\n }\n \n // MARK: - Collision Avoidance\n \n // Calculate jitter based on node ID to spread transmissions\n private func calculateNodeIDJitter() -> TimeInterval {\n // Use hash of peer ID to generate consistent jitter for this node\n let hashValue = myPeerID.hash\n let normalizedHash = Double(abs(hashValue % 1000)) / 1000.0 // 0.0 to 0.999\n \n // Jitter range: 0-20ms based on node ID\n let jitterRange: TimeInterval = 0.02 // 20ms max jitter\n return normalizedHash * jitterRange\n }\n \n // Add smart delay to avoid collisions\n private func smartCollisionAvoidanceDelay(baseDelay: TimeInterval) -> TimeInterval {\n // Add node-specific jitter to base delay\n let nodeJitter = calculateNodeIDJitter()\n \n // Add small random component to avoid perfect synchronization\n let randomJitter = TimeInterval.random(in: 0...0.005) // 0-5ms additional random\n \n return baseDelay + nodeJitter + randomJitter\n }\n \n // MARK: - Relay Cancellation\n \n private func scheduleRelay(_ packet: BitchatPacket, messageID: String, delay: TimeInterval) {\n pendingRelaysLock.lock()\n defer { pendingRelaysLock.unlock() }\n \n // Cancel any existing relay for this message\n if let existingRelay = pendingRelays[messageID] {\n existingRelay.cancel()\n }\n \n // Apply smart collision avoidance to delay\n let adjustedDelay = smartCollisionAvoidanceDelay(baseDelay: delay)\n \n // Create new relay task\n let relayTask = DispatchWorkItem { [weak self] in\n guard let self = self else { return }\n \n // Remove from pending when executed\n self.pendingRelaysLock.lock()\n self.pendingRelays.removeValue(forKey: messageID)\n self.pendingRelaysLock.unlock()\n \n // Mark this message as relayed\n self.processedMessagesLock.lock()\n if var state = self.processedMessages[messageID] {\n state.relayed = true\n self.processedMessages[messageID] = state\n }\n self.processedMessagesLock.unlock()\n \n // Actually relay the packet\n self.broadcastPacket(packet)\n }\n \n // Store the task\n pendingRelays[messageID] = relayTask\n \n // Schedule it with adjusted delay\n DispatchQueue.global(qos: .default).asyncAfter(deadline: .now() + adjustedDelay, execute: relayTask)\n }\n \n private func cancelPendingRelay(messageID: String) {\n pendingRelaysLock.lock()\n defer { pendingRelaysLock.unlock() }\n \n if let pendingRelay = pendingRelays[messageID] {\n pendingRelay.cancel()\n pendingRelays.removeValue(forKey: messageID)\n // Cancelled pending relay - another node handled it\n }\n }\n \n // MARK: - Memory Management\n \n private func startMemoryCleanupTimer() {\n memoryCleanupTimer?.invalidate()\n memoryCleanupTimer = Timer.scheduledTimer(withTimeInterval: 60.0, repeats: true) { [weak self] _ in\n self?.performMemoryCleanup()\n }\n }\n \n private func performMemoryCleanup() {\n messageQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n let startTime = Date()\n \n // Clean up old fragments\n let fragmentTimeout = Date().addingTimeInterval(-self.fragmentTimeout)\n var expiredFragments = [String]()\n for (fragmentID, metadata) in self.fragmentMetadata {\n if metadata.timestamp < fragmentTimeout {\n expiredFragments.append(fragmentID)\n }\n }\n for fragmentID in expiredFragments {\n self.incomingFragments.removeValue(forKey: fragmentID)\n self.fragmentMetadata.removeValue(forKey: fragmentID)\n }\n \n // Limit pending private messages\n if self.pendingPrivateMessages.count > self.maxPendingPrivateMessages {\n let excess = self.pendingPrivateMessages.count - self.maxPendingPrivateMessages\n let keysToRemove = Array(self.pendingPrivateMessages.keys.prefix(excess))\n for key in keysToRemove {\n self.pendingPrivateMessages.removeValue(forKey: key)\n }\n SecureLogger.log(\"Removed \\(excess) oldest pending private message queues\", \n category: SecureLogger.session, level: .info)\n }\n \n // Limit cached messages sent to peer\n if self.cachedMessagesSentToPeer.count > self.maxCachedMessagesSentToPeer {\n let excess = self.cachedMessagesSentToPeer.count - self.maxCachedMessagesSentToPeer\n let toRemove = self.cachedMessagesSentToPeer.prefix(excess)\n self.cachedMessagesSentToPeer.subtract(toRemove)\n SecureLogger.log(\"Removed \\(excess) oldest cached message tracking entries\", \n category: SecureLogger.session, level: .debug)\n }\n \n // Clean up pending relays\n self.pendingRelaysLock.lock()\n _ = self.pendingRelays.count\n self.pendingRelaysLock.unlock()\n \n // Clean up rate limiters\n self.cleanupRateLimiters()\n \n // Log memory status\n _ = Date().timeIntervalSince(startTime)\n // Memory cleanup completed\n \n // Estimate current memory usage and log if high\n let estimatedMemory = self.estimateMemoryUsage()\n if estimatedMemory > self.maxMemoryUsageBytes {\n SecureLogger.log(\"Warning: Estimated memory usage \\(estimatedMemory / 1024 / 1024)MB exceeds limit\", \n category: SecureLogger.session, level: .warning)\n }\n }\n }\n \n private func estimateMemoryUsage() -> Int {\n // Rough estimates based on typical sizes\n let messageSize = 512 // Average message size\n let fragmentSize = 512 // Average fragment size\n \n var totalBytes = 0\n \n // Processed messages (string storage + MessageState)\n processedMessagesLock.lock()\n totalBytes += processedMessages.count * 150 // messageID strings + MessageState struct\n processedMessagesLock.unlock()\n \n // Fragments\n for (_, fragments) in incomingFragments {\n totalBytes += fragments.count * fragmentSize\n }\n \n // Pending private messages\n for (_, messages) in pendingPrivateMessages {\n totalBytes += messages.count * messageSize\n }\n \n // Other caches\n totalBytes += cachedMessagesSentToPeer.count * 50 // peerID strings\n totalBytes += deliveredMessages.count * 100 // messageID strings\n totalBytes += recentlySentMessages.count * 100 // messageID strings\n \n return totalBytes\n }\n \n // MARK: - Rate Limiting\n \n private func isRateLimited(peerID: String, messageType: UInt8) -> Bool {\n rateLimiterLock.lock()\n defer { rateLimiterLock.unlock() }\n \n let now = Date()\n let cutoff = now.addingTimeInterval(-rateLimitWindow)\n \n // Clean old timestamps from total counter\n totalMessageTimestamps.removeAll { $0 < cutoff }\n \n // Check global rate limit with progressive throttling\n if totalMessageTimestamps.count >= maxTotalMessagesPerMinute {\n // Apply progressive throttling for global limit\n let overageRatio = Double(totalMessageTimestamps.count - maxTotalMessagesPerMinute) / Double(maxTotalMessagesPerMinute)\n let dropProbability = min(0.95, 0.5 + overageRatio * 0.5) // 50% to 95% drop rate\n \n if Double.random(in: 0...1) < dropProbability {\n SecureLogger.log(\"Global rate limit throttling: \\(totalMessageTimestamps.count) messages, drop prob: \\(Int(dropProbability * 100))%\", \n category: SecureLogger.security, level: .warning)\n return true\n }\n }\n \n // Determine which rate limiter to use based on message type\n let isChatMessage = messageType == MessageType.message.rawValue\n \n let limiter = isChatMessage ? messageRateLimiter : protocolMessageRateLimiter\n let maxPerMinute = isChatMessage ? maxChatMessagesPerPeerPerMinute : maxProtocolMessagesPerPeerPerMinute\n \n // Clean old timestamps for this peer\n if var timestamps = limiter[peerID] {\n timestamps.removeAll { $0 < cutoff }\n \n // Update the appropriate limiter\n if isChatMessage {\n messageRateLimiter[peerID] = timestamps\n } else {\n protocolMessageRateLimiter[peerID] = timestamps\n }\n \n // Progressive throttling for per-peer limit\n if timestamps.count >= maxPerMinute {\n // Calculate how much over the limit we are\n let overageRatio = Double(timestamps.count - maxPerMinute) / Double(maxPerMinute)\n \n // Progressive drop probability: starts at 30% when just over limit, increases to 90%\n let dropProbability = min(0.9, 0.3 + overageRatio * 0.6)\n \n if Double.random(in: 0...1) < dropProbability {\n let messageTypeStr = isChatMessage ? \"chat\" : \"protocol\"\n SecureLogger.log(\"Peer \\(peerID) \\(messageTypeStr) rate throttling: \\(timestamps.count) msgs/min, drop prob: \\(Int(dropProbability * 100))%\", \n category: SecureLogger.security, level: .info)\n return true\n } else {\n SecureLogger.log(\"Peer \\(peerID) rate throttling: allowing message (\\(timestamps.count) msgs/min)\", \n category: SecureLogger.security, level: .debug)\n }\n }\n }\n \n return false\n }\n \n private func recordMessage(from peerID: String, messageType: UInt8) {\n rateLimiterLock.lock()\n defer { rateLimiterLock.unlock() }\n \n let now = Date()\n \n // Record in global counter\n totalMessageTimestamps.append(now)\n \n // Determine which rate limiter to use based on message type\n let isChatMessage = messageType == MessageType.message.rawValue\n \n // Record for specific peer in the appropriate limiter\n if isChatMessage {\n if messageRateLimiter[peerID] == nil {\n messageRateLimiter[peerID] = []\n }\n messageRateLimiter[peerID]?.append(now)\n } else {\n if protocolMessageRateLimiter[peerID] == nil {\n protocolMessageRateLimiter[peerID] = []\n }\n protocolMessageRateLimiter[peerID]?.append(now)\n }\n }\n \n private func cleanupRateLimiters() {\n rateLimiterLock.lock()\n defer { rateLimiterLock.unlock() }\n \n let cutoff = Date().addingTimeInterval(-rateLimitWindow)\n \n // Clean global timestamps\n totalMessageTimestamps.removeAll { $0 < cutoff }\n \n // Clean up old identity announce tracking\n processedMessagesLock.lock()\n let identityCutoff = Date().addingTimeInterval(-identityAnnounceDuplicateWindow * 2)\n recentIdentityAnnounces = recentIdentityAnnounces.filter { $0.value > identityCutoff }\n processedMessagesLock.unlock()\n \n // Clean per-peer chat message timestamps\n for (peerID, timestamps) in messageRateLimiter {\n let filtered = timestamps.filter { $0 >= cutoff }\n if filtered.isEmpty {\n messageRateLimiter.removeValue(forKey: peerID)\n } else {\n messageRateLimiter[peerID] = filtered\n }\n }\n \n // Clean per-peer protocol message timestamps\n for (peerID, timestamps) in protocolMessageRateLimiter {\n let filtered = timestamps.filter { $0 >= cutoff }\n if filtered.isEmpty {\n protocolMessageRateLimiter.removeValue(forKey: peerID)\n } else {\n protocolMessageRateLimiter[peerID] = filtered\n }\n }\n \n SecureLogger.log(\"Rate limiter cleanup: tracking \\(messageRateLimiter.count) chat peers, \\(protocolMessageRateLimiter.count) protocol peers, \\(totalMessageTimestamps.count) total messages\", \n category: SecureLogger.session, level: .debug)\n }\n \n // MARK: - Cover Traffic\n \n private func startCoverTraffic() {\n // Start cover traffic with random interval\n scheduleCoverTraffic()\n }\n \n private func scheduleCoverTraffic() {\n // Random interval between 30-120 seconds\n let interval = TimeInterval.random(in: 30...120)\n \n coverTrafficTimer?.invalidate()\n coverTrafficTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { [weak self] _ in\n self?.sendDummyMessage()\n self?.scheduleCoverTraffic() // Schedule next dummy message\n }\n }\n \n private func sendDummyMessage() {\n // Only send dummy messages if we have connected peers with established sessions\n let peersWithSessions = getAllConnectedPeerIDs().filter { peerID in\n return noiseService.hasEstablishedSession(with: peerID)\n }\n \n guard !peersWithSessions.isEmpty else { \n SecureLogger.log(\"Cover traffic: No peers with established sessions, skipping dummy message\", \n category: SecureLogger.security, level: .debug)\n return \n }\n \n // Skip if battery is low\n if currentBatteryLevel < 0.2 {\n SecureLogger.log(\"Cover traffic: Battery low, skipping dummy message\", \n category: SecureLogger.security, level: .debug)\n return\n }\n \n // Pick a random peer with an established session to send to\n guard let randomPeer = peersWithSessions.randomElement() else { return }\n \n // Generate random dummy content\n let dummyContent = generateDummyContent()\n \n SecureLogger.log(\"Cover traffic: Sending dummy message to \\(randomPeer)\", \n category: SecureLogger.security, level: .info)\n \n // Send as a private message so it's encrypted\n let recipientNickname = collectionsQueue.sync {\n return peerNicknames[randomPeer] ?? \"unknown\"\n }\n \n sendPrivateMessage(dummyContent, to: randomPeer, recipientNickname: recipientNickname)\n }\n \n private func generateDummyContent() -> String {\n // Generate realistic-looking dummy messages\n let templates = [\n \"hey\",\n \"ok\",\n \"got it\",\n \"sure\",\n \"sounds good\",\n \"thanks\",\n \"np\",\n \"see you there\",\n \"on my way\",\n \"running late\",\n \"be there soon\",\n \"👍\",\n \"✓\",\n \"meeting at the usual spot\",\n \"confirmed\",\n \"roger that\"\n ]\n \n // Prefix with dummy marker (will be encrypted)\n return coverTrafficPrefix + (templates.randomElement() ?? \"ok\")\n }\n \n \n private func updatePeerLastSeen(_ peerID: String) {\n peerLastSeenTimestamps.set(peerID, value: Date())\n }\n \n private func sendPendingPrivateMessages(to peerID: String) {\n messageQueue.async(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n \n // Get pending messages with proper queue synchronization\n let pendingMessages = self.collectionsQueue.sync {\n return self.pendingPrivateMessages[peerID]\n }\n \n guard let messages = pendingMessages else { return }\n \n SecureLogger.log(\"Sending \\(messages.count) pending private messages to \\(peerID)\", category: SecureLogger.session, level: .info)\n \n // Clear pending messages for this peer\n self.collectionsQueue.sync(flags: .barrier) {\n _ = self.pendingPrivateMessages.removeValue(forKey: peerID)\n }\n \n // Send each pending message\n for (content, recipientNickname, messageID) in messages {\n // Check if this is a read receipt\n if content.hasPrefix(\"READ_RECEIPT:\") {\n // Extract the original message ID\n let originalMessageID = String(content.dropFirst(\"READ_RECEIPT:\".count))\n SecureLogger.log(\"Sending queued read receipt for message \\(originalMessageID) to \\(peerID)\", category: SecureLogger.session, level: .debug)\n \n // Create and send the actual read receipt\n let receipt = ReadReceipt(\n originalMessageID: originalMessageID,\n readerID: self.myPeerID,\n readerNickname: recipientNickname // This is actually the reader's nickname\n )\n \n // Send the read receipt using the normal method\n DispatchQueue.global().async { [weak self] in\n self?.sendReadReceipt(receipt, to: peerID)\n }\n } else {\n // Regular message\n SecureLogger.log(\"Sending pending message \\(messageID) to \\(peerID)\", category: SecureLogger.session, level: .debug)\n // Use async to avoid blocking the queue\n DispatchQueue.global().async { [weak self] in\n self?.sendPrivateMessage(content, to: peerID, recipientNickname: recipientNickname, messageID: messageID)\n }\n }\n }\n }\n }\n \n // MARK: - Noise Protocol Support\n \n private func attemptHandshakeIfNeeded(with peerID: String, forceIfStale: Bool = false) {\n // Check if we already have an established session\n if noiseService.hasEstablishedSession(with: peerID) {\n SecureLogger.log(\"Already have established session with \\(peerID), skipping handshake\", \n category: SecureLogger.handshake, level: .debug)\n return\n }\n \n // Check if we should initiate using the handshake coordinator\n if !handshakeCoordinator.shouldInitiateHandshake(\n myPeerID: myPeerID, \n remotePeerID: peerID,\n forceIfStale: forceIfStale\n ) {\n SecureLogger.log(\"Should not initiate handshake with \\(peerID) at this time\", \n category: SecureLogger.handshake, level: .debug)\n return\n }\n \n // Initiate the handshake\n initiateNoiseHandshake(with: peerID)\n }\n \n // Send keep-alive pings to all connected peers to prevent iOS BLE timeouts\n private func sendKeepAlivePings() {\n let connectedPeers = collectionsQueue.sync {\n return Array(activePeers).filter { peerID in\n // Only send keepalive to authenticated peers that still exist\n // Check if this peer ID is still current (not rotated)\n guard let fingerprint = peerIDToFingerprint[peerID],\n let currentPeerID = fingerprintToPeerID[fingerprint],\n currentPeerID == peerID else {\n // This peer ID has rotated, skip it\n SecureLogger.log(\"Skipping keepalive for rotated peer ID: \\(peerID)\", \n category: SecureLogger.session, level: .debug)\n return false\n }\n \n // Check if we actually have a Noise session with this peer\n guard noiseService.hasEstablishedSession(with: peerID) else {\n SecureLogger.log(\"Skipping keepalive for \\(peerID) - no established session\", \n category: SecureLogger.session, level: .debug)\n return false\n }\n \n return peerConnectionStates[peerID] == .authenticated\n }\n }\n \n SecureLogger.log(\"Keep-alive timer: checking \\(connectedPeers.count) peers for pings\", \n category: SecureLogger.session, level: .debug)\n \n for peerID in connectedPeers {\n // Don't spam if we recently heard from them\n if let lastHeard = lastHeardFromPeer[peerID], \n Date().timeIntervalSince(lastHeard) < keepAliveInterval / 2 {\n SecureLogger.log(\"Skipping keepalive for \\(peerID) - heard recently\", \n category: SecureLogger.session, level: .debug)\n continue // Skip if we heard from them in the last 10 seconds\n }\n \n SecureLogger.log(\"Sending keepalive ping to \\(peerID)\", \n category: SecureLogger.session, level: .debug)\n validateNoiseSession(with: peerID)\n }\n }\n \n // Validate an existing Noise session by sending an encrypted ping\n private func validateNoiseSession(with peerID: String) {\n let encryptionQueue = getEncryptionQueue(for: peerID)\n \n encryptionQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Create a ping packet with minimal data\n let pingData = \"ping:\\(Date().timeIntervalSince1970)\".data(using: .utf8)!\n \n do {\n // Try to encrypt a small ping message\n let encrypted = try self.noiseService.encrypt(pingData, for: peerID)\n \n // Create a validation packet (won't be displayed to user)\n let packet = BitchatPacket(\n type: MessageType.systemValidation.rawValue,\n senderID: Data(hexString: self.myPeerID) ?? Data(),\n recipientID: Data(hexString: peerID),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: encrypted,\n signature: nil,\n ttl: 1 )\n \n // System validation should go directly to the peer when possible\n if !self.sendDirectToRecipient(packet, recipientPeerID: peerID) {\n // Fall back to selective relay if direct delivery fails\n self.sendViaSelectiveRelay(packet, recipientPeerID: peerID)\n }\n \n SecureLogger.log(\"Sent session validation ping to \\(peerID)\", \n category: SecureLogger.session, level: .debug)\n } catch {\n // Encryption failed - session is invalid\n SecureLogger.log(\"Session validation failed for \\(peerID): \\(error)\", \n category: SecureLogger.session, level: .warning)\n \n // Clear the invalid session\n self.cleanupPeerCryptoState(peerID)\n \n // Initiate fresh handshake\n DispatchQueue.main.async { [weak self] in\n self?.attemptHandshakeIfNeeded(with: peerID, forceIfStale: true)\n }\n }\n }\n }\n \n private func initiateNoiseHandshake(with peerID: String) {\n // Use noiseService directly\n \n SecureLogger.log(\"Initiating Noise handshake with \\(peerID)\", category: SecureLogger.noise, level: .info)\n \n // Check if we already have an established session\n if noiseService.hasEstablishedSession(with: peerID) {\n SecureLogger.log(\"Already have established session with \\(peerID)\", category: SecureLogger.noise, level: .debug)\n // Clear any lingering handshake attempt time\n handshakeAttemptTimes.removeValue(forKey: peerID)\n handshakeCoordinator.recordHandshakeSuccess(peerID: peerID)\n \n // Update session state to established\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[peerID] = .established\n }\n \n // Update connection state to authenticated\n updatePeerConnectionState(peerID, state: .authenticated)\n \n // Force UI update since we have an existing session\n DispatchQueue.main.async { [weak self] in\n (self?.delegate as? ChatViewModel)?.updateEncryptionStatusForPeers()\n }\n \n return\n }\n \n // Update state to handshaking\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[peerID] = .handshaking\n }\n \n // Check if we have pending messages\n let hasPendingMessages = collectionsQueue.sync {\n return pendingPrivateMessages[peerID]?.isEmpty == false\n }\n \n // Check with coordinator if we should initiate\n if !handshakeCoordinator.shouldInitiateHandshake(myPeerID: myPeerID, remotePeerID: peerID, forceIfStale: hasPendingMessages) {\n SecureLogger.log(\"Coordinator says we should not initiate handshake with \\(peerID)\", category: SecureLogger.handshake, level: .debug)\n \n if hasPendingMessages {\n // Check if peer is still connected before retrying\n let connectionState = collectionsQueue.sync { peerConnectionStates[peerID] ?? .disconnected }\n \n if connectionState == .disconnected {\n // Peer is disconnected - clear pending messages and stop retrying\n SecureLogger.log(\"Peer \\(peerID) is disconnected, clearing pending messages\", category: SecureLogger.handshake, level: .info)\n collectionsQueue.async(flags: .barrier) { [weak self] in\n self?.pendingPrivateMessages[peerID]?.removeAll()\n }\n handshakeCoordinator.resetHandshakeState(for: peerID)\n } else {\n // Peer is still connected but handshake is stuck\n // Send identity announce to prompt them to initiate if they have lower ID\n SecureLogger.log(\"Handshake stuck with connected peer \\(peerID), sending identity announce\", category: SecureLogger.handshake, level: .info)\n sendNoiseIdentityAnnounce(to: peerID)\n \n // Only retry if we haven't retried too many times\n let retryCount = handshakeCoordinator.getRetryCount(for: peerID)\n if retryCount < 3 {\n handshakeCoordinator.incrementRetryCount(for: peerID)\n DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { [weak self] in\n self?.initiateNoiseHandshake(with: peerID)\n }\n } else {\n SecureLogger.log(\"Max retries reached for \\(peerID), clearing pending messages\", category: SecureLogger.handshake, level: .warning)\n collectionsQueue.async(flags: .barrier) { [weak self] in\n self?.pendingPrivateMessages[peerID]?.removeAll()\n }\n handshakeCoordinator.resetHandshakeState(for: peerID)\n }\n }\n }\n return\n }\n \n // Check if there's a retry delay\n if let retryDelay = handshakeCoordinator.getRetryDelay(for: peerID), retryDelay > 0 {\n SecureLogger.log(\"Waiting \\(retryDelay)s before retrying handshake with \\(peerID)\", category: SecureLogger.handshake, level: .debug)\n DispatchQueue.main.asyncAfter(deadline: .now() + retryDelay) { [weak self] in\n self?.initiateNoiseHandshake(with: peerID)\n }\n return\n }\n \n // Record that we're initiating\n handshakeCoordinator.recordHandshakeInitiation(peerID: peerID)\n handshakeAttemptTimes[peerID] = Date()\n \n // Update connection state to authenticating\n updatePeerConnectionState(peerID, state: .authenticating)\n \n do {\n // Generate handshake initiation message\n let handshakeData = try noiseService.initiateHandshake(with: peerID)\n SecureLogger.logHandshake(\"initiated\", peerID: peerID, success: true)\n \n // Send handshake initiation\n let packet = BitchatPacket(\n type: MessageType.noiseHandshakeInit.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: peerID) ?? Data(), // Add recipient ID for targeted delivery\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: handshakeData,\n signature: nil,\n ttl: 6 // Increased TTL for better delivery on startup\n )\n \n // Track packet for ACK\n trackPacketForAck(packet)\n \n // Try direct delivery first for handshake init\n if !sendDirectToRecipient(packet, recipientPeerID: peerID) {\n // Handshakes are critical - use broadcast as fallback to ensure delivery\n SecureLogger.log(\"Recipient \\(peerID) not directly connected for handshake init, using broadcast\", \n category: SecureLogger.session, level: .info)\n broadcastPacket(packet)\n }\n \n // Schedule a retry check after 5 seconds\n DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) { [weak self] in\n guard let self = self else { return }\n // Check if handshake completed\n if !self.noiseService.hasEstablishedSession(with: peerID) {\n let state = self.handshakeCoordinator.getHandshakeState(for: peerID)\n if case .initiating = state {\n SecureLogger.log(\"Handshake with \\(peerID) not completed after 5s, will retry\", category: SecureLogger.handshake, level: .warning)\n // The handshake coordinator will handle retry logic\n }\n }\n }\n \n } catch NoiseSessionError.alreadyEstablished {\n // Session already established, no need to handshake\n handshakeCoordinator.recordHandshakeSuccess(peerID: peerID)\n } catch {\n // Failed to initiate handshake\n handshakeCoordinator.recordHandshakeFailure(peerID: peerID, reason: error.localizedDescription)\n SecureLogger.logSecurityEvent(.handshakeFailed(peerID: peerID, error: error.localizedDescription))\n }\n }\n \n private func handleNoiseHandshakeMessage(from peerID: String, message: Data, isInitiation: Bool) {\n // Use noiseService directly\n SecureLogger.logHandshake(\"processing \\(isInitiation ? \"init\" : \"response\")\", peerID: peerID, success: true)\n \n // Get current handshake state before processing\n let currentState = handshakeCoordinator.getHandshakeState(for: peerID)\n let hasEstablishedSession = noiseService.hasEstablishedSession(with: peerID)\n SecureLogger.log(\"Current handshake state for \\(peerID): \\(currentState), hasEstablishedSession: \\(hasEstablishedSession)\", category: SecureLogger.noise, level: .info)\n \n // Check for duplicate handshake messages\n if handshakeCoordinator.isDuplicateHandshakeMessage(message) {\n SecureLogger.log(\"Duplicate handshake message from \\(peerID), ignoring\", category: SecureLogger.handshake, level: .debug)\n return\n }\n \n // If this is an initiation, check if we should accept it\n if isInitiation {\n if !handshakeCoordinator.shouldAcceptHandshakeInitiation(myPeerID: myPeerID, remotePeerID: peerID) {\n SecureLogger.log(\"Coordinator says we should not accept handshake from \\(peerID)\", category: SecureLogger.handshake, level: .debug)\n return\n }\n // Record that we're responding\n handshakeCoordinator.recordHandshakeResponse(peerID: peerID)\n \n // Update connection state to authenticating\n updatePeerConnectionState(peerID, state: .authenticating)\n }\n \n do {\n // Process handshake message\n if let response = try noiseService.processHandshakeMessage(from: peerID, message: message) {\n // Handshake response ready to send\n \n // Always send responses as handshake response type\n let packet = BitchatPacket(\n type: MessageType.noiseHandshakeResp.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: peerID) ?? Data(), // Add recipient ID for targeted delivery\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: response,\n signature: nil,\n ttl: 6 // Increased TTL for better delivery on startup\n )\n \n // Track packet for ACK\n trackPacketForAck(packet)\n \n // Try direct delivery first for handshake response\n if !sendDirectToRecipient(packet, recipientPeerID: peerID) {\n // Handshakes are critical - use broadcast as fallback to ensure delivery\n SecureLogger.log(\"Recipient \\(peerID) not directly connected for handshake response, using broadcast\", \n category: SecureLogger.session, level: .info)\n broadcastPacket(packet)\n }\n } else {\n SecureLogger.log(\"No response needed from processHandshakeMessage (isInitiation: \\(isInitiation))\", category: SecureLogger.noise, level: .debug)\n }\n \n // Check if handshake is complete\n let sessionEstablished = noiseService.hasEstablishedSession(with: peerID)\n _ = handshakeCoordinator.getHandshakeState(for: peerID)\n // Handshake state updated\n \n if sessionEstablished {\n SecureLogger.logSecurityEvent(.handshakeCompleted(peerID: peerID))\n // Unlock rotation now that handshake is complete\n unlockRotation()\n \n // Session established successfully\n handshakeCoordinator.recordHandshakeSuccess(peerID: peerID)\n \n // Update session state to established\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[peerID] = .established\n }\n \n // Update connection state to authenticated\n updatePeerConnectionState(peerID, state: .authenticated)\n \n // Clear handshake attempt time on success\n handshakeAttemptTimes.removeValue(forKey: peerID)\n \n // Initialize last successful message time\n lastSuccessfulMessageTime[peerID] = Date()\n SecureLogger.log(\"Initialized lastSuccessfulMessageTime for \\(peerID)\", category: SecureLogger.noise, level: .debug)\n \n // Send identity announcement to this specific peer\n sendNoiseIdentityAnnounce(to: peerID)\n \n // Also broadcast to ensure all peers get it\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n self?.sendNoiseIdentityAnnounce()\n }\n \n // Send regular announce packet after handshake to trigger connect message\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [weak self] in\n self?.sendAnnouncementToPeer(peerID)\n }\n \n // Send any pending private messages\n self.sendPendingPrivateMessages(to: peerID)\n \n // Send any cached store-and-forward messages\n sendCachedMessages(to: peerID)\n }\n } catch NoiseSessionError.alreadyEstablished {\n // Session already established, ignore handshake\n SecureLogger.log(\"Handshake already established with \\(peerID)\", category: SecureLogger.noise, level: .info)\n handshakeCoordinator.recordHandshakeSuccess(peerID: peerID)\n \n // Update session state to established\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[peerID] = .established\n }\n } catch {\n // Handshake failed\n handshakeCoordinator.recordHandshakeFailure(peerID: peerID, reason: error.localizedDescription)\n SecureLogger.logSecurityEvent(.handshakeFailed(peerID: peerID, error: error.localizedDescription))\n SecureLogger.log(\"Handshake failed with \\(peerID): \\(error)\", category: SecureLogger.noise, level: .error)\n \n // Update session state to failed\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[peerID] = .failed(error)\n }\n \n // If handshake failed due to authentication error, clear the session to allow retry\n if case NoiseError.authenticationFailure = error {\n SecureLogger.log(\"Handshake failed with \\(peerID): authenticationFailure - clearing session\", category: SecureLogger.noise, level: .warning)\n cleanupPeerCryptoState(peerID)\n }\n }\n }\n \n private func handleNoiseEncryptedMessage(from peerID: String, encryptedData: Data, originalPacket: BitchatPacket, peripheral: CBPeripheral? = nil) {\n // Use noiseService directly\n \n // For Noise encrypted messages, we need to decrypt first to check the inner packet\n // The outer packet's recipientID might be for routing, not the final recipient\n \n // Create unique identifier for this encrypted message\n let messageHash = encryptedData.prefix(32).hexEncodedString() // Use first 32 bytes as identifier\n let messageKey = \"\\(peerID)-\\(messageHash)\"\n \n // Check if we've already processed this exact encrypted message\n let alreadyProcessed = collectionsQueue.sync(flags: .barrier) {\n if processedNoiseMessages.contains(messageKey) {\n return true\n }\n processedNoiseMessages.insert(messageKey)\n return false\n }\n \n if alreadyProcessed {\n return\n }\n \n do {\n // Decrypt the message\n // Attempting to decrypt\n let decryptedData = try noiseService.decrypt(encryptedData, from: peerID)\n // Successfully decrypted message\n \n // Update last successful message time\n lastSuccessfulMessageTime[peerID] = Date()\n \n // Send protocol ACK after successful decryption (only once per encrypted packet)\n sendProtocolAck(for: originalPacket, to: peerID)\n \n // If we can decrypt messages from this peer, they should be in activePeers\n let wasAdded = collectionsQueue.sync(flags: .barrier) {\n if !self.activePeers.contains(peerID) {\n SecureLogger.log(\"Adding \\(peerID) to activePeers after successful decryption\", category: SecureLogger.noise, level: .info)\n return self.activePeers.insert(peerID).inserted\n }\n return false\n }\n \n if wasAdded {\n // Notify about peer list update\n self.notifyPeerListUpdate()\n }\n \n // Check if this is a special format message (type marker + payload)\n if decryptedData.count > 1 {\n let typeMarker = decryptedData[0]\n \n // Check if this is a delivery ACK with the new format\n if typeMarker == MessageType.deliveryAck.rawValue {\n // Extract the ACK JSON data (skip the type marker)\n let ackData = decryptedData.dropFirst()\n \n // Decode the delivery ACK - try binary first, then JSON\n if let ack = DeliveryAck.fromBinaryData(ackData) {\n SecureLogger.log(\"Received binary delivery ACK via Noise: \\(ack.originalMessageID) from \\(ack.recipientNickname)\", category: SecureLogger.session, level: .debug)\n \n // Process the ACK\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n return\n } else if let ack = DeliveryAck.decode(from: ackData) {\n SecureLogger.log(\"Received JSON delivery ACK via Noise: \\(ack.originalMessageID) from \\(ack.recipientNickname)\", category: SecureLogger.session, level: .debug)\n \n // Process the ACK\n DeliveryTracker.shared.processDeliveryAck(ack)\n \n // Notify delegate\n DispatchQueue.main.async {\n self.delegate?.didReceiveDeliveryAck(ack)\n }\n return\n } else {\n SecureLogger.log(\"Failed to decode delivery ACK via Noise - data size: \\(ackData.count)\", category: SecureLogger.session, level: .warning)\n }\n }\n \n // Check if this is a read receipt with the new format\n else if typeMarker == MessageType.readReceipt.rawValue {\n // Extract the receipt binary data (skip the type marker)\n let receiptData = decryptedData.dropFirst()\n \n // Decode the read receipt from binary\n if let receipt = ReadReceipt.fromBinaryData(receiptData) {\n SecureLogger.log(\"Received binary read receipt via Noise: \\(receipt.originalMessageID) from \\(receipt.readerNickname)\", category: SecureLogger.session, level: .debug)\n \n // Process the read receipt\n DispatchQueue.main.async {\n self.delegate?.didReceiveReadReceipt(receipt)\n }\n return\n } else {\n SecureLogger.log(\"Failed to decode read receipt via Noise - data size: \\(receiptData.count)\", category: SecureLogger.session, level: .warning)\n }\n }\n }\n \n // Try to parse as a full inner packet (for backward compatibility and other message types)\n if let innerPacket = BitchatPacket.from(decryptedData) {\n SecureLogger.log(\"Successfully parsed inner packet - type: \\(MessageType(rawValue: innerPacket.type)?.description ?? \"unknown\"), from: \\(innerPacket.senderID.hexEncodedString()), to: \\(innerPacket.recipientID?.hexEncodedString() ?? \"broadcast\")\", category: SecureLogger.session, level: .debug)\n \n // Process the decrypted inner packet\n // The packet will be handled according to its recipient ID\n // If it's for us, it won't be relayed\n // Pass the peripheral context for proper ACK routing\n handleReceivedPacket(innerPacket, from: peerID, peripheral: peripheral)\n } else {\n SecureLogger.log(\"Failed to parse inner packet from decrypted data\", category: SecureLogger.encryption, level: .warning)\n }\n } catch {\n // Failed to decrypt - might need to re-establish session\n SecureLogger.log(\"Failed to decrypt Noise message from \\(peerID): \\(error)\", category: SecureLogger.encryption, level: .error)\n if !noiseService.hasEstablishedSession(with: peerID) {\n SecureLogger.log(\"No Noise session with \\(peerID), attempting handshake\", category: SecureLogger.noise, level: .info)\n attemptHandshakeIfNeeded(with: peerID, forceIfStale: true)\n } else {\n SecureLogger.log(\"Have session with \\(peerID) but decryption failed\", category: SecureLogger.encryption, level: .warning)\n \n // Send a NACK to inform peer that decryption failed\n sendProtocolNack(for: originalPacket, to: peerID,\n reason: \"Decryption failed\",\n errorCode: .decryptionFailed)\n \n // The NACK handler will take care of clearing sessions and re-establishing\n // Don't initiate anything here to avoid race conditions\n \n // Update UI to show encryption is broken\n DispatchQueue.main.async { [weak self] in\n if let chatVM = self?.delegate as? ChatViewModel {\n chatVM.updateEncryptionStatusForPeer(peerID)\n }\n }\n }\n }\n }\n \n \n // MARK: - Protocol Version Negotiation\n \n private func handleVersionHello(from peerID: String, data: Data, peripheral: CBPeripheral? = nil) {\n // Create a copy to avoid potential race conditions\n let dataCopy = Data(data)\n \n // Safety check for empty data\n guard !dataCopy.isEmpty else {\n SecureLogger.log(\"Received empty version hello data from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n // Check if this peer is reconnecting after disconnect\n if let lastConnected = lastConnectionTime[peerID] {\n let timeSinceLastConnection = Date().timeIntervalSince(lastConnected)\n // Only clear truly stale sessions, not on every reconnect\n if timeSinceLastConnection > 86400.0 { // More than 24 hours since last connection\n // Clear any stale Noise session\n if noiseService.hasEstablishedSession(with: peerID) {\n SecureLogger.log(\"Peer \\(peerID) reconnecting after \\(Int(timeSinceLastConnection))s - clearing stale session\", category: SecureLogger.noise, level: .info)\n cleanupPeerCryptoState(peerID)\n }\n } else if timeSinceLastConnection > 5.0 {\n // Just log the reconnection, don't clear the session\n SecureLogger.log(\"Peer \\(peerID) reconnecting after \\(Int(timeSinceLastConnection))s - keeping existing session\", category: SecureLogger.noise, level: .info)\n }\n }\n \n // Update last connection time\n lastConnectionTime[peerID] = Date()\n \n // Check if we've already negotiated version with this peer\n if let existingVersion = negotiatedVersions[peerID] {\n SecureLogger.log(\"Already negotiated version \\(existingVersion) with \\(peerID), skipping re-negotiation\", \n category: SecureLogger.session, level: .debug)\n // If we have a session, validate it\n if noiseService.hasEstablishedSession(with: peerID) {\n validateNoiseSession(with: peerID)\n }\n return\n }\n \n // Try JSON first if it looks like JSON\n let hello: VersionHello?\n if let firstByte = dataCopy.first, firstByte == 0x7B { // '{' character\n SecureLogger.log(\"Version hello from \\(peerID) appears to be JSON (size: \\(dataCopy.count))\", category: SecureLogger.session, level: .debug)\n hello = VersionHello.decode(from: dataCopy) ?? VersionHello.fromBinaryData(dataCopy)\n } else {\n SecureLogger.log(\"Version hello from \\(peerID) appears to be binary (size: \\(dataCopy.count), first byte: \\(dataCopy.first?.description ?? \"nil\"))\", category: SecureLogger.session, level: .debug)\n hello = VersionHello.fromBinaryData(dataCopy) ?? VersionHello.decode(from: dataCopy)\n }\n \n guard let hello = hello else {\n SecureLogger.log(\"Failed to decode version hello from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n SecureLogger.log(\"Received version hello from \\(peerID): supported versions \\(hello.supportedVersions), preferred \\(hello.preferredVersion)\", \n category: SecureLogger.session, level: .debug)\n \n // Find the best common version\n let ourVersions = Array(ProtocolVersion.supportedVersions)\n if let agreedVersion = ProtocolVersion.negotiateVersion(clientVersions: hello.supportedVersions, serverVersions: ourVersions) {\n // We can communicate! Send ACK\n SecureLogger.log(\"Version negotiation agreed with \\(peerID): v\\(agreedVersion) (client: \\(hello.clientVersion), platform: \\(hello.platform))\", category: SecureLogger.session, level: .info)\n negotiatedVersions[peerID] = agreedVersion\n versionNegotiationState[peerID] = .ackReceived(version: agreedVersion)\n \n let ack = VersionAck(\n agreedVersion: agreedVersion,\n serverVersion: Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String ?? \"1.0\",\n platform: getPlatformString()\n )\n \n sendVersionAck(ack, to: peerID)\n \n // Lazy handshake: No longer initiate handshake after version negotiation\n // Just announce our identity\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in\n guard let self = self else { return }\n \n // Just announce our identity\n self.sendNoiseIdentityAnnounce()\n \n SecureLogger.log(\"Version negotiation complete with \\(peerID) - lazy handshake mode\", \n category: SecureLogger.handshake, level: .info)\n }\n } else {\n // No compatible version\n SecureLogger.log(\"Version negotiation failed with \\(peerID): No compatible version (client supports: \\(hello.supportedVersions))\", category: SecureLogger.session, level: .warning)\n versionNegotiationState[peerID] = .failed(reason: \"No compatible protocol version\")\n \n let ack = VersionAck(\n agreedVersion: 0,\n serverVersion: Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String ?? \"1.0\",\n platform: getPlatformString(),\n rejected: true,\n reason: \"No compatible protocol version. Client supports: \\(hello.supportedVersions), server supports: \\(ourVersions)\"\n )\n \n sendVersionAck(ack, to: peerID)\n \n // Disconnect after a short delay\n if let peripheral = peripheral {\n DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in\n self?.centralManager?.cancelPeripheralConnection(peripheral)\n }\n }\n }\n }\n \n private func handleVersionAck(from peerID: String, data: Data) {\n // Create a copy to avoid potential race conditions\n let dataCopy = Data(data)\n \n // Safety check for empty data\n guard !dataCopy.isEmpty else {\n SecureLogger.log(\"Received empty version ack data from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n // Try JSON first if it looks like JSON\n let ack: VersionAck?\n if let firstByte = dataCopy.first, firstByte == 0x7B { // '{' character\n ack = VersionAck.decode(from: dataCopy) ?? VersionAck.fromBinaryData(dataCopy)\n } else {\n ack = VersionAck.fromBinaryData(dataCopy) ?? VersionAck.decode(from: dataCopy)\n }\n \n guard let ack = ack else {\n SecureLogger.log(\"Failed to decode version ack from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n if ack.rejected {\n SecureLogger.log(\"Version negotiation rejected by \\(peerID): \\(ack.reason ?? \"Unknown reason\")\", \n category: SecureLogger.session, level: .error)\n versionNegotiationState[peerID] = .failed(reason: ack.reason ?? \"Version rejected\")\n \n // Clean up state for incompatible peer\n collectionsQueue.sync(flags: .barrier) {\n _ = self.activePeers.remove(peerID)\n _ = self.peerNicknames.removeValue(forKey: peerID)\n _ = self.lastHeardFromPeer.removeValue(forKey: peerID)\n }\n announcedPeers.remove(peerID)\n \n // Clean up any Noise session\n cleanupPeerCryptoState(peerID)\n \n // Notify delegate about incompatible peer disconnection\n DispatchQueue.main.async { [weak self] in\n self?.delegate?.didDisconnectFromPeer(peerID)\n }\n } else {\n // Version negotiation successful\n negotiatedVersions[peerID] = ack.agreedVersion\n versionNegotiationState[peerID] = .ackReceived(version: ack.agreedVersion)\n \n // If we were the initiator (sent hello first), proceed with Noise handshake\n // Note: Since we're handling their ACK, they initiated, so we should not initiate again\n // The peer who sent hello will initiate the Noise handshake\n }\n }\n \n private func sendVersionHello(to peripheral: CBPeripheral? = nil) {\n let hello = VersionHello(\n clientVersion: Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String ?? \"1.0\",\n platform: getPlatformString()\n )\n \n let helloData = hello.toBinaryData()\n \n let packet = BitchatPacket(\n type: MessageType.versionHello.rawValue,\n ttl: 1, // Version negotiation is direct, no relay\n senderID: myPeerID,\n payload: helloData )\n \n // Mark that we initiated version negotiation\n // We don't know the peer ID yet from peripheral, so we'll track it when we get the response\n \n if let peripheral = peripheral,\n let characteristic = peripheralCharacteristics[peripheral] {\n // Send directly to specific peripheral\n if let data = packet.toBinaryData() {\n writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: nil)\n }\n } else {\n // Broadcast to all\n broadcastPacket(packet)\n }\n }\n \n private func sendVersionAck(_ ack: VersionAck, to peerID: String) {\n let ackData = ack.toBinaryData()\n \n let packet = BitchatPacket(\n type: MessageType.versionAck.rawValue,\n senderID: Data(myPeerID.utf8),\n recipientID: Data(peerID.utf8),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: ackData,\n signature: nil,\n ttl: 1 // Direct response, no relay\n )\n \n // Version ACKs should go directly to the peer when possible\n if !sendDirectToRecipient(packet, recipientPeerID: peerID) {\n // Fall back to selective relay if direct delivery fails\n sendViaSelectiveRelay(packet, recipientPeerID: peerID)\n }\n }\n \n private func getPlatformString() -> String {\n #if os(iOS)\n return \"iOS\"\n #elseif os(macOS)\n return \"macOS\"\n #else\n return \"Unknown\"\n #endif\n }\n \n // MARK: - Protocol ACK/NACK Handling\n \n private func handleProtocolAck(from peerID: String, data: Data) {\n guard let ack = ProtocolAck.fromBinaryData(data) else {\n SecureLogger.log(\"Failed to decode protocol ACK from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n SecureLogger.log(\"Received protocol ACK from \\(peerID) for packet \\(ack.originalPacketID), type: \\(ack.packetType), ackID: \\(ack.ackID)\", \n category: SecureLogger.session, level: .debug)\n \n // Remove from pending ACKs and mark as acknowledged\n // Note: readUUID returns uppercase, but we track with lowercase\n let normalizedPacketID = ack.originalPacketID.lowercased()\n _ = collectionsQueue.sync(flags: .barrier) {\n pendingAcks.removeValue(forKey: normalizedPacketID)\n }\n \n // Track this packet as acknowledged to prevent future retries\n acknowledgedPacketsLock.lock()\n acknowledgedPackets.insert(ack.originalPacketID)\n // Keep only recent acknowledged packets (last 1000)\n if acknowledgedPackets.count > 1000 {\n // Remove oldest entries (this is approximate since Set doesn't maintain order)\n acknowledgedPackets = Set(Array(acknowledgedPackets).suffix(1000))\n }\n acknowledgedPacketsLock.unlock()\n \n // Handle specific packet types that need ACK confirmation\n if let messageType = MessageType(rawValue: ack.packetType) {\n switch messageType {\n case .noiseHandshakeInit, .noiseHandshakeResp:\n SecureLogger.log(\"Handshake confirmed by \\(peerID)\", category: SecureLogger.handshake, level: .info)\n case .noiseEncrypted:\n // Encrypted message confirmed\n break\n default:\n break\n }\n }\n }\n \n private func handleProtocolNack(from peerID: String, data: Data) {\n guard let nack = ProtocolNack.fromBinaryData(data) else {\n SecureLogger.log(\"Failed to decode protocol NACK from \\(peerID)\", category: SecureLogger.session, level: .error)\n return\n }\n \n SecureLogger.log(\"Received protocol NACK from \\(peerID) for packet \\(nack.originalPacketID): \\(nack.reason)\", \n category: SecureLogger.session, level: .warning)\n \n // Remove from pending ACKs\n _ = collectionsQueue.sync(flags: .barrier) {\n pendingAcks.removeValue(forKey: nack.originalPacketID)\n }\n \n // Handle specific error codes\n if let errorCode = ProtocolNack.ErrorCode(rawValue: nack.errorCode) {\n switch errorCode {\n case .decryptionFailed:\n // Session is out of sync - both sides need to clear and re-establish\n SecureLogger.log(\"Decryption failed at \\(peerID), clearing session and re-establishing\", \n category: SecureLogger.encryption, level: .warning)\n \n // Clear our session state and handshake coordinator state\n cleanupPeerCryptoState(peerID)\n handshakeCoordinator.resetHandshakeState(for: peerID)\n \n // Update connection state\n updatePeerConnectionState(peerID, state: .connected)\n \n // Use deterministic role assignment to prevent race conditions\n let shouldInitiate = handshakeCoordinator.determineHandshakeRole(\n myPeerID: myPeerID,\n remotePeerID: peerID\n ) == .initiator\n \n if shouldInitiate {\n // Small delay to ensure both sides have cleared state\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n guard let self = self else { return }\n SecureLogger.log(\"Initiating handshake after decryption failure with \\(peerID)\", \n category: SecureLogger.session, level: .info)\n self.attemptHandshakeIfNeeded(with: peerID, forceIfStale: true)\n }\n } else {\n // Send identity announcement to signal we're ready\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n guard let self = self else { return }\n SecureLogger.log(\"Sending identity announcement after decryption failure to \\(peerID)\", \n category: SecureLogger.session, level: .info)\n self.sendNoiseIdentityAnnounce(to: peerID)\n }\n }\n case .sessionExpired:\n // Clear session and re-handshake\n SecureLogger.log(\"Session expired at \\(peerID), clearing and re-handshaking\", \n category: SecureLogger.session, level: .warning)\n cleanupPeerCryptoState(peerID)\n handshakeCoordinator.resetHandshakeState(for: peerID)\n attemptHandshakeIfNeeded(with: peerID, forceIfStale: true)\n default:\n break\n }\n }\n }\n \n private func handleHandshakeRequest(from peerID: String, data: Data) {\n guard let request = HandshakeRequest.fromBinaryData(data) else {\n SecureLogger.log(\"Failed to decode handshake request from \\(peerID)\", category: SecureLogger.noise, level: .error)\n return\n }\n \n // Verify this request is for us\n guard request.targetID == myPeerID else {\n // This request is not for us, might need to relay\n return\n }\n \n SecureLogger.log(\"Received handshake request from \\(request.requesterID) (\\(request.requesterNickname)) with \\(request.pendingMessageCount) pending messages\", \n category: SecureLogger.noise, level: .info)\n \n // Don't show handshake request notification in UI\n // User requested to remove this notification\n /*\n DispatchQueue.main.async { [weak self] in\n if let chatVM = self?.delegate as? ChatViewModel {\n // Notify the UI that someone wants to send messages\n chatVM.handleHandshakeRequest(from: request.requesterID, \n nickname: request.requesterNickname,\n pendingCount: request.pendingMessageCount)\n }\n }\n */\n \n // Check if we already have a session\n if noiseService.hasEstablishedSession(with: peerID) {\n // We already have a session, no action needed\n SecureLogger.log(\"Already have session with \\(peerID), ignoring handshake request\", category: SecureLogger.noise, level: .debug)\n return\n }\n \n // Apply tie-breaker logic for handshake initiation\n if myPeerID < peerID {\n // We have lower ID, initiate handshake\n SecureLogger.log(\"Initiating handshake with \\(peerID) in response to handshake request\", category: SecureLogger.noise, level: .info)\n initiateNoiseHandshake(with: peerID)\n } else {\n // We have higher ID, send identity announce to prompt them\n SecureLogger.log(\"Sending identity announce to \\(peerID) in response to handshake request\", category: SecureLogger.noise, level: .info)\n sendNoiseIdentityAnnounce(to: peerID)\n }\n }\n \n // Send protocol ACK for important packets\n private func sendProtocolAck(for packet: BitchatPacket, to peerID: String, hopCount: UInt8 = 0) {\n // Generate packet ID from packet content hash\n let packetID = generatePacketID(for: packet)\n \n // Debug: log packet details\n _ = packet.senderID.prefix(4).hexEncodedString()\n _ = packet.recipientID?.prefix(4).hexEncodedString() ?? \"nil\"\n // Send protocol ACK\n \n let ack = ProtocolAck(\n originalPacketID: packetID,\n senderID: packet.senderID.hexEncodedString(),\n receiverID: myPeerID,\n packetType: packet.type,\n hopCount: hopCount\n )\n \n let ackPacket = BitchatPacket(\n type: MessageType.protocolAck.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: peerID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: ack.toBinaryData(),\n signature: nil,\n ttl: 3 // ACKs don't need to travel far\n )\n \n // Protocol ACKs should go directly to the sender when possible\n if !sendDirectToRecipient(ackPacket, recipientPeerID: peerID) {\n // Fall back to selective relay if direct delivery fails\n sendViaSelectiveRelay(ackPacket, recipientPeerID: peerID)\n }\n }\n \n // Send protocol NACK for failed packets\n private func sendProtocolNack(for packet: BitchatPacket, to peerID: String, reason: String, errorCode: ProtocolNack.ErrorCode) {\n let packetID = generatePacketID(for: packet)\n \n let nack = ProtocolNack(\n originalPacketID: packetID,\n senderID: packet.senderID.hexEncodedString(),\n receiverID: myPeerID,\n packetType: packet.type,\n reason: reason,\n errorCode: errorCode\n )\n \n let nackPacket = BitchatPacket(\n type: MessageType.protocolNack.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: peerID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: nack.toBinaryData(),\n signature: nil,\n ttl: 3 // NACKs don't need to travel far\n )\n \n // Protocol NACKs should go directly to the sender when possible\n if !sendDirectToRecipient(nackPacket, recipientPeerID: peerID) {\n // Fall back to selective relay if direct delivery fails\n sendViaSelectiveRelay(nackPacket, recipientPeerID: peerID)\n }\n }\n \n // Generate unique packet ID from immutable packet fields\n private func generatePacketID(for packet: BitchatPacket) -> String {\n // Use only immutable fields for ID generation to ensure consistency\n // across network hops (TTL changes, so can't use full packet data)\n \n // Create a deterministic ID using SHA256 of immutable fields\n var data = Data()\n data.append(packet.senderID)\n data.append(contentsOf: withUnsafeBytes(of: packet.timestamp) { Array($0) })\n data.append(packet.type)\n // Add first 32 bytes of payload for uniqueness\n data.append(packet.payload.prefix(32))\n \n let hash = SHA256.hash(data: data)\n let hashData = Data(hash)\n \n // Take first 16 bytes for UUID format\n let bytes = Array(hashData.prefix(16))\n \n // Format as UUID\n let p1 = String(format: \"%02x%02x%02x%02x\", bytes[0], bytes[1], bytes[2], bytes[3])\n let p2 = String(format: \"%02x%02x\", bytes[4], bytes[5])\n let p3 = String(format: \"%02x%02x\", bytes[6], bytes[7])\n let p4 = String(format: \"%02x%02x\", bytes[8], bytes[9])\n let p5 = String(format: \"%02x%02x%02x%02x%02x%02x\", bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15])\n \n let result = \"\\(p1)-\\(p2)-\\(p3)-\\(p4)-\\(p5)\"\n \n // Generated packet ID for tracking\n \n return result\n }\n \n // Track packets that need ACKs\n private func trackPacketForAck(_ packet: BitchatPacket) {\n let packetID = generatePacketID(for: packet)\n \n // Debug: log packet details\n _ = packet.senderID.prefix(4).hexEncodedString()\n _ = packet.recipientID?.prefix(4).hexEncodedString() ?? \"nil\"\n // Track packet for ACK\n \n collectionsQueue.sync(flags: .barrier) {\n pendingAcks[packetID] = (packet: packet, timestamp: Date(), retries: 0)\n }\n \n // Schedule timeout check with initial delay (using exponential backoff starting at 1s)\n let initialDelay = calculateExponentialBackoff(retry: 1) // 1 second initial delay\n DispatchQueue.main.asyncAfter(deadline: .now() + initialDelay) { [weak self] in\n self?.checkAckTimeout(for: packetID)\n }\n }\n \n // Check for ACK timeout and retry if needed\n private func checkAckTimeout(for packetID: String) {\n // Check if already acknowledged\n acknowledgedPacketsLock.lock()\n let isAcknowledged = acknowledgedPackets.contains(packetID)\n acknowledgedPacketsLock.unlock()\n \n if isAcknowledged {\n // Already acknowledged, remove from pending and don't retry\n _ = collectionsQueue.sync(flags: .barrier) {\n pendingAcks.removeValue(forKey: packetID)\n }\n SecureLogger.log(\"Packet \\(packetID) already acknowledged, cancelling retries\", \n category: SecureLogger.session, level: .debug)\n return\n }\n \n collectionsQueue.sync(flags: .barrier) { [weak self] in\n guard let self = self,\n let pending = self.pendingAcks[packetID] else { return }\n \n // Check if this is a handshake packet and we already have an established session\n if pending.packet.type == MessageType.noiseHandshakeInit.rawValue ||\n pending.packet.type == MessageType.noiseHandshakeResp.rawValue {\n // Extract peer ID from packet\n let peerID = pending.packet.recipientID?.hexEncodedString() ?? \"\"\n if !peerID.isEmpty && self.noiseService.hasEstablishedSession(with: peerID) {\n // We have an established session, don't retry handshake packets\n SecureLogger.log(\"Not retrying handshake packet \\(packetID) - session already established with \\(peerID)\", \n category: SecureLogger.handshake, level: .info)\n self.pendingAcks.removeValue(forKey: packetID)\n return\n }\n }\n \n if pending.retries < self.maxAckRetries {\n // Retry sending the packet\n SecureLogger.log(\"ACK timeout for packet \\(packetID), retrying (attempt \\(pending.retries + 1))\", \n category: SecureLogger.session, level: .warning)\n \n self.pendingAcks[packetID] = (packet: pending.packet, \n timestamp: Date(), \n retries: pending.retries + 1)\n \n // Resend the packet\n SecureLogger.log(\"Resending packet due to ACK timeout (retry \\(pending.retries + 1))\", \n category: SecureLogger.session, level: .debug)\n DispatchQueue.main.async {\n self.broadcastPacket(pending.packet)\n }\n \n // Schedule next timeout check with exponential backoff\n let backoffDelay = self.calculateExponentialBackoff(retry: pending.retries + 1)\n DispatchQueue.main.asyncAfter(deadline: .now() + backoffDelay) {\n self.checkAckTimeout(for: packetID)\n }\n } else {\n // Max retries reached, give up\n SecureLogger.log(\"Max ACK retries reached for packet \\(packetID), giving up\", \n category: SecureLogger.session, level: .error)\n self.pendingAcks.removeValue(forKey: packetID)\n \n // Could notify upper layer about delivery failure here\n }\n }\n }\n \n // Check all pending ACKs for timeouts (called by timer)\n private func checkAckTimeouts() {\n let now = Date()\n var timedOutPackets: [String] = []\n \n collectionsQueue.sync {\n for (packetID, pending) in pendingAcks {\n if now.timeIntervalSince(pending.timestamp) > ackTimeout {\n timedOutPackets.append(packetID)\n }\n }\n }\n \n // Process timeouts outside the sync block\n for packetID in timedOutPackets {\n checkAckTimeout(for: packetID)\n }\n }\n \n // Update RSSI for all connected peripherals\n private func updateAllPeripheralRSSI() {\n \n // Read RSSI for all connected peripherals\n for (_, peripheral) in connectedPeripherals {\n if peripheral.state == .connected {\n peripheral.readRSSI()\n }\n }\n }\n \n // Check peer availability based on last heard time\n private func checkPeerAvailability() {\n let now = Date()\n var stateChanges: [(peerID: String, available: Bool)] = []\n \n collectionsQueue.sync(flags: .barrier) {\n // Check all active peers\n for peerID in activePeers {\n let lastHeard = lastHeardFromPeer[peerID] ?? Date.distantPast\n let timeSinceLastHeard = now.timeIntervalSince(lastHeard)\n let wasAvailable = peerAvailabilityState[peerID] ?? true\n \n // Check connection state\n let connectionState = peerConnectionStates[peerID] ?? .disconnected\n let hasConnection = connectionState == .connected || connectionState == .authenticating || connectionState == .authenticated\n \n // Peer is available if:\n // 1. We have an active connection (regardless of last heard time), OR\n // 2. We're authenticated and heard from them within timeout period\n let isAvailable = hasConnection || \n (connectionState == .authenticated && timeSinceLastHeard < peerAvailabilityTimeout)\n \n if wasAvailable != isAvailable {\n peerAvailabilityState[peerID] = isAvailable\n stateChanges.append((peerID: peerID, available: isAvailable))\n }\n }\n \n // Remove availability state for peers no longer active\n let inactivePeers = peerAvailabilityState.keys.filter { !activePeers.contains($0) }\n for peerID in inactivePeers {\n peerAvailabilityState.removeValue(forKey: peerID)\n }\n }\n \n // Notify about availability changes\n for change in stateChanges {\n SecureLogger.log(\"Peer \\(change.peerID) availability changed to: \\(change.available)\", \n category: SecureLogger.session, level: .info)\n \n // Notify delegate about availability change\n DispatchQueue.main.async { [weak self] in\n self?.delegate?.peerAvailabilityChanged(change.peerID, available: change.available)\n }\n }\n }\n \n // Update peer availability when we hear from them\n private func updatePeerAvailability(_ peerID: String) {\n collectionsQueue.sync(flags: .barrier) {\n lastHeardFromPeer[peerID] = Date()\n \n // If peer wasn't available, mark as available now\n if peerAvailabilityState[peerID] != true {\n peerAvailabilityState[peerID] = true\n \n SecureLogger.log(\"Peer \\(peerID) marked as available after hearing from them\", \n category: SecureLogger.session, level: .info)\n \n DispatchQueue.main.async { [weak self] in\n self?.delegate?.peerAvailabilityChanged(peerID, available: true)\n }\n }\n }\n }\n \n // Check if a peer is currently available\n func isPeerAvailable(_ peerID: String) -> Bool {\n return collectionsQueue.sync {\n return peerAvailabilityState[peerID] ?? false\n }\n }\n \n private func sendNoiseIdentityAnnounce(to specificPeerID: String? = nil) {\n // Rate limit identity announcements\n let now = Date()\n \n // If targeting a specific peer, check rate limit\n if let peerID = specificPeerID {\n if let lastTime = lastIdentityAnnounceTimes[peerID],\n now.timeIntervalSince(lastTime) < identityAnnounceMinInterval {\n // Too soon, skip this announcement\n return\n }\n lastIdentityAnnounceTimes[peerID] = now\n } else {\n // Broadcasting to all - check global rate limit\n if let lastTime = lastIdentityAnnounceTimes[\"*broadcast*\"],\n now.timeIntervalSince(lastTime) < identityAnnounceMinInterval {\n return\n }\n lastIdentityAnnounceTimes[\"*broadcast*\"] = now\n }\n \n // Get our Noise static public key and signing public key\n let staticKey = noiseService.getStaticPublicKeyData()\n let signingKey = noiseService.getSigningPublicKeyData()\n \n // Get nickname from delegate\n let nickname = (delegate as? ChatViewModel)?.nickname ?? \"Anonymous\"\n \n // Create the binding data to sign (peerID + publicKey + timestamp)\n let timestampData = String(Int64(now.timeIntervalSince1970 * 1000)).data(using: .utf8)!\n let bindingData = myPeerID.data(using: .utf8)! + staticKey + timestampData\n \n // Sign the binding with our Ed25519 signing key\n let signature = noiseService.signData(bindingData) ?? Data()\n \n // Create the identity announcement\n let announcement = NoiseIdentityAnnouncement(\n peerID: myPeerID,\n publicKey: staticKey,\n signingPublicKey: signingKey,\n nickname: nickname,\n timestamp: now,\n previousPeerID: previousPeerID,\n signature: signature\n )\n \n // Encode the announcement\n let announcementData = announcement.toBinaryData()\n \n let packet = BitchatPacket(\n type: MessageType.noiseIdentityAnnounce.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: specificPeerID.flatMap { Data(hexString: $0) }, // Targeted or broadcast\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: announcementData,\n signature: nil,\n ttl: adaptiveTTL )\n \n if let targetPeer = specificPeerID {\n SecureLogger.log(\"Sending targeted identity announce to \\(targetPeer)\", \n category: SecureLogger.noise, level: .info)\n \n // Try direct delivery for targeted announces\n if !sendDirectToRecipient(packet, recipientPeerID: targetPeer) {\n // Fall back to selective relay if direct delivery fails\n SecureLogger.log(\"Recipient \\(targetPeer) not directly connected for identity announce, using relay\", \n category: SecureLogger.session, level: .info)\n sendViaSelectiveRelay(packet, recipientPeerID: targetPeer)\n }\n } else {\n SecureLogger.log(\"Broadcasting identity announce to all peers\", \n category: SecureLogger.noise, level: .info)\n broadcastPacket(packet)\n }\n }\n \n // Removed sendPacket method - all packets should use broadcastPacket to ensure mesh delivery\n \n // Send private message using Noise Protocol\n private func sendPrivateMessageViaNoise(_ content: String, to recipientPeerID: String, recipientNickname: String, messageID: String? = nil) {\n SecureLogger.log(\"sendPrivateMessageViaNoise called - content: '\\(content.prefix(50))...', to: \\(recipientPeerID), messageID: \\(messageID ?? \"nil\")\", \n category: SecureLogger.noise, level: .info)\n \n // Use per-peer encryption queue to prevent nonce desynchronization\n let encryptionQueue = getEncryptionQueue(for: recipientPeerID)\n \n encryptionQueue.async { [weak self] in\n guard let self = self else { return }\n \n // Use noiseService directly\n \n // Check if we have a Noise session with this peer\n let hasSession = self.noiseService.hasEstablishedSession(with: recipientPeerID)\n \n // Check if session is stale (no successful communication for a while)\n var sessionIsStale = false\n if hasSession {\n let lastSuccess = lastSuccessfulMessageTime[recipientPeerID] ?? Date.distantPast\n let sessionAge = Date().timeIntervalSince(lastSuccess)\n // Increase session validity to 24 hours - sessions should persist across temporary disconnects\n if sessionAge > 86400.0 { // More than 24 hours since last successful message\n sessionIsStale = true\n SecureLogger.log(\"Session with \\(recipientPeerID) is stale (last success: \\(Int(sessionAge))s ago), will re-establish\", category: SecureLogger.noise, level: .info)\n }\n }\n \n if !hasSession || sessionIsStale {\n if sessionIsStale {\n // Clear stale session first\n cleanupPeerCryptoState(recipientPeerID)\n }\n \n // Update state to handshakeQueued\n collectionsQueue.sync(flags: .barrier) {\n self.noiseSessionStates[recipientPeerID] = .handshakeQueued\n }\n \n SecureLogger.log(\"No valid Noise session with \\(recipientPeerID), initiating handshake (lazy mode)\", category: SecureLogger.noise, level: .info)\n \n // Notify UI that we're establishing encryption\n DispatchQueue.main.async { [weak self] in\n if let chatVM = self?.delegate as? ChatViewModel {\n // This will update the UI to show \"establishing encryption\" state\n chatVM.updateEncryptionStatusForPeer(recipientPeerID)\n }\n }\n \n // Queue message for sending after handshake completes\n collectionsQueue.sync(flags: .barrier) { [weak self] in\n guard let self = self else { return }\n if self.pendingPrivateMessages[recipientPeerID] == nil {\n self.pendingPrivateMessages[recipientPeerID] = []\n }\n self.pendingPrivateMessages[recipientPeerID]?.append((content, recipientNickname, messageID ?? UUID().uuidString))\n let count = self.pendingPrivateMessages[recipientPeerID]?.count ?? 0\n SecureLogger.log(\"Queued private message for \\(recipientPeerID), \\(count) messages pending\", category: SecureLogger.noise, level: .info)\n }\n \n // Send handshake request to notify recipient of pending messages\n sendHandshakeRequest(to: recipientPeerID, pendingCount: UInt8(pendingPrivateMessages[recipientPeerID]?.count ?? 1))\n \n // Apply tie-breaker logic for handshake initiation\n if myPeerID < recipientPeerID {\n // We have lower ID, initiate handshake\n initiateNoiseHandshake(with: recipientPeerID)\n } else {\n // We have higher ID, send targeted identity announce to prompt them to initiate\n sendNoiseIdentityAnnounce(to: recipientPeerID)\n }\n \n return\n }\n \n // Use provided message ID or generate a new one\n let msgID = messageID ?? UUID().uuidString\n \n // Check if we're already processing this message\n let sendKey = \"\\(msgID)-\\(recipientPeerID)\"\n let alreadySending = self.collectionsQueue.sync(flags: .barrier) {\n if self.recentlySentMessages.contains(sendKey) {\n return true\n }\n self.recentlySentMessages.insert(sendKey)\n // Clean up old entries after 10 seconds\n DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) { [weak self] in\n self?.collectionsQueue.sync(flags: .barrier) {\n _ = self?.recentlySentMessages.remove(sendKey)\n }\n }\n return false\n }\n \n if alreadySending {\n return\n }\n \n \n // Get sender nickname from delegate\n let nickname = self.delegate as? ChatViewModel\n let senderNick = nickname?.nickname ?? self.myPeerID\n \n // Create the inner message\n let message = BitchatMessage(\n id: msgID,\n sender: senderNick,\n content: content,\n timestamp: Date(),\n isRelay: false,\n isPrivate: true,\n recipientNickname: recipientNickname,\n senderPeerID: myPeerID\n )\n \n // Use binary payload format to match the receiver's expectations\n guard let messageData = message.toBinaryPayload() else { \n return \n }\n \n // Create inner packet\n let innerPacket = BitchatPacket(\n type: MessageType.message.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: recipientPeerID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: messageData,\n signature: nil,\n ttl: self.adaptiveTTL // Inner packet needs valid TTL for processing after decryption\n )\n \n guard let innerData = innerPacket.toBinaryData() else { return }\n \n do {\n // Encrypt with Noise\n SecureLogger.log(\"Encrypting private message \\(msgID) for \\(recipientPeerID)\", category: SecureLogger.encryption, level: .debug)\n let encryptedData = try noiseService.encrypt(innerData, for: recipientPeerID)\n SecureLogger.log(\"Successfully encrypted message, size: \\(encryptedData.count)\", category: SecureLogger.encryption, level: .debug)\n \n // Update last successful message time\n lastSuccessfulMessageTime[recipientPeerID] = Date()\n \n // Send as Noise encrypted message\n let outerPacket = BitchatPacket(\n type: MessageType.noiseEncrypted.rawValue,\n senderID: Data(hexString: myPeerID) ?? Data(),\n recipientID: Data(hexString: recipientPeerID) ?? Data(),\n timestamp: UInt64(Date().timeIntervalSince1970 * 1000),\n payload: encryptedData,\n signature: nil,\n ttl: adaptiveTTL )\n \n SecureLogger.log(\"Sending encrypted private message \\(msgID) to \\(recipientPeerID)\", category: SecureLogger.session, level: .info)\n \n // Track packet for ACK\n trackPacketForAck(outerPacket)\n \n // Try direct delivery first\n if !sendDirectToRecipient(outerPacket, recipientPeerID: recipientPeerID) {\n // Recipient not directly connected, use selective relay\n SecureLogger.log(\"Recipient \\(recipientPeerID) not directly connected, using relay strategy\", \n category: SecureLogger.session, level: .info)\n sendViaSelectiveRelay(outerPacket, recipientPeerID: recipientPeerID)\n }\n } catch {\n // Failed to encrypt message\n SecureLogger.log(\"Failed to encrypt private message \\(msgID) for \\(recipientPeerID): \\(error)\", category: SecureLogger.encryption, level: .error)\n }\n } // End of encryptionQueue.async\n }\n \n // MARK: - Targeted Message Delivery\n \n private func sendDirectToRecipient(_ packet: BitchatPacket, recipientPeerID: String) -> Bool {\n // Try to send directly to the recipient if they're connected\n if let peripheral = connectedPeripherals[recipientPeerID],\n let characteristic = peripheralCharacteristics[peripheral],\n peripheral.state == .connected {\n \n guard let data = packet.toBinaryData() else { return false }\n \n // Send only to the intended recipient\n writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: recipientPeerID)\n SecureLogger.log(\"Sent private message directly to \\(recipientPeerID)\", category: SecureLogger.session, level: .info)\n return true\n }\n \n // Check if recipient is connected as a central (we're peripheral)\n if !subscribedCentrals.isEmpty {\n // We can't target specific centrals, so return false to trigger relay\n return false\n }\n \n return false\n }\n \n private func sendHandshakeRequest(to targetPeerID: String, pendingCount: UInt8) {\n // Create handshake request\n let request = HandshakeRequest(requesterID: myPeerID,\n requesterNickname: (delegate as? ChatViewModel)?.nickname ?? myPeerID,\n targetID: targetPeerID,\n pendingMessageCount: pendingCount)\n \n let requestData = request.toBinaryData()\n \n // Create packet for handshake request\n let packet = BitchatPacket(type: MessageType.handshakeRequest.rawValue,\n ttl: 6,\n senderID: myPeerID,\n payload: requestData)\n \n // Try direct delivery first\n if sendDirectToRecipient(packet, recipientPeerID: targetPeerID) {\n SecureLogger.log(\"Sent handshake request directly to \\(targetPeerID)\", category: SecureLogger.noise, level: .info)\n } else {\n // Use selective relay if direct delivery fails\n sendViaSelectiveRelay(packet, recipientPeerID: targetPeerID)\n SecureLogger.log(\"Sent handshake request via relay to \\(targetPeerID)\", category: SecureLogger.noise, level: .info)\n }\n }\n \n private func selectBestRelayPeers(excluding: String, maxPeers: Int = 3) -> [String] {\n // Select peers with best RSSI for relay, excluding the target recipient\n var candidates: [(peerID: String, rssi: Int)] = []\n \n for (peerID, _) in connectedPeripherals {\n if peerID != excluding && peerID != myPeerID {\n let rssiValue = peerRSSI[peerID]?.intValue ?? -80\n candidates.append((peerID: peerID, rssi: rssiValue))\n }\n }\n \n // Sort by RSSI (strongest first) and take top N\n candidates.sort { $0.rssi > $1.rssi }\n return candidates.prefix(maxPeers).map { $0.peerID }\n }\n \n private func sendViaSelectiveRelay(_ packet: BitchatPacket, recipientPeerID: String) {\n // Select best relay candidates\n let relayPeers = selectBestRelayPeers(excluding: recipientPeerID)\n \n if relayPeers.isEmpty {\n // No relay candidates, fall back to broadcast\n SecureLogger.log(\"No relay candidates for private message to \\(recipientPeerID), using broadcast\", \n category: SecureLogger.session, level: .warning)\n broadcastPacket(packet)\n return\n }\n \n // Limit TTL for relay\n var relayPacket = packet\n relayPacket.ttl = min(packet.ttl, 2) // Max 2 hops for private message relay\n \n guard let data = relayPacket.toBinaryData() else { return }\n \n // Send to selected relay peers\n var sentCount = 0\n for relayPeerID in relayPeers {\n if let peripheral = connectedPeripherals[relayPeerID],\n let characteristic = peripheralCharacteristics[peripheral],\n peripheral.state == .connected {\n writeToPeripheral(data, peripheral: peripheral, characteristic: characteristic, peerID: relayPeerID)\n sentCount += 1\n }\n }\n \n SecureLogger.log(\"Sent private message to \\(sentCount) relay peers (targeting \\(recipientPeerID))\", \n category: SecureLogger.session, level: .info)\n \n // If no relays worked, fall back to broadcast\n if sentCount == 0 {\n SecureLogger.log(\"Failed to send to relay peers, falling back to broadcast\", \n category: SecureLogger.session, level: .warning)\n broadcastPacket(packet)\n }\n }\n \n // MARK: - Connection Pool Management\n \n private func findLeastRecentlyUsedPeripheral() -> String? {\n var lruPeripheralID: String?\n var oldestActivityTime = Date()\n \n for (peripheralID, peripheral) in connectionPool {\n // Only consider connected peripherals\n guard peripheral.state == .connected else { continue }\n \n // Skip if this peripheral has an active peer connection\n if let peerID = peerIDByPeripheralID[peripheralID],\n activePeers.contains(peerID) {\n continue\n }\n \n // Find the least recently used peripheral based on last activity\n if let lastActivity = lastActivityByPeripheralID[peripheralID],\n lastActivity < oldestActivityTime {\n oldestActivityTime = lastActivity\n lruPeripheralID = peripheralID\n } else if lastActivityByPeripheralID[peripheralID] == nil {\n // If no activity recorded, it's a candidate for removal\n lruPeripheralID = peripheralID\n break\n }\n }\n \n return lruPeripheralID\n }\n \n // Track activity for peripherals\n private func updatePeripheralActivity(_ peripheralID: String) {\n lastActivityByPeripheralID[peripheralID] = Date()\n }\n}\n"], ["/bitchat/bitchat/Services/NoiseEncryptionService.swift", "//\n// NoiseEncryptionService.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # NoiseEncryptionService\n///\n/// High-level encryption service that manages Noise Protocol sessions for secure\n/// peer-to-peer communication in BitChat. Acts as the bridge between the transport\n/// layer (BluetoothMeshService) and the cryptographic layer (NoiseProtocol).\n///\n/// ## Overview\n/// This service provides a simplified API for establishing and managing encrypted\n/// channels between peers. It handles:\n/// - Static identity key management\n/// - Session lifecycle (creation, maintenance, teardown)\n/// - Message encryption/decryption\n/// - Peer authentication and fingerprint tracking\n/// - Automatic rekeying for forward secrecy\n///\n/// ## Architecture\n/// The service operates at multiple levels:\n/// 1. **Identity Management**: Persistent Curve25519 keys stored in Keychain\n/// 2. **Session Management**: Per-peer Noise sessions with state tracking\n/// 3. **Message Processing**: Encryption/decryption with proper framing\n/// 4. **Security Features**: Rate limiting, fingerprint verification\n///\n/// ## Key Features\n///\n/// ### Identity Keys\n/// - Static Curve25519 key pair for Noise XX pattern\n/// - Ed25519 signing key pair for additional authentication\n/// - Keys persisted securely in iOS/macOS Keychain\n/// - Fingerprints derived from SHA256 of public keys\n///\n/// ### Session Management\n/// - Lazy session creation (on-demand when sending messages)\n/// - Automatic session recovery after disconnections\n/// - Configurable rekey intervals for forward secrecy\n/// - Graceful handling of simultaneous handshakes\n///\n/// ### Security Properties\n/// - Forward secrecy via ephemeral keys in handshakes\n/// - Mutual authentication via static key exchange\n/// - Protection against replay attacks\n/// - Rate limiting to prevent DoS attacks\n///\n/// ## Encryption Flow\n/// ```\n/// 1. Message arrives for encryption\n/// 2. Check if session exists for peer\n/// 3. If not, initiate Noise handshake\n/// 4. Once established, encrypt message\n/// 5. Add message type header for protocol handling\n/// 6. Return encrypted payload for transmission\n/// ```\n///\n/// ## Integration Points\n/// - **BluetoothMeshService**: Calls this service for all private messages\n/// - **ChatViewModel**: Monitors encryption status for UI indicators\n/// - **NoiseHandshakeCoordinator**: Prevents handshake race conditions\n/// - **KeychainManager**: Secure storage for identity keys\n///\n/// ## Thread Safety\n/// - Concurrent read access via reader-writer queue\n/// - Session operations protected by per-peer queues\n/// - Atomic updates for critical state changes\n///\n/// ## Error Handling\n/// - Graceful fallback for encryption failures\n/// - Clear error messages for debugging\n/// - Automatic retry with exponential backoff\n/// - User notification for critical failures\n///\n/// ## Performance Considerations\n/// - Sessions cached in memory for fast access\n/// - Minimal allocations in hot paths\n/// - Efficient binary message format\n/// - Background queue for CPU-intensive operations\n///\n\nimport Foundation\nimport CryptoKit\nimport os.log\n\n// MARK: - Encryption Status\n\n/// Represents the current encryption status of a peer connection.\n/// Used for UI indicators and decision-making about message handling.\nenum EncryptionStatus: Equatable {\n case none // Failed or incompatible\n case noHandshake // No handshake attempted yet\n case noiseHandshaking // Currently establishing\n case noiseSecured // Established but not verified\n case noiseVerified // Established and verified\n \n var icon: String? { // Made optional to hide icon when no handshake\n switch self {\n case .none:\n return \"lock.slash\" // Failed handshake\n case .noHandshake:\n return nil // No icon when no handshake attempted\n case .noiseHandshaking:\n return \"lock.rotation\"\n case .noiseSecured:\n return \"lock.fill\" // Changed from \"lock\" to \"lock.fill\" for filled lock\n case .noiseVerified:\n return \"lock.shield.fill\" // Changed to filled version for consistency\n }\n }\n \n var description: String {\n switch self {\n case .none:\n return \"Encryption failed\"\n case .noHandshake:\n return \"Not encrypted\"\n case .noiseHandshaking:\n return \"Establishing encryption...\"\n case .noiseSecured:\n return \"Encrypted\"\n case .noiseVerified:\n return \"Encrypted & Verified\"\n }\n }\n}\n\n// MARK: - Noise Encryption Service\n\n/// Manages end-to-end encryption for BitChat using the Noise Protocol Framework.\n/// Provides a high-level API for establishing secure channels between peers,\n/// handling all cryptographic operations transparently.\n/// - Important: This service maintains the device's cryptographic identity\nclass NoiseEncryptionService {\n // Static identity key (persistent across sessions)\n private let staticIdentityKey: Curve25519.KeyAgreement.PrivateKey\n public let staticIdentityPublicKey: Curve25519.KeyAgreement.PublicKey\n \n // Ed25519 signing key (persistent across sessions)\n private let signingKey: Curve25519.Signing.PrivateKey\n public let signingPublicKey: Curve25519.Signing.PublicKey\n \n // Session manager\n private let sessionManager: NoiseSessionManager\n \n // Peer fingerprints (SHA256 hash of static public key)\n private var peerFingerprints: [String: String] = [:] // peerID -> fingerprint\n private var fingerprintToPeerID: [String: String] = [:] // fingerprint -> peerID\n \n // Thread safety\n private let serviceQueue = DispatchQueue(label: \"chat.bitchat.noise.service\", attributes: .concurrent)\n \n // Security components\n private let rateLimiter = NoiseRateLimiter()\n \n // Session maintenance\n private var rekeyTimer: Timer?\n private let rekeyCheckInterval: TimeInterval = 60.0 // Check every minute\n \n // Callbacks\n var onPeerAuthenticated: ((String, String) -> Void)? // peerID, fingerprint\n var onHandshakeRequired: ((String) -> Void)? // peerID needs handshake\n \n init() {\n // Load or create static identity key (ONLY from keychain)\n let loadedKey: Curve25519.KeyAgreement.PrivateKey\n \n // Try to load from keychain\n if let identityData = KeychainManager.shared.getIdentityKey(forKey: \"noiseStaticKey\"),\n let key = try? Curve25519.KeyAgreement.PrivateKey(rawRepresentation: identityData) {\n loadedKey = key\n SecureLogger.logKeyOperation(\"load\", keyType: \"noiseStaticKey\", success: true)\n }\n // If no identity exists, create new one\n else {\n loadedKey = Curve25519.KeyAgreement.PrivateKey()\n let keyData = loadedKey.rawRepresentation\n \n // Save to keychain\n let saved = KeychainManager.shared.saveIdentityKey(keyData, forKey: \"noiseStaticKey\")\n SecureLogger.logKeyOperation(\"create\", keyType: \"noiseStaticKey\", success: saved)\n }\n \n // Now assign the final value\n self.staticIdentityKey = loadedKey\n self.staticIdentityPublicKey = staticIdentityKey.publicKey\n \n // Load or create signing key pair\n let loadedSigningKey: Curve25519.Signing.PrivateKey\n \n // Try to load from keychain\n if let signingData = KeychainManager.shared.getIdentityKey(forKey: \"ed25519SigningKey\"),\n let key = try? Curve25519.Signing.PrivateKey(rawRepresentation: signingData) {\n loadedSigningKey = key\n SecureLogger.logKeyOperation(\"load\", keyType: \"ed25519SigningKey\", success: true)\n }\n // If no signing key exists, create new one\n else {\n loadedSigningKey = Curve25519.Signing.PrivateKey()\n let keyData = loadedSigningKey.rawRepresentation\n \n // Save to keychain\n let saved = KeychainManager.shared.saveIdentityKey(keyData, forKey: \"ed25519SigningKey\")\n SecureLogger.logKeyOperation(\"create\", keyType: \"ed25519SigningKey\", success: saved)\n }\n \n // Now assign the signing keys\n self.signingKey = loadedSigningKey\n self.signingPublicKey = signingKey.publicKey\n \n // Initialize session manager\n self.sessionManager = NoiseSessionManager(localStaticKey: staticIdentityKey)\n \n // Set up session callbacks\n sessionManager.onSessionEstablished = { [weak self] peerID, remoteStaticKey in\n self?.handleSessionEstablished(peerID: peerID, remoteStaticKey: remoteStaticKey)\n }\n \n // Start session maintenance timer\n startRekeyTimer()\n }\n \n // MARK: - Public Interface\n \n /// Get our static public key for sharing\n func getStaticPublicKeyData() -> Data {\n return staticIdentityPublicKey.rawRepresentation\n }\n \n /// Get our signing public key for sharing\n func getSigningPublicKeyData() -> Data {\n return signingPublicKey.rawRepresentation\n }\n \n /// Get our identity fingerprint\n func getIdentityFingerprint() -> String {\n let hash = SHA256.hash(data: staticIdentityPublicKey.rawRepresentation)\n return hash.map { String(format: \"%02x\", $0) }.joined()\n }\n \n /// Get peer's public key data\n func getPeerPublicKeyData(_ peerID: String) -> Data? {\n return sessionManager.getRemoteStaticKey(for: peerID)?.rawRepresentation\n }\n \n /// Clear persistent identity (for panic mode)\n func clearPersistentIdentity() {\n // Clear from keychain\n let deletedStatic = KeychainManager.shared.deleteIdentityKey(forKey: \"noiseStaticKey\")\n let deletedSigning = KeychainManager.shared.deleteIdentityKey(forKey: \"ed25519SigningKey\")\n SecureLogger.logKeyOperation(\"delete\", keyType: \"identity keys\", success: deletedStatic && deletedSigning)\n SecureLogger.log(\"Panic mode activated - identity cleared\", category: SecureLogger.security, level: .warning)\n // Stop rekey timer\n stopRekeyTimer()\n }\n \n /// Sign data with our Ed25519 signing key\n func signData(_ data: Data) -> Data? {\n do {\n let signature = try signingKey.signature(for: data)\n return signature\n } catch {\n SecureLogger.logError(error, context: \"Failed to sign data\", category: SecureLogger.noise)\n return nil\n }\n }\n \n /// Verify signature with a peer's Ed25519 public key\n func verifySignature(_ signature: Data, for data: Data, publicKey: Data) -> Bool {\n do {\n let signingPublicKey = try Curve25519.Signing.PublicKey(rawRepresentation: publicKey)\n return signingPublicKey.isValidSignature(signature, for: data)\n } catch {\n SecureLogger.logError(error, context: \"Failed to verify signature\", category: SecureLogger.noise)\n return false\n }\n }\n \n // MARK: - Handshake Management\n \n /// Initiate a Noise handshake with a peer\n func initiateHandshake(with peerID: String) throws -> Data {\n \n // Validate peer ID\n guard NoiseSecurityValidator.validatePeerID(peerID) else {\n SecureLogger.logSecurityEvent(.authenticationFailed(peerID: peerID), level: .warning)\n throw NoiseSecurityError.invalidPeerID\n }\n \n // Check rate limit\n guard rateLimiter.allowHandshake(from: peerID) else {\n SecureLogger.logSecurityEvent(.authenticationFailed(peerID: \"Rate limited: \\(peerID)\"), level: .warning)\n throw NoiseSecurityError.rateLimitExceeded\n }\n \n SecureLogger.logSecurityEvent(.handshakeStarted(peerID: peerID))\n \n // Return raw handshake data without wrapper\n // The Noise protocol handles its own message format\n let handshakeData = try sessionManager.initiateHandshake(with: peerID)\n return handshakeData\n }\n \n /// Process an incoming handshake message\n func processHandshakeMessage(from peerID: String, message: Data) throws -> Data? {\n \n // Validate peer ID\n guard NoiseSecurityValidator.validatePeerID(peerID) else {\n SecureLogger.logSecurityEvent(.authenticationFailed(peerID: peerID), level: .warning)\n throw NoiseSecurityError.invalidPeerID\n }\n \n // Validate message size\n guard NoiseSecurityValidator.validateHandshakeMessageSize(message) else {\n SecureLogger.logSecurityEvent(.handshakeFailed(peerID: peerID, error: \"Message too large\"), level: .warning)\n throw NoiseSecurityError.messageTooLarge\n }\n \n // Check rate limit\n guard rateLimiter.allowHandshake(from: peerID) else {\n SecureLogger.logSecurityEvent(.authenticationFailed(peerID: \"Rate limited: \\(peerID)\"), level: .warning)\n throw NoiseSecurityError.rateLimitExceeded\n }\n \n // For handshakes, we process the raw data directly without NoiseMessage wrapper\n // The Noise protocol handles its own message format\n let responsePayload = try sessionManager.handleIncomingHandshake(from: peerID, message: message)\n \n \n // Return raw response without wrapper\n return responsePayload\n }\n \n /// Check if we have an established session with a peer\n func hasEstablishedSession(with peerID: String) -> Bool {\n return sessionManager.getSession(for: peerID)?.isEstablished() ?? false\n }\n \n /// Check if we have a session (established or handshaking) with a peer\n func hasSession(with peerID: String) -> Bool {\n return sessionManager.getSession(for: peerID) != nil\n }\n \n // MARK: - Encryption/Decryption\n \n /// Encrypt data for a specific peer\n func encrypt(_ data: Data, for peerID: String) throws -> Data {\n // Validate message size\n guard NoiseSecurityValidator.validateMessageSize(data) else {\n throw NoiseSecurityError.messageTooLarge\n }\n \n // Check rate limit\n guard rateLimiter.allowMessage(from: peerID) else {\n throw NoiseSecurityError.rateLimitExceeded\n }\n \n // Check if we have an established session\n guard hasEstablishedSession(with: peerID) else {\n // Signal that handshake is needed\n onHandshakeRequired?(peerID)\n throw NoiseEncryptionError.handshakeRequired\n }\n \n return try sessionManager.encrypt(data, for: peerID)\n }\n \n /// Decrypt data from a specific peer\n func decrypt(_ data: Data, from peerID: String) throws -> Data {\n // Validate message size\n guard NoiseSecurityValidator.validateMessageSize(data) else {\n throw NoiseSecurityError.messageTooLarge\n }\n \n // Check rate limit\n guard rateLimiter.allowMessage(from: peerID) else {\n throw NoiseSecurityError.rateLimitExceeded\n }\n \n // Check if we have an established session\n guard hasEstablishedSession(with: peerID) else {\n throw NoiseEncryptionError.sessionNotEstablished\n }\n \n return try sessionManager.decrypt(data, from: peerID)\n }\n \n // MARK: - Peer Management\n \n /// Get fingerprint for a peer\n func getPeerFingerprint(_ peerID: String) -> String? {\n return serviceQueue.sync {\n return peerFingerprints[peerID]\n }\n }\n \n /// Get peer ID for a fingerprint\n func getPeerID(for fingerprint: String) -> String? {\n return serviceQueue.sync {\n return fingerprintToPeerID[fingerprint]\n }\n }\n \n /// Remove a peer session\n func removePeer(_ peerID: String) {\n sessionManager.removeSession(for: peerID)\n \n serviceQueue.sync(flags: .barrier) {\n if let fingerprint = peerFingerprints[peerID] {\n fingerprintToPeerID.removeValue(forKey: fingerprint)\n }\n peerFingerprints.removeValue(forKey: peerID)\n }\n \n SecureLogger.logSecurityEvent(.sessionExpired(peerID: peerID))\n }\n \n /// Migrate session when peer ID changes\n func migratePeerSession(from oldPeerID: String, to newPeerID: String, fingerprint: String) {\n // First update the fingerprint mappings\n serviceQueue.sync(flags: .barrier) {\n // Remove old mapping\n if let oldFingerprint = peerFingerprints[oldPeerID], oldFingerprint == fingerprint {\n peerFingerprints.removeValue(forKey: oldPeerID)\n }\n \n // Add new mapping\n peerFingerprints[newPeerID] = fingerprint\n fingerprintToPeerID[fingerprint] = newPeerID\n }\n \n // Migrate the session in session manager\n sessionManager.migrateSession(from: oldPeerID, to: newPeerID)\n }\n \n // MARK: - Private Helpers\n \n private func handleSessionEstablished(peerID: String, remoteStaticKey: Curve25519.KeyAgreement.PublicKey) {\n // Calculate fingerprint\n let fingerprint = calculateFingerprint(for: remoteStaticKey)\n \n // Store fingerprint mapping\n serviceQueue.sync(flags: .barrier) {\n peerFingerprints[peerID] = fingerprint\n fingerprintToPeerID[fingerprint] = peerID\n }\n \n // Log security event\n SecureLogger.logSecurityEvent(.handshakeCompleted(peerID: peerID))\n \n // Notify about authentication\n onPeerAuthenticated?(peerID, fingerprint)\n }\n \n private func calculateFingerprint(for publicKey: Curve25519.KeyAgreement.PublicKey) -> String {\n let hash = SHA256.hash(data: publicKey.rawRepresentation)\n return hash.map { String(format: \"%02x\", $0) }.joined()\n }\n \n // MARK: - Session Maintenance\n \n private func startRekeyTimer() {\n rekeyTimer = Timer.scheduledTimer(withTimeInterval: rekeyCheckInterval, repeats: true) { [weak self] _ in\n self?.checkSessionsForRekey()\n }\n }\n \n private func stopRekeyTimer() {\n rekeyTimer?.invalidate()\n rekeyTimer = nil\n }\n \n private func checkSessionsForRekey() {\n let sessionsNeedingRekey = sessionManager.getSessionsNeedingRekey()\n \n for (peerID, needsRekey) in sessionsNeedingRekey where needsRekey {\n \n // Attempt to rekey the session\n do {\n try sessionManager.initiateRekey(for: peerID)\n SecureLogger.log(\"Key rotation initiated for peer: \\(peerID)\", category: SecureLogger.security, level: .info)\n \n // Signal that handshake is needed\n onHandshakeRequired?(peerID)\n } catch {\n SecureLogger.logError(error, context: \"Failed to initiate rekey for peer: \\(peerID)\", category: SecureLogger.session)\n }\n }\n }\n \n deinit {\n stopRekeyTimer()\n }\n}\n\n// MARK: - Protocol Message Types for Noise\n\n/// Message types for the Noise encryption protocol layer.\n/// These types wrap the underlying BitChat protocol messages with encryption metadata.\nenum NoiseMessageType: UInt8 {\n case handshakeInitiation = 0x10\n case handshakeResponse = 0x11\n case handshakeFinal = 0x12\n case encryptedMessage = 0x13\n case sessionRenegotiation = 0x14\n}\n\n// MARK: - Noise Message Wrapper\n\n/// Container for encrypted messages in the Noise protocol.\n/// Provides versioning and type information for proper message handling.\n/// The actual message content is encrypted in the payload field.\nstruct NoiseMessage: Codable {\n let type: UInt8\n let sessionID: String // Random ID for this handshake session\n let payload: Data\n \n init(type: NoiseMessageType, sessionID: String, payload: Data) {\n self.type = type.rawValue\n self.sessionID = sessionID\n self.payload = payload\n }\n \n func encode() -> Data? {\n do {\n let encoded = try JSONEncoder().encode(self)\n return encoded\n } catch {\n return nil\n }\n }\n \n static func decode(from data: Data) -> NoiseMessage? {\n return try? JSONDecoder().decode(NoiseMessage.self, from: data)\n }\n \n static func decodeWithError(from data: Data) -> NoiseMessage? {\n do {\n let decoded = try JSONDecoder().decode(NoiseMessage.self, from: data)\n return decoded\n } catch {\n return nil\n }\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUInt8(type)\n data.appendUUID(sessionID)\n data.appendData(payload)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> NoiseMessage? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n var offset = 0\n \n guard let type = dataCopy.readUInt8(at: &offset),\n let sessionID = dataCopy.readUUID(at: &offset),\n let payload = dataCopy.readData(at: &offset) else { return nil }\n \n guard let messageType = NoiseMessageType(rawValue: type) else { return nil }\n \n return NoiseMessage(type: messageType, sessionID: sessionID, payload: payload)\n }\n}\n\n// MARK: - Errors\n\nenum NoiseEncryptionError: Error {\n case handshakeRequired\n case sessionNotEstablished\n}\n"], ["/bitchat/bitchat/Utils/SecureLogger.swift", "//\n// SecureLogger.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport os.log\n\n/// Centralized security-aware logging framework\n/// Provides safe logging that filters sensitive data and security events\nclass SecureLogger {\n \n // MARK: - Log Categories\n \n private static let subsystem = \"chat.bitchat\"\n \n static let noise = OSLog(subsystem: subsystem, category: \"noise\")\n static let encryption = OSLog(subsystem: subsystem, category: \"encryption\")\n static let keychain = OSLog(subsystem: subsystem, category: \"keychain\")\n static let session = OSLog(subsystem: subsystem, category: \"session\")\n static let security = OSLog(subsystem: subsystem, category: \"security\")\n static let handshake = OSLog(subsystem: subsystem, category: \"handshake\")\n \n // MARK: - Timestamp Formatter\n \n private static let timestampFormatter: DateFormatter = {\n let formatter = DateFormatter()\n formatter.dateFormat = \"HH:mm:ss.SSS\"\n formatter.timeZone = TimeZone.current\n return formatter\n }()\n \n // MARK: - Cached Regex Patterns\n \n private static let fingerprintPattern = #/[a-fA-F0-9]{64}/#\n private static let base64Pattern = #/[A-Za-z0-9+/]{40,}={0,2}/#\n private static let passwordPattern = #/password[\"\\s:=]+[\"']?[^\"'\\s]+[\"']?/#\n private static let peerIDPattern = #/peerID: ([a-zA-Z0-9]{8})[a-zA-Z0-9]+/#\n \n // MARK: - Sanitization Cache\n \n private static let sanitizationCache: NSCache = {\n let cache = NSCache()\n cache.countLimit = 100 // Keep last 100 sanitized strings\n return cache\n }()\n private static let cacheQueue = DispatchQueue(label: \"chat.bitchat.securelogger.cache\", attributes: .concurrent)\n \n // MARK: - Log Levels\n \n enum LogLevel {\n case debug\n case info\n case warning\n case error\n case fault\n \n var osLogType: OSLogType {\n switch self {\n case .debug: return .debug\n case .info: return .info\n case .warning: return .default\n case .error: return .error\n case .fault: return .fault\n }\n }\n }\n \n // MARK: - Security Event Types\n \n enum SecurityEvent {\n case handshakeStarted(peerID: String)\n case handshakeCompleted(peerID: String)\n case handshakeFailed(peerID: String, error: String)\n case sessionExpired(peerID: String)\n case authenticationFailed(peerID: String)\n \n var message: String {\n switch self {\n case .handshakeStarted(let peerID):\n return \"Handshake started with peer: \\(sanitize(peerID))\"\n case .handshakeCompleted(let peerID):\n return \"Handshake completed with peer: \\(sanitize(peerID))\"\n case .handshakeFailed(let peerID, let error):\n return \"Handshake failed with peer: \\(sanitize(peerID)), error: \\(error)\"\n case .sessionExpired(let peerID):\n return \"Session expired for peer: \\(sanitize(peerID))\"\n case .authenticationFailed(let peerID):\n return \"Authentication failed for peer: \\(sanitize(peerID))\"\n }\n }\n }\n \n // MARK: - Public Logging Methods\n \n /// Log a security event\n static func logSecurityEvent(_ event: SecurityEvent, level: LogLevel = .info, \n file: String = #file, line: Int = #line, function: String = #function) {\n let location = formatLocation(file: file, line: line, function: function)\n let message = \"\\(location) \\(event.message)\"\n \n #if DEBUG\n os_log(\"%{public}@\", log: security, type: level.osLogType, message)\n #else\n // In release, use private logging to prevent sensitive data exposure\n os_log(\"%{private}@\", log: security, type: level.osLogType, message)\n #endif\n }\n \n /// Log general messages with automatic sensitive data filtering\n static func log(_ message: String, category: OSLog = noise, level: LogLevel = .debug,\n file: String = #file, line: Int = #line, function: String = #function) {\n let location = formatLocation(file: file, line: line, function: function)\n let sanitized = sanitize(\"\\(location) \\(message)\")\n \n #if DEBUG\n os_log(\"%{public}@\", log: category, type: level.osLogType, sanitized)\n #else\n // In release builds, only log non-debug messages\n if level != .debug {\n os_log(\"%{private}@\", log: category, type: level.osLogType, sanitized)\n }\n #endif\n }\n \n /// Log errors with context\n static func logError(_ error: Error, context: String, category: OSLog = noise,\n file: String = #file, line: Int = #line, function: String = #function) {\n let location = formatLocation(file: file, line: line, function: function)\n let sanitized = sanitize(context)\n let errorDesc = sanitize(error.localizedDescription)\n \n #if DEBUG\n os_log(\"%{public}@ Error in %{public}@: %{public}@\", log: category, type: .error, location, sanitized, errorDesc)\n #else\n os_log(\"%{private}@ Error in %{private}@: %{private}@\", log: category, type: .error, location, sanitized, errorDesc)\n #endif\n }\n \n // MARK: - Private Helpers\n \n /// Format location information for logging\n private static func formatLocation(file: String, line: Int, function: String) -> String {\n let fileName = (file as NSString).lastPathComponent\n let timestamp = timestampFormatter.string(from: Date())\n return \"[\\(timestamp)] [\\(fileName):\\(line) \\(function)]\"\n }\n \n /// Sanitize strings to remove potentially sensitive data\n private static func sanitize(_ input: String) -> String {\n let key = input as NSString\n \n // Check cache first\n var cachedValue: String?\n cacheQueue.sync {\n cachedValue = sanitizationCache.object(forKey: key) as String?\n }\n \n if let cached = cachedValue {\n return cached\n }\n \n // Perform sanitization\n var sanitized = input\n \n // Remove full fingerprints (keep first 8 chars for debugging)\n sanitized = sanitized.replacing(fingerprintPattern) { match in\n let fingerprint = String(match.output)\n return String(fingerprint.prefix(8)) + \"...\"\n }\n \n // Remove base64 encoded data that might be keys\n sanitized = sanitized.replacing(base64Pattern) { _ in\n \"\"\n }\n \n // Remove potential passwords (assuming they're in quotes or after \"password:\")\n sanitized = sanitized.replacing(passwordPattern) { _ in\n \"password: \"\n }\n \n // Truncate peer IDs to first 8 characters\n sanitized = sanitized.replacing(peerIDPattern) { match in\n \"peerID: \\(match.1)...\"\n }\n \n // Cache the result\n cacheQueue.async(flags: .barrier) {\n sanitizationCache.setObject(sanitized as NSString, forKey: key)\n }\n \n return sanitized\n }\n \n /// Sanitize individual values\n private static func sanitize(_ value: T) -> String {\n let stringValue = String(describing: value)\n return sanitize(stringValue)\n }\n}\n\n// MARK: - Convenience Extensions\n\nextension SecureLogger {\n \n /// Log handshake events\n static func logHandshake(_ phase: String, peerID: String, success: Bool = true,\n file: String = #file, line: Int = #line, function: String = #function) {\n if success {\n log(\"Handshake \\(phase) with peer: \\(peerID)\", category: session, level: .info,\n file: file, line: line, function: function)\n } else {\n log(\"Handshake \\(phase) failed with peer: \\(peerID)\", category: session, level: .warning,\n file: file, line: line, function: function)\n }\n }\n \n /// Log encryption operations\n static func logEncryption(_ operation: String, success: Bool = true,\n file: String = #file, line: Int = #line, function: String = #function) {\n let level: LogLevel = success ? .debug : .error\n log(\"Encryption operation '\\(operation)' \\(success ? \"succeeded\" : \"failed\")\", \n category: encryption, level: level, file: file, line: line, function: function)\n }\n \n /// Log key management operations\n static func logKeyOperation(_ operation: String, keyType: String, success: Bool = true,\n file: String = #file, line: Int = #line, function: String = #function) {\n let level: LogLevel = success ? .info : .error\n log(\"Key operation '\\(operation)' for \\(keyType) \\(success ? \"succeeded\" : \"failed\")\", \n category: keychain, level: level, file: file, line: line, function: function)\n }\n}\n\n// MARK: - Migration Helper\n\n/// Helper to migrate from print statements to SecureLogger\n/// Usage: Replace print(...) with secureLog(...)\nfunc secureLog(_ items: Any..., separator: String = \" \", terminator: String = \"\\n\",\n file: String = #file, line: Int = #line, function: String = #function) {\n #if DEBUG\n let message = items.map { String(describing: $0) }.joined(separator: separator)\n SecureLogger.log(message, level: .debug, file: file, line: line, function: function)\n #endif\n}\n"], ["/bitchat/bitchat/Identity/SecureIdentityStateManager.swift", "//\n// SecureIdentityStateManager.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # SecureIdentityStateManager\n///\n/// Manages the persistent storage and retrieval of identity mappings with\n/// encryption at rest. This singleton service maintains the relationship between\n/// ephemeral peer IDs, cryptographic fingerprints, and social identities.\n///\n/// ## Overview\n/// The SecureIdentityStateManager provides a secure, privacy-preserving way to\n/// maintain identity relationships across app launches. It implements:\n/// - Encrypted storage of identity mappings\n/// - In-memory caching for performance\n/// - Thread-safe access patterns\n/// - Automatic debounced persistence\n///\n/// ## Architecture\n/// The manager operates at three levels:\n/// 1. **In-Memory State**: Fast access to active identities\n/// 2. **Encrypted Cache**: Persistent storage in Keychain\n/// 3. **Privacy Controls**: User-configurable persistence settings\n///\n/// ## Security Features\n///\n/// ### Encryption at Rest\n/// - Identity cache encrypted with AES-GCM\n/// - Unique 256-bit encryption key per device\n/// - Key stored separately in Keychain\n/// - No plaintext identity data on disk\n///\n/// ### Privacy by Design\n/// - Persistence is optional (user-controlled)\n/// - Minimal data retention\n/// - No cloud sync or backup\n/// - Automatic cleanup of stale entries\n///\n/// ### Thread Safety\n/// - Concurrent read access via GCD barriers\n/// - Write operations serialized\n/// - Atomic state updates\n/// - No data races or corruption\n///\n/// ## Data Model\n/// Manages three types of identity data:\n/// 1. **Ephemeral Sessions**: Current peer connections\n/// 2. **Cryptographic Identities**: Public keys and fingerprints\n/// 3. **Social Identities**: User-assigned names and trust\n///\n/// ## Persistence Strategy\n/// - Changes batched and debounced (2-second window)\n/// - Automatic save on app termination\n/// - Crash-resistant with atomic writes\n/// - Migration support for schema changes\n///\n/// ## Usage Patterns\n/// ```swift\n/// // Register a new peer identity\n/// manager.registerPeerIdentity(peerID, publicKey, fingerprint)\n/// \n/// // Update social identity\n/// manager.updateSocialIdentity(fingerprint, nickname, trustLevel)\n/// \n/// // Query identity\n/// let identity = manager.resolvePeerIdentity(peerID)\n/// ```\n///\n/// ## Performance Optimizations\n/// - In-memory cache eliminates Keychain roundtrips\n/// - Debounced saves reduce I/O operations\n/// - Efficient data structures for lookups\n/// - Background queue for expensive operations\n///\n/// ## Privacy Considerations\n/// - Users can disable all persistence\n/// - Identity cache can be wiped instantly\n/// - No analytics or telemetry\n/// - Ephemeral mode for high-risk users\n///\n/// ## Future Enhancements\n/// - Selective identity export\n/// - Cross-device identity sync (optional)\n/// - Identity attestation support\n/// - Advanced conflict resolution\n///\n\nimport Foundation\nimport CryptoKit\n\n/// Singleton manager for secure identity state persistence and retrieval.\n/// Provides thread-safe access to identity mappings with encryption at rest.\n/// All identity data is stored encrypted in the device Keychain for security.\nclass SecureIdentityStateManager {\n static let shared = SecureIdentityStateManager()\n \n private let keychain = KeychainManager.shared\n private let cacheKey = \"bitchat.identityCache.v2\"\n private let encryptionKeyName = \"identityCacheEncryptionKey\"\n \n // In-memory state\n private var ephemeralSessions: [String: EphemeralIdentity] = [:]\n private var cryptographicIdentities: [String: CryptographicIdentity] = [:]\n private var cache: IdentityCache = IdentityCache()\n \n // Pending actions before handshake\n private var pendingActions: [String: PendingActions] = [:]\n \n // Thread safety\n private let queue = DispatchQueue(label: \"bitchat.identity.state\", attributes: .concurrent)\n \n // Debouncing for keychain saves\n private var saveTimer: Timer?\n private let saveDebounceInterval: TimeInterval = 2.0 // Save at most once every 2 seconds\n private var pendingSave = false\n \n // Encryption key\n private let encryptionKey: SymmetricKey\n \n private init() {\n // Generate or retrieve encryption key from keychain\n let loadedKey: SymmetricKey\n \n // Try to load from keychain\n if let keyData = keychain.getIdentityKey(forKey: encryptionKeyName) {\n loadedKey = SymmetricKey(data: keyData)\n SecureLogger.logKeyOperation(\"load\", keyType: \"identity cache encryption key\", success: true)\n }\n // Generate new key if needed\n else {\n loadedKey = SymmetricKey(size: .bits256)\n let keyData = loadedKey.withUnsafeBytes { Data($0) }\n // Save to keychain\n let saved = keychain.saveIdentityKey(keyData, forKey: encryptionKeyName)\n SecureLogger.logKeyOperation(\"generate\", keyType: \"identity cache encryption key\", success: saved)\n }\n \n self.encryptionKey = loadedKey\n \n // Load identity cache on init\n loadIdentityCache()\n }\n \n // MARK: - Secure Loading/Saving\n \n func loadIdentityCache() {\n guard let encryptedData = keychain.getIdentityKey(forKey: cacheKey) else {\n // No existing cache, start fresh\n return\n }\n \n do {\n let sealedBox = try AES.GCM.SealedBox(combined: encryptedData)\n let decryptedData = try AES.GCM.open(sealedBox, using: encryptionKey)\n cache = try JSONDecoder().decode(IdentityCache.self, from: decryptedData)\n } catch {\n // Log error but continue with empty cache\n SecureLogger.logError(error, context: \"Failed to load identity cache\", category: SecureLogger.security)\n }\n }\n \n deinit {\n // Force save any pending changes\n forceSave()\n }\n \n func saveIdentityCache() {\n // Mark that we need to save\n pendingSave = true\n \n // Cancel any existing timer\n saveTimer?.invalidate()\n \n // Schedule a new save after the debounce interval\n saveTimer = Timer.scheduledTimer(withTimeInterval: saveDebounceInterval, repeats: false) { [weak self] _ in\n self?.performSave()\n }\n }\n \n private func performSave() {\n guard pendingSave else { return }\n pendingSave = false\n \n do {\n let data = try JSONEncoder().encode(cache)\n let sealedBox = try AES.GCM.seal(data, using: encryptionKey)\n let saved = keychain.saveIdentityKey(sealedBox.combined!, forKey: cacheKey)\n if saved {\n SecureLogger.log(\"Identity cache saved to keychain\", category: SecureLogger.security, level: .debug)\n }\n } catch {\n SecureLogger.logError(error, context: \"Failed to save identity cache\", category: SecureLogger.security)\n }\n }\n \n // Force immediate save (for app termination)\n func forceSave() {\n saveTimer?.invalidate()\n if pendingSave {\n performSave()\n }\n }\n \n // MARK: - Identity Resolution\n \n func resolveIdentity(peerID: String, claimedNickname: String) -> IdentityHint {\n queue.sync {\n // Check if we have candidates based on nickname\n if let fingerprints = cache.nicknameIndex[claimedNickname] {\n if fingerprints.count == 1 {\n return .likelyKnown(fingerprint: fingerprints.first!)\n } else {\n return .ambiguous(candidates: fingerprints)\n }\n }\n return .unknown\n }\n }\n \n // MARK: - Social Identity Management\n \n func getSocialIdentity(for fingerprint: String) -> SocialIdentity? {\n queue.sync {\n return cache.socialIdentities[fingerprint]\n }\n }\n \n func getAllSocialIdentities() -> [SocialIdentity] {\n queue.sync {\n return Array(cache.socialIdentities.values)\n }\n }\n \n func updateSocialIdentity(_ identity: SocialIdentity) {\n queue.async(flags: .barrier) {\n self.cache.socialIdentities[identity.fingerprint] = identity\n \n // Update nickname index\n if let existingIdentity = self.cache.socialIdentities[identity.fingerprint] {\n // Remove old nickname from index if changed\n if existingIdentity.claimedNickname != identity.claimedNickname {\n self.cache.nicknameIndex[existingIdentity.claimedNickname]?.remove(identity.fingerprint)\n if self.cache.nicknameIndex[existingIdentity.claimedNickname]?.isEmpty == true {\n self.cache.nicknameIndex.removeValue(forKey: existingIdentity.claimedNickname)\n }\n }\n }\n \n // Add new nickname to index\n if self.cache.nicknameIndex[identity.claimedNickname] == nil {\n self.cache.nicknameIndex[identity.claimedNickname] = Set()\n }\n self.cache.nicknameIndex[identity.claimedNickname]?.insert(identity.fingerprint)\n \n // Save to keychain\n self.saveIdentityCache()\n }\n }\n \n // MARK: - Favorites Management\n \n func getFavorites() -> Set {\n queue.sync {\n let favorites = cache.socialIdentities.values\n .filter { $0.isFavorite }\n .map { $0.fingerprint }\n return Set(favorites)\n }\n }\n \n func setFavorite(_ fingerprint: String, isFavorite: Bool) {\n queue.async(flags: .barrier) {\n if var identity = self.cache.socialIdentities[fingerprint] {\n identity.isFavorite = isFavorite\n self.cache.socialIdentities[fingerprint] = identity\n } else {\n // Create new social identity for this fingerprint\n let newIdentity = SocialIdentity(\n fingerprint: fingerprint,\n localPetname: nil,\n claimedNickname: \"Unknown\",\n trustLevel: .unknown,\n isFavorite: isFavorite,\n isBlocked: false,\n notes: nil\n )\n self.cache.socialIdentities[fingerprint] = newIdentity\n }\n self.saveIdentityCache()\n }\n }\n \n func isFavorite(fingerprint: String) -> Bool {\n queue.sync {\n return cache.socialIdentities[fingerprint]?.isFavorite ?? false\n }\n }\n \n // MARK: - Blocked Users Management\n \n func isBlocked(fingerprint: String) -> Bool {\n queue.sync {\n return cache.socialIdentities[fingerprint]?.isBlocked ?? false\n }\n }\n \n func setBlocked(_ fingerprint: String, isBlocked: Bool) {\n SecureLogger.log(\"User \\(isBlocked ? \"blocked\" : \"unblocked\"): \\(fingerprint)\", category: SecureLogger.security, level: .info)\n \n queue.async(flags: .barrier) {\n if var identity = self.cache.socialIdentities[fingerprint] {\n identity.isBlocked = isBlocked\n if isBlocked {\n identity.isFavorite = false // Can't be both favorite and blocked\n }\n self.cache.socialIdentities[fingerprint] = identity\n } else {\n // Create new social identity for this fingerprint\n let newIdentity = SocialIdentity(\n fingerprint: fingerprint,\n localPetname: nil,\n claimedNickname: \"Unknown\",\n trustLevel: .unknown,\n isFavorite: false,\n isBlocked: isBlocked,\n notes: nil\n )\n self.cache.socialIdentities[fingerprint] = newIdentity\n }\n self.saveIdentityCache()\n }\n }\n \n // MARK: - Ephemeral Session Management\n \n func registerEphemeralSession(peerID: String, handshakeState: HandshakeState = .none) {\n queue.async(flags: .barrier) {\n self.ephemeralSessions[peerID] = EphemeralIdentity(\n peerID: peerID,\n sessionStart: Date(),\n handshakeState: handshakeState\n )\n }\n }\n \n func updateHandshakeState(peerID: String, state: HandshakeState) {\n queue.async(flags: .barrier) {\n self.ephemeralSessions[peerID]?.handshakeState = state\n \n // If handshake completed, update last interaction\n if case .completed(let fingerprint) = state {\n self.cache.lastInteractions[fingerprint] = Date()\n self.saveIdentityCache()\n }\n }\n }\n \n func getHandshakeState(peerID: String) -> HandshakeState? {\n queue.sync {\n return ephemeralSessions[peerID]?.handshakeState\n }\n }\n \n // MARK: - Pending Actions\n \n func setPendingAction(peerID: String, action: PendingActions) {\n queue.async(flags: .barrier) {\n self.pendingActions[peerID] = action\n }\n }\n \n func applyPendingActions(peerID: String, fingerprint: String) {\n queue.async(flags: .barrier) {\n guard let actions = self.pendingActions[peerID] else { return }\n \n // Get or create social identity\n var identity = self.cache.socialIdentities[fingerprint] ?? SocialIdentity(\n fingerprint: fingerprint,\n localPetname: nil,\n claimedNickname: \"Unknown\",\n trustLevel: .unknown,\n isFavorite: false,\n isBlocked: false,\n notes: nil\n )\n \n // Apply pending actions\n if let toggleFavorite = actions.toggleFavorite {\n identity.isFavorite = toggleFavorite\n }\n if let trustLevel = actions.setTrustLevel {\n identity.trustLevel = trustLevel\n }\n if let petname = actions.setPetname {\n identity.localPetname = petname\n }\n \n // Save updated identity\n self.cache.socialIdentities[fingerprint] = identity\n self.pendingActions.removeValue(forKey: peerID)\n self.saveIdentityCache()\n }\n }\n \n // MARK: - Cleanup\n \n func clearAllIdentityData() {\n SecureLogger.log(\"Clearing all identity data\", category: SecureLogger.security, level: .warning)\n \n queue.async(flags: .barrier) {\n self.cache = IdentityCache()\n self.ephemeralSessions.removeAll()\n self.cryptographicIdentities.removeAll()\n self.pendingActions.removeAll()\n \n // Delete from keychain\n let deleted = self.keychain.deleteIdentityKey(forKey: self.cacheKey)\n SecureLogger.logKeyOperation(\"delete\", keyType: \"identity cache\", success: deleted)\n }\n }\n \n func removeEphemeralSession(peerID: String) {\n queue.async(flags: .barrier) {\n self.ephemeralSessions.removeValue(forKey: peerID)\n self.pendingActions.removeValue(forKey: peerID)\n }\n }\n \n // MARK: - Verification\n \n func setVerified(fingerprint: String, verified: Bool) {\n SecureLogger.log(\"Fingerprint \\(verified ? \"verified\" : \"unverified\"): \\(fingerprint)\", category: SecureLogger.security, level: .info)\n \n queue.async(flags: .barrier) {\n if verified {\n self.cache.verifiedFingerprints.insert(fingerprint)\n } else {\n self.cache.verifiedFingerprints.remove(fingerprint)\n }\n \n // Update trust level if social identity exists\n if var identity = self.cache.socialIdentities[fingerprint] {\n identity.trustLevel = verified ? .verified : .casual\n self.cache.socialIdentities[fingerprint] = identity\n }\n \n self.saveIdentityCache()\n }\n }\n \n func isVerified(fingerprint: String) -> Bool {\n queue.sync {\n return cache.verifiedFingerprints.contains(fingerprint)\n }\n }\n \n func getVerifiedFingerprints() -> Set {\n queue.sync {\n return cache.verifiedFingerprints\n }\n }\n}"], ["/bitchat/bitchat/BitchatApp.swift", "//\n// BitchatApp.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport SwiftUI\nimport UserNotifications\n\n@main\nstruct BitchatApp: App {\n @StateObject private var chatViewModel = ChatViewModel()\n #if os(iOS)\n @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate\n #elseif os(macOS)\n @NSApplicationDelegateAdaptor(MacAppDelegate.self) var appDelegate\n #endif\n \n init() {\n UNUserNotificationCenter.current().delegate = NotificationDelegate.shared\n }\n \n var body: some Scene {\n WindowGroup {\n ContentView()\n .environmentObject(chatViewModel)\n .onAppear {\n NotificationDelegate.shared.chatViewModel = chatViewModel\n #if os(iOS)\n appDelegate.chatViewModel = chatViewModel\n #elseif os(macOS)\n appDelegate.chatViewModel = chatViewModel\n #endif\n // Check for shared content\n checkForSharedContent()\n }\n .onOpenURL { url in\n handleURL(url)\n }\n #if os(iOS)\n .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in\n // Check for shared content when app becomes active\n checkForSharedContent()\n }\n #endif\n }\n #if os(macOS)\n .windowStyle(.hiddenTitleBar)\n .windowResizability(.contentSize)\n #endif\n }\n \n private func handleURL(_ url: URL) {\n if url.scheme == \"bitchat\" && url.host == \"share\" {\n // Handle shared content\n checkForSharedContent()\n }\n }\n \n private func checkForSharedContent() {\n // Check app group for shared content from extension\n guard let userDefaults = UserDefaults(suiteName: \"group.chat.bitchat\") else {\n return\n }\n \n guard let sharedContent = userDefaults.string(forKey: \"sharedContent\"),\n let sharedDate = userDefaults.object(forKey: \"sharedContentDate\") as? Date else {\n return\n }\n \n // Only process if shared within last 30 seconds\n if Date().timeIntervalSince(sharedDate) < 30 {\n let contentType = userDefaults.string(forKey: \"sharedContentType\") ?? \"text\"\n \n // Clear the shared content\n userDefaults.removeObject(forKey: \"sharedContent\")\n userDefaults.removeObject(forKey: \"sharedContentType\")\n userDefaults.removeObject(forKey: \"sharedContentDate\")\n userDefaults.synchronize()\n \n // Show notification about shared content\n DispatchQueue.main.async {\n // Add system message about sharing\n let systemMessage = BitchatMessage(\n sender: \"system\",\n content: \"preparing to share \\(contentType)...\",\n timestamp: Date(),\n isRelay: false\n )\n self.chatViewModel.messages.append(systemMessage)\n }\n \n // Send the shared content after a short delay\n DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {\n if contentType == \"url\" {\n // Try to parse as JSON first\n if let data = sharedContent.data(using: .utf8),\n let urlData = try? JSONSerialization.jsonObject(with: data) as? [String: String],\n let url = urlData[\"url\"] {\n // Send plain URL\n self.chatViewModel.sendMessage(url)\n } else {\n // Fallback to simple URL\n self.chatViewModel.sendMessage(sharedContent)\n }\n } else {\n self.chatViewModel.sendMessage(sharedContent)\n }\n }\n }\n }\n}\n\n#if os(iOS)\nclass AppDelegate: NSObject, UIApplicationDelegate {\n weak var chatViewModel: ChatViewModel?\n \n func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {\n return true\n }\n}\n#endif\n\n#if os(macOS)\nimport AppKit\n\nclass MacAppDelegate: NSObject, NSApplicationDelegate {\n weak var chatViewModel: ChatViewModel?\n \n func applicationWillTerminate(_ notification: Notification) {\n chatViewModel?.applicationWillTerminate()\n }\n \n func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {\n return true\n }\n}\n#endif\n\nclass NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {\n static let shared = NotificationDelegate()\n weak var chatViewModel: ChatViewModel?\n \n func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {\n let identifier = response.notification.request.identifier\n let userInfo = response.notification.request.content.userInfo\n \n // Check if this is a private message notification\n if identifier.hasPrefix(\"private-\") {\n // Get peer ID from userInfo\n if let peerID = userInfo[\"peerID\"] as? String {\n DispatchQueue.main.async {\n self.chatViewModel?.startPrivateChat(with: peerID)\n }\n }\n }\n \n completionHandler()\n }\n \n func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {\n let identifier = notification.request.identifier\n let userInfo = notification.request.content.userInfo\n \n // Check if this is a private message notification\n if identifier.hasPrefix(\"private-\") {\n // Get peer ID from userInfo\n if let peerID = userInfo[\"peerID\"] as? String {\n // Don't show notification if the private chat is already open\n if chatViewModel?.selectedPrivateChatPeer == peerID {\n completionHandler([])\n return\n }\n }\n }\n \n // Show notification in all other cases\n completionHandler([.banner, .sound])\n }\n}\n\nextension String {\n var nilIfEmpty: String? {\n self.isEmpty ? nil : self\n }\n}"], ["/bitchat/bitchat/Protocols/BitchatProtocol.swift", "//\n// BitchatProtocol.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # BitchatProtocol\n///\n/// Defines the application-layer protocol for BitChat mesh networking, including\n/// message types, packet structures, and encoding/decoding logic.\n///\n/// ## Overview\n/// BitchatProtocol implements a binary protocol optimized for Bluetooth LE's\n/// constrained bandwidth and MTU limitations. It provides:\n/// - Efficient binary message encoding\n/// - Message fragmentation for large payloads\n/// - TTL-based routing for mesh networks\n/// - Privacy features like padding and timing obfuscation\n/// - Integration points for end-to-end encryption\n///\n/// ## Protocol Design\n/// The protocol uses a compact binary format to minimize overhead:\n/// - 1-byte message type identifier\n/// - Variable-length fields with length prefixes\n/// - Network byte order (big-endian) for multi-byte values\n/// - PKCS#7-style padding for privacy\n///\n/// ## Message Flow\n/// 1. **Creation**: Messages are created with type, content, and metadata\n/// 2. **Encoding**: Converted to binary format with proper field ordering\n/// 3. **Fragmentation**: Split if larger than BLE MTU (512 bytes)\n/// 4. **Transmission**: Sent via BluetoothMeshService\n/// 5. **Routing**: Relayed by intermediate nodes (TTL decrements)\n/// 6. **Reassembly**: Fragments collected and reassembled\n/// 7. **Decoding**: Binary data parsed back to message objects\n///\n/// ## Security Considerations\n/// - Message padding obscures actual content length\n/// - Timing obfuscation prevents traffic analysis\n/// - Integration with Noise Protocol for E2E encryption\n/// - No persistent identifiers in protocol headers\n///\n/// ## Message Types\n/// - **Announce/Leave**: Peer presence notifications\n/// - **Message**: User chat messages (broadcast or directed)\n/// - **Fragment**: Multi-part message handling\n/// - **Delivery/Read**: Message acknowledgments\n/// - **Noise**: Encrypted channel establishment\n/// - **Version**: Protocol compatibility negotiation\n///\n/// ## Future Extensions\n/// The protocol is designed to be extensible:\n/// - Reserved message type ranges for future use\n/// - Version negotiation for backward compatibility\n/// - Optional fields for new features\n///\n\nimport Foundation\nimport CryptoKit\n\n// MARK: - Message Padding\n\n/// Provides privacy-preserving message padding to obscure actual content length.\n/// Uses PKCS#7-style padding with random bytes to prevent traffic analysis.\nstruct MessagePadding {\n // Standard block sizes for padding\n static let blockSizes = [256, 512, 1024, 2048]\n \n // Add PKCS#7-style padding to reach target size\n static func pad(_ data: Data, toSize targetSize: Int) -> Data {\n guard data.count < targetSize else { return data }\n \n let paddingNeeded = targetSize - data.count\n \n // PKCS#7 only supports padding up to 255 bytes\n // If we need more padding than that, don't pad - return original data\n guard paddingNeeded <= 255 else { return data }\n \n var padded = data\n \n // Standard PKCS#7 padding\n var randomBytes = [UInt8](repeating: 0, count: paddingNeeded - 1)\n _ = SecRandomCopyBytes(kSecRandomDefault, paddingNeeded - 1, &randomBytes)\n padded.append(contentsOf: randomBytes)\n padded.append(UInt8(paddingNeeded))\n \n return padded\n }\n \n // Remove padding from data\n static func unpad(_ data: Data) -> Data {\n guard !data.isEmpty else { return data }\n \n // Last byte tells us how much padding to remove\n let paddingLength = Int(data[data.count - 1])\n guard paddingLength > 0 && paddingLength <= data.count else { \n // Debug logging for 243-byte packets\n if data.count == 243 {\n }\n return data \n }\n \n let result = data.prefix(data.count - paddingLength)\n \n // Debug logging for 243-byte packets\n if data.count == 243 {\n }\n \n return result\n }\n \n // Find optimal block size for data\n static func optimalBlockSize(for dataSize: Int) -> Int {\n // Account for encryption overhead (~16 bytes for AES-GCM tag)\n let totalSize = dataSize + 16\n \n // Find smallest block that fits\n for blockSize in blockSizes {\n if totalSize <= blockSize {\n return blockSize\n }\n }\n \n // For very large messages, just use the original size\n // (will be fragmented anyway)\n return dataSize\n }\n}\n\n// MARK: - Message Types\n\n/// Defines all message types in the BitChat protocol.\n/// Each type has a unique identifier for efficient binary encoding.\n/// Types are grouped by function: user messages, protocol control, encryption, etc.\nenum MessageType: UInt8 {\n case announce = 0x01\n case leave = 0x03\n case message = 0x04 // All user messages (private and broadcast)\n case fragmentStart = 0x05\n case fragmentContinue = 0x06\n case fragmentEnd = 0x07\n case deliveryAck = 0x0A // Acknowledge message received\n case deliveryStatusRequest = 0x0B // Request delivery status update\n case readReceipt = 0x0C // Message has been read/viewed\n \n // Noise Protocol messages\n case noiseHandshakeInit = 0x10 // Noise handshake initiation\n case noiseHandshakeResp = 0x11 // Noise handshake response\n case noiseEncrypted = 0x12 // Noise encrypted transport message\n case noiseIdentityAnnounce = 0x13 // Announce static public key for discovery\n \n // Protocol version negotiation\n case versionHello = 0x20 // Initial version announcement\n case versionAck = 0x21 // Version acknowledgment\n \n // Protocol-level acknowledgments\n case protocolAck = 0x22 // Generic protocol acknowledgment\n case protocolNack = 0x23 // Negative acknowledgment (failure)\n case systemValidation = 0x24 // Session validation ping\n case handshakeRequest = 0x25 // Request handshake for pending messages\n \n var description: String {\n switch self {\n case .announce: return \"announce\"\n case .leave: return \"leave\"\n case .message: return \"message\"\n case .fragmentStart: return \"fragmentStart\"\n case .fragmentContinue: return \"fragmentContinue\"\n case .fragmentEnd: return \"fragmentEnd\"\n case .deliveryAck: return \"deliveryAck\"\n case .deliveryStatusRequest: return \"deliveryStatusRequest\"\n case .readReceipt: return \"readReceipt\"\n case .noiseHandshakeInit: return \"noiseHandshakeInit\"\n case .noiseHandshakeResp: return \"noiseHandshakeResp\"\n case .noiseEncrypted: return \"noiseEncrypted\"\n case .noiseIdentityAnnounce: return \"noiseIdentityAnnounce\"\n case .versionHello: return \"versionHello\"\n case .versionAck: return \"versionAck\"\n case .protocolAck: return \"protocolAck\"\n case .protocolNack: return \"protocolNack\"\n case .systemValidation: return \"systemValidation\"\n case .handshakeRequest: return \"handshakeRequest\"\n }\n }\n}\n\n// MARK: - Handshake State\n\n// Lazy handshake state tracking\nenum LazyHandshakeState {\n case none // No session, no handshake attempted\n case handshakeQueued // User action requires handshake\n case handshaking // Currently in handshake process\n case established // Session ready for use\n case failed(Error) // Handshake failed\n}\n\n// MARK: - Special Recipients\n\n/// Defines special recipient identifiers used in the protocol.\n/// These magic values indicate broadcast or system-level recipients\n/// rather than specific peer IDs.\nstruct SpecialRecipients {\n static let broadcast = Data(repeating: 0xFF, count: 8) // All 0xFF = broadcast\n}\n\n// MARK: - Core Protocol Structures\n\n/// The core packet structure for all BitChat protocol messages.\n/// Encapsulates all data needed for routing through the mesh network,\n/// including TTL for hop limiting and optional encryption.\n/// - Note: Packets larger than BLE MTU (512 bytes) are automatically fragmented\nstruct BitchatPacket: Codable {\n let version: UInt8\n let type: UInt8\n let senderID: Data\n let recipientID: Data?\n let timestamp: UInt64\n let payload: Data\n let signature: Data?\n var ttl: UInt8\n \n init(type: UInt8, senderID: Data, recipientID: Data?, timestamp: UInt64, payload: Data, signature: Data?, ttl: UInt8) {\n self.version = 1\n self.type = type\n self.senderID = senderID\n self.recipientID = recipientID\n self.timestamp = timestamp\n self.payload = payload\n self.signature = signature\n self.ttl = ttl\n }\n \n // Convenience initializer for new binary format\n init(type: UInt8, ttl: UInt8, senderID: String, payload: Data) {\n self.version = 1\n self.type = type\n // Convert hex string peer ID to binary data (8 bytes)\n var senderData = Data()\n var tempID = senderID\n while tempID.count >= 2 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n senderData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n self.senderID = senderData\n self.recipientID = nil\n self.timestamp = UInt64(Date().timeIntervalSince1970 * 1000) // milliseconds\n self.payload = payload\n self.signature = nil\n self.ttl = ttl\n }\n \n var data: Data? {\n BinaryProtocol.encode(self)\n }\n \n func toBinaryData() -> Data? {\n BinaryProtocol.encode(self)\n }\n \n static func from(_ data: Data) -> BitchatPacket? {\n BinaryProtocol.decode(data)\n }\n}\n\n// MARK: - Delivery Acknowledgments\n\n/// Acknowledgment sent when a message is successfully delivered to a recipient.\n/// Provides delivery confirmation for reliable messaging and UI feedback.\n/// - Note: Only sent for direct messages, not broadcasts\nstruct DeliveryAck: Codable {\n let originalMessageID: String\n let ackID: String\n let recipientID: String // Who received it\n let recipientNickname: String\n let timestamp: Date\n let hopCount: UInt8 // How many hops to reach recipient\n \n init(originalMessageID: String, recipientID: String, recipientNickname: String, hopCount: UInt8) {\n self.originalMessageID = originalMessageID\n self.ackID = UUID().uuidString\n self.recipientID = recipientID\n self.recipientNickname = recipientNickname\n self.timestamp = Date()\n self.hopCount = hopCount\n }\n \n // For binary decoding\n private init(originalMessageID: String, ackID: String, recipientID: String, recipientNickname: String, timestamp: Date, hopCount: UInt8) {\n self.originalMessageID = originalMessageID\n self.ackID = ackID\n self.recipientID = recipientID\n self.recipientNickname = recipientNickname\n self.timestamp = timestamp\n self.hopCount = hopCount\n }\n \n func encode() -> Data? {\n try? JSONEncoder().encode(self)\n }\n \n static func decode(from data: Data) -> DeliveryAck? {\n try? JSONDecoder().decode(DeliveryAck.self, from: data)\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUUID(originalMessageID)\n data.appendUUID(ackID)\n // RecipientID as 8-byte hex string\n var recipientData = Data()\n var tempID = recipientID\n while tempID.count >= 2 && recipientData.count < 8 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n recipientData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n while recipientData.count < 8 {\n recipientData.append(0)\n }\n data.append(recipientData)\n data.appendUInt8(hopCount)\n data.appendDate(timestamp)\n data.appendString(recipientNickname)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> DeliveryAck? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size: 2 UUIDs (32) + recipientID (8) + hopCount (1) + timestamp (8) + min nickname\n guard dataCopy.count >= 50 else { return nil }\n \n var offset = 0\n \n guard let originalMessageID = dataCopy.readUUID(at: &offset),\n let ackID = dataCopy.readUUID(at: &offset) else { return nil }\n \n guard let recipientIDData = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n let recipientID = recipientIDData.hexEncodedString()\n \n guard let hopCount = dataCopy.readUInt8(at: &offset),\n let timestamp = dataCopy.readDate(at: &offset),\n let recipientNickname = dataCopy.readString(at: &offset) else { return nil }\n \n return DeliveryAck(originalMessageID: originalMessageID,\n ackID: ackID,\n recipientID: recipientID,\n recipientNickname: recipientNickname,\n timestamp: timestamp,\n hopCount: hopCount)\n }\n}\n\n// MARK: - Read Receipts\n\n// Read receipt structure\nstruct ReadReceipt: Codable {\n let originalMessageID: String\n let receiptID: String\n let readerID: String // Who read it\n let readerNickname: String\n let timestamp: Date\n \n init(originalMessageID: String, readerID: String, readerNickname: String) {\n self.originalMessageID = originalMessageID\n self.receiptID = UUID().uuidString\n self.readerID = readerID\n self.readerNickname = readerNickname\n self.timestamp = Date()\n }\n \n // For binary decoding\n private init(originalMessageID: String, receiptID: String, readerID: String, readerNickname: String, timestamp: Date) {\n self.originalMessageID = originalMessageID\n self.receiptID = receiptID\n self.readerID = readerID\n self.readerNickname = readerNickname\n self.timestamp = timestamp\n }\n \n func encode() -> Data? {\n try? JSONEncoder().encode(self)\n }\n \n static func decode(from data: Data) -> ReadReceipt? {\n try? JSONDecoder().decode(ReadReceipt.self, from: data)\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUUID(originalMessageID)\n data.appendUUID(receiptID)\n // ReaderID as 8-byte hex string\n var readerData = Data()\n var tempID = readerID\n while tempID.count >= 2 && readerData.count < 8 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n readerData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n while readerData.count < 8 {\n readerData.append(0)\n }\n data.append(readerData)\n data.appendDate(timestamp)\n data.appendString(readerNickname)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> ReadReceipt? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size: 2 UUIDs (32) + readerID (8) + timestamp (8) + min nickname\n guard dataCopy.count >= 49 else { return nil }\n \n var offset = 0\n \n guard let originalMessageID = dataCopy.readUUID(at: &offset),\n let receiptID = dataCopy.readUUID(at: &offset) else { return nil }\n \n guard let readerIDData = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n let readerID = readerIDData.hexEncodedString()\n \n guard let timestamp = dataCopy.readDate(at: &offset),\n let readerNickname = dataCopy.readString(at: &offset) else { return nil }\n \n return ReadReceipt(originalMessageID: originalMessageID,\n receiptID: receiptID,\n readerID: readerID,\n readerNickname: readerNickname,\n timestamp: timestamp)\n }\n}\n\n// MARK: - Handshake Requests\n\n// Handshake request for pending messages\nstruct HandshakeRequest: Codable {\n let requestID: String\n let requesterID: String // Who needs the handshake\n let requesterNickname: String // Nickname of requester\n let targetID: String // Who should initiate handshake\n let pendingMessageCount: UInt8 // Number of messages queued\n let timestamp: Date\n \n init(requesterID: String, requesterNickname: String, targetID: String, pendingMessageCount: UInt8) {\n self.requestID = UUID().uuidString\n self.requesterID = requesterID\n self.requesterNickname = requesterNickname\n self.targetID = targetID\n self.pendingMessageCount = pendingMessageCount\n self.timestamp = Date()\n }\n \n // For binary decoding\n private init(requestID: String, requesterID: String, requesterNickname: String, targetID: String, pendingMessageCount: UInt8, timestamp: Date) {\n self.requestID = requestID\n self.requesterID = requesterID\n self.requesterNickname = requesterNickname\n self.targetID = targetID\n self.pendingMessageCount = pendingMessageCount\n self.timestamp = timestamp\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUUID(requestID)\n \n // RequesterID as 8-byte hex string\n var requesterData = Data()\n var tempID = requesterID\n while tempID.count >= 2 && requesterData.count < 8 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n requesterData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n while requesterData.count < 8 {\n requesterData.append(0)\n }\n data.append(requesterData)\n \n // TargetID as 8-byte hex string\n var targetData = Data()\n tempID = targetID\n while tempID.count >= 2 && targetData.count < 8 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n targetData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n while targetData.count < 8 {\n targetData.append(0)\n }\n data.append(targetData)\n \n data.appendUInt8(pendingMessageCount)\n data.appendDate(timestamp)\n data.appendString(requesterNickname)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> HandshakeRequest? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size: UUID (16) + requesterID (8) + targetID (8) + count (1) + timestamp (8) + min nickname\n guard dataCopy.count >= 42 else { return nil }\n \n var offset = 0\n \n guard let requestID = dataCopy.readUUID(at: &offset) else { return nil }\n \n guard let requesterIDData = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n let requesterID = requesterIDData.hexEncodedString()\n \n guard let targetIDData = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n let targetID = targetIDData.hexEncodedString()\n \n guard let pendingMessageCount = dataCopy.readUInt8(at: &offset),\n let timestamp = dataCopy.readDate(at: &offset),\n let requesterNickname = dataCopy.readString(at: &offset) else { return nil }\n \n return HandshakeRequest(requestID: requestID,\n requesterID: requesterID,\n requesterNickname: requesterNickname,\n targetID: targetID,\n pendingMessageCount: pendingMessageCount,\n timestamp: timestamp)\n }\n}\n\n// MARK: - Protocol Acknowledgments\n\n// Protocol-level acknowledgment for reliable delivery\nstruct ProtocolAck: Codable {\n let originalPacketID: String // ID of the packet being acknowledged\n let ackID: String // Unique ID for this ACK\n let senderID: String // Who sent the original packet\n let receiverID: String // Who received and is acknowledging\n let packetType: UInt8 // Type of packet being acknowledged\n let timestamp: Date // When ACK was generated\n let hopCount: UInt8 // Hops taken to reach receiver\n \n init(originalPacketID: String, senderID: String, receiverID: String, packetType: UInt8, hopCount: UInt8) {\n self.originalPacketID = originalPacketID\n self.ackID = UUID().uuidString\n self.senderID = senderID\n self.receiverID = receiverID\n self.packetType = packetType\n self.timestamp = Date()\n self.hopCount = hopCount\n }\n \n // Private init for binary decoding\n private init(originalPacketID: String, ackID: String, senderID: String, receiverID: String, \n packetType: UInt8, timestamp: Date, hopCount: UInt8) {\n self.originalPacketID = originalPacketID\n self.ackID = ackID\n self.senderID = senderID\n self.receiverID = receiverID\n self.packetType = packetType\n self.timestamp = timestamp\n self.hopCount = hopCount\n }\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUUID(originalPacketID)\n data.appendUUID(ackID)\n \n // Sender and receiver IDs as 8-byte hex strings\n data.append(Data(hexString: senderID) ?? Data(repeating: 0, count: 8))\n data.append(Data(hexString: receiverID) ?? Data(repeating: 0, count: 8))\n \n data.appendUInt8(packetType)\n data.appendUInt8(hopCount)\n data.appendDate(timestamp)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> ProtocolAck? {\n let dataCopy = Data(data)\n guard dataCopy.count >= 50 else { return nil } // 2 UUIDs + 2 IDs + type + hop + timestamp\n \n var offset = 0\n guard let originalPacketID = dataCopy.readUUID(at: &offset),\n let ackID = dataCopy.readUUID(at: &offset),\n let senderIDData = dataCopy.readFixedBytes(at: &offset, count: 8),\n let receiverIDData = dataCopy.readFixedBytes(at: &offset, count: 8),\n let packetType = dataCopy.readUInt8(at: &offset),\n let hopCount = dataCopy.readUInt8(at: &offset),\n let timestamp = dataCopy.readDate(at: &offset) else { return nil }\n \n let senderID = senderIDData.hexEncodedString()\n let receiverID = receiverIDData.hexEncodedString()\n \n return ProtocolAck(originalPacketID: originalPacketID,\n ackID: ackID,\n senderID: senderID,\n receiverID: receiverID,\n packetType: packetType,\n timestamp: timestamp,\n hopCount: hopCount)\n }\n}\n\n// Protocol-level negative acknowledgment\nstruct ProtocolNack: Codable {\n let originalPacketID: String // ID of the packet that failed\n let nackID: String // Unique ID for this NACK\n let senderID: String // Who sent the original packet\n let receiverID: String // Who is reporting the failure\n let packetType: UInt8 // Type of packet that failed\n let timestamp: Date // When NACK was generated\n let reason: String // Reason for failure\n let errorCode: UInt8 // Numeric error code\n \n // Error codes\n enum ErrorCode: UInt8 {\n case unknown = 0\n case checksumFailed = 1\n case decryptionFailed = 2\n case malformedPacket = 3\n case unsupportedVersion = 4\n case resourceExhausted = 5\n case routingFailed = 6\n case sessionExpired = 7\n }\n \n init(originalPacketID: String, senderID: String, receiverID: String, \n packetType: UInt8, reason: String, errorCode: ErrorCode = .unknown) {\n self.originalPacketID = originalPacketID\n self.nackID = UUID().uuidString\n self.senderID = senderID\n self.receiverID = receiverID\n self.packetType = packetType\n self.timestamp = Date()\n self.reason = reason\n self.errorCode = errorCode.rawValue\n }\n \n // Private init for binary decoding\n private init(originalPacketID: String, nackID: String, senderID: String, receiverID: String,\n packetType: UInt8, timestamp: Date, reason: String, errorCode: UInt8) {\n self.originalPacketID = originalPacketID\n self.nackID = nackID\n self.senderID = senderID\n self.receiverID = receiverID\n self.packetType = packetType\n self.timestamp = timestamp\n self.reason = reason\n self.errorCode = errorCode\n }\n \n func toBinaryData() -> Data {\n var data = Data()\n data.appendUUID(originalPacketID)\n data.appendUUID(nackID)\n \n // Sender and receiver IDs as 8-byte hex strings\n data.append(Data(hexString: senderID) ?? Data(repeating: 0, count: 8))\n data.append(Data(hexString: receiverID) ?? Data(repeating: 0, count: 8))\n \n data.appendUInt8(packetType)\n data.appendUInt8(errorCode)\n data.appendDate(timestamp)\n data.appendString(reason)\n return data\n }\n \n static func fromBinaryData(_ data: Data) -> ProtocolNack? {\n let dataCopy = Data(data)\n guard dataCopy.count >= 52 else { return nil } // Minimum size\n \n var offset = 0\n guard let originalPacketID = dataCopy.readUUID(at: &offset),\n let nackID = dataCopy.readUUID(at: &offset),\n let senderIDData = dataCopy.readFixedBytes(at: &offset, count: 8),\n let receiverIDData = dataCopy.readFixedBytes(at: &offset, count: 8),\n let packetType = dataCopy.readUInt8(at: &offset),\n let errorCode = dataCopy.readUInt8(at: &offset),\n let timestamp = dataCopy.readDate(at: &offset),\n let reason = dataCopy.readString(at: &offset) else { return nil }\n \n let senderID = senderIDData.hexEncodedString()\n let receiverID = receiverIDData.hexEncodedString()\n \n return ProtocolNack(originalPacketID: originalPacketID,\n nackID: nackID,\n senderID: senderID,\n receiverID: receiverID,\n packetType: packetType,\n timestamp: timestamp,\n reason: reason,\n errorCode: errorCode)\n }\n}\n\n// MARK: - Peer Identity Rotation\n\n/// Announces a peer's cryptographic identity to enable secure communication.\n/// Contains the peer's Noise static public key and supports identity rotation\n/// by binding ephemeral peer IDs to stable cryptographic fingerprints.\n/// - Note: Critical for establishing end-to-end encrypted channels\nstruct NoiseIdentityAnnouncement: Codable {\n let peerID: String // Current ephemeral peer ID\n let publicKey: Data // Noise static public key\n let signingPublicKey: Data // Ed25519 signing public key\n let nickname: String // Current nickname\n let timestamp: Date // When this binding was created\n let previousPeerID: String? // Previous peer ID (for smooth transition)\n let signature: Data // Signature proving ownership\n \n init(peerID: String, publicKey: Data, signingPublicKey: Data, nickname: String, timestamp: Date, previousPeerID: String? = nil, signature: Data) {\n self.peerID = peerID\n self.publicKey = publicKey\n self.signingPublicKey = signingPublicKey\n // Trim whitespace from nickname\n self.nickname = nickname.trimmingCharacters(in: .whitespacesAndNewlines)\n self.timestamp = timestamp\n self.previousPeerID = previousPeerID\n self.signature = signature\n }\n \n // Custom decoder to ensure nickname is trimmed\n init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n self.peerID = try container.decode(String.self, forKey: .peerID)\n self.publicKey = try container.decode(Data.self, forKey: .publicKey)\n self.signingPublicKey = try container.decode(Data.self, forKey: .signingPublicKey)\n // Trim whitespace from decoded nickname\n let rawNickname = try container.decode(String.self, forKey: .nickname)\n self.nickname = rawNickname.trimmingCharacters(in: .whitespacesAndNewlines)\n self.timestamp = try container.decode(Date.self, forKey: .timestamp)\n self.previousPeerID = try container.decodeIfPresent(String.self, forKey: .previousPeerID)\n self.signature = try container.decode(Data.self, forKey: .signature)\n }\n \n func encode() -> Data? {\n return try? JSONEncoder().encode(self)\n }\n \n static func decode(from data: Data) -> NoiseIdentityAnnouncement? {\n return try? JSONDecoder().decode(NoiseIdentityAnnouncement.self, from: data)\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n \n // Flags byte: bit 0 = hasPreviousPeerID\n var flags: UInt8 = 0\n if previousPeerID != nil { flags |= 0x01 }\n data.appendUInt8(flags)\n \n // PeerID as 8-byte hex string\n var peerData = Data()\n var tempID = peerID\n while tempID.count >= 2 && peerData.count < 8 {\n let hexByte = String(tempID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n peerData.append(byte)\n }\n tempID = String(tempID.dropFirst(2))\n }\n while peerData.count < 8 {\n peerData.append(0)\n }\n data.append(peerData)\n \n data.appendData(publicKey)\n data.appendData(signingPublicKey)\n data.appendString(nickname)\n data.appendDate(timestamp)\n \n if let previousPeerID = previousPeerID {\n // Previous PeerID as 8-byte hex string\n var prevData = Data()\n var tempPrevID = previousPeerID\n while tempPrevID.count >= 2 && prevData.count < 8 {\n let hexByte = String(tempPrevID.prefix(2))\n if let byte = UInt8(hexByte, radix: 16) {\n prevData.append(byte)\n }\n tempPrevID = String(tempPrevID.dropFirst(2))\n }\n while prevData.count < 8 {\n prevData.append(0)\n }\n data.append(prevData)\n }\n \n data.appendData(signature)\n \n return data\n }\n \n static func fromBinaryData(_ data: Data) -> NoiseIdentityAnnouncement? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size check: flags(1) + peerID(8) + min data lengths\n guard dataCopy.count >= 20 else { return nil }\n \n var offset = 0\n \n guard let flags = dataCopy.readUInt8(at: &offset) else { return nil }\n let hasPreviousPeerID = (flags & 0x01) != 0\n \n // Read peerID using safe method\n guard let peerIDBytes = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n let peerID = peerIDBytes.hexEncodedString()\n \n guard let publicKey = dataCopy.readData(at: &offset),\n let signingPublicKey = dataCopy.readData(at: &offset),\n let rawNickname = dataCopy.readString(at: &offset),\n let timestamp = dataCopy.readDate(at: &offset) else { return nil }\n \n // Trim whitespace from nickname\n let nickname = rawNickname.trimmingCharacters(in: .whitespacesAndNewlines)\n \n var previousPeerID: String? = nil\n if hasPreviousPeerID {\n // Read previousPeerID using safe method\n guard let prevIDBytes = dataCopy.readFixedBytes(at: &offset, count: 8) else { return nil }\n previousPeerID = prevIDBytes.hexEncodedString()\n }\n \n guard let signature = dataCopy.readData(at: &offset) else { return nil }\n \n return NoiseIdentityAnnouncement(peerID: peerID,\n publicKey: publicKey,\n signingPublicKey: signingPublicKey,\n nickname: nickname,\n timestamp: timestamp,\n previousPeerID: previousPeerID,\n signature: signature)\n }\n}\n\n// Binding between ephemeral peer ID and cryptographic identity\nstruct PeerIdentityBinding {\n let currentPeerID: String // Current ephemeral ID\n let fingerprint: String // Permanent cryptographic identity\n let publicKey: Data // Noise static public key\n let signingPublicKey: Data // Ed25519 signing public key\n let nickname: String // Last known nickname\n let bindingTimestamp: Date // When this binding was created\n let signature: Data // Cryptographic proof of binding\n \n // Verify the binding signature\n func verify() -> Bool {\n let bindingData = currentPeerID.data(using: .utf8)! + publicKey + \n String(Int64(bindingTimestamp.timeIntervalSince1970 * 1000)).data(using: .utf8)!\n \n do {\n let signingKey = try Curve25519.Signing.PublicKey(rawRepresentation: signingPublicKey)\n return signingKey.isValidSignature(signature, for: bindingData)\n } catch {\n return false\n }\n }\n}\n\n// MARK: - Protocol Version Negotiation\n\n// Protocol version constants\nstruct ProtocolVersion {\n static let current: UInt8 = 1\n static let minimum: UInt8 = 1\n static let maximum: UInt8 = 1\n \n // Future versions can be added here\n static let supportedVersions: Set = [1]\n \n static func isSupported(_ version: UInt8) -> Bool {\n return supportedVersions.contains(version)\n }\n \n static func negotiateVersion(clientVersions: [UInt8], serverVersions: [UInt8]) -> UInt8? {\n // Find the highest common version\n let clientSet = Set(clientVersions)\n let serverSet = Set(serverVersions)\n let common = clientSet.intersection(serverSet)\n \n return common.max()\n }\n}\n\n// Version negotiation hello message\nstruct VersionHello: Codable {\n let supportedVersions: [UInt8] // List of supported protocol versions\n let preferredVersion: UInt8 // Preferred version (usually the latest)\n let clientVersion: String // App version string (e.g., \"1.0.0\")\n let platform: String // Platform identifier (e.g., \"iOS\", \"macOS\")\n let capabilities: [String]? // Optional capability flags for future extensions\n \n init(supportedVersions: [UInt8] = Array(ProtocolVersion.supportedVersions), \n preferredVersion: UInt8 = ProtocolVersion.current,\n clientVersion: String,\n platform: String,\n capabilities: [String]? = nil) {\n self.supportedVersions = supportedVersions\n self.preferredVersion = preferredVersion\n self.clientVersion = clientVersion\n self.platform = platform\n self.capabilities = capabilities\n }\n \n func encode() -> Data? {\n return try? JSONEncoder().encode(self)\n }\n \n static func decode(from data: Data) -> VersionHello? {\n try? JSONDecoder().decode(VersionHello.self, from: data)\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n \n // Flags byte: bit 0 = hasCapabilities\n var flags: UInt8 = 0\n if capabilities != nil { flags |= 0x01 }\n data.appendUInt8(flags)\n \n // Supported versions array\n data.appendUInt8(UInt8(supportedVersions.count))\n for version in supportedVersions {\n data.appendUInt8(version)\n }\n \n data.appendUInt8(preferredVersion)\n data.appendString(clientVersion)\n data.appendString(platform)\n \n if let capabilities = capabilities {\n data.appendUInt8(UInt8(capabilities.count))\n for capability in capabilities {\n data.appendString(capability)\n }\n }\n \n return data\n }\n \n static func fromBinaryData(_ data: Data) -> VersionHello? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size check: flags(1) + versionCount(1) + at least one version(1) + preferredVersion(1) + min strings\n guard dataCopy.count >= 4 else { return nil }\n \n var offset = 0\n \n guard let flags = dataCopy.readUInt8(at: &offset) else { return nil }\n let hasCapabilities = (flags & 0x01) != 0\n \n guard let versionCount = dataCopy.readUInt8(at: &offset) else { return nil }\n var supportedVersions: [UInt8] = []\n for _ in 0.. Data? {\n return try? JSONEncoder().encode(self)\n }\n \n static func decode(from data: Data) -> VersionAck? {\n try? JSONDecoder().decode(VersionAck.self, from: data)\n }\n \n // MARK: - Binary Encoding\n \n func toBinaryData() -> Data {\n var data = Data()\n \n // Flags byte: bit 0 = hasCapabilities, bit 1 = hasReason\n var flags: UInt8 = 0\n if capabilities != nil { flags |= 0x01 }\n if reason != nil { flags |= 0x02 }\n data.appendUInt8(flags)\n \n data.appendUInt8(agreedVersion)\n data.appendString(serverVersion)\n data.appendString(platform)\n data.appendUInt8(rejected ? 1 : 0)\n \n if let capabilities = capabilities {\n data.appendUInt8(UInt8(capabilities.count))\n for capability in capabilities {\n data.appendString(capability)\n }\n }\n \n if let reason = reason {\n data.appendString(reason)\n }\n \n return data\n }\n \n static func fromBinaryData(_ data: Data) -> VersionAck? {\n // Create defensive copy\n let dataCopy = Data(data)\n \n // Minimum size: flags(1) + version(1) + rejected(1) + min strings\n guard dataCopy.count >= 5 else { return nil }\n \n var offset = 0\n \n guard let flags = dataCopy.readUInt8(at: &offset) else { return nil }\n let hasCapabilities = (flags & 0x01) != 0\n let hasReason = (flags & 0x02) != 0\n \n guard let agreedVersion = dataCopy.readUInt8(at: &offset),\n let serverVersion = dataCopy.readString(at: &offset),\n let platform = dataCopy.readString(at: &offset),\n let rejectedByte = dataCopy.readUInt8(at: &offset) else { return nil }\n \n let rejected = rejectedByte != 0\n \n var capabilities: [String]? = nil\n if hasCapabilities {\n guard let capCount = dataCopy.readUInt8(at: &offset) else { return nil }\n capabilities = []\n for _ in 0.. AttributedString? {\n return _cachedFormattedText[\"\\(isDark)\"]\n }\n \n func setCachedFormattedText(_ text: AttributedString, isDark: Bool) {\n _cachedFormattedText[\"\\(isDark)\"] = text\n }\n \n // Codable implementation\n enum CodingKeys: String, CodingKey {\n case id, sender, content, timestamp, isRelay, originalSender\n case isPrivate, recipientNickname, senderPeerID, mentions, deliveryStatus\n }\n \n init(id: String? = nil, sender: String, content: String, timestamp: Date, isRelay: Bool, originalSender: String? = nil, isPrivate: Bool = false, recipientNickname: String? = nil, senderPeerID: String? = nil, mentions: [String]? = nil, deliveryStatus: DeliveryStatus? = nil) {\n self.id = id ?? UUID().uuidString\n self.sender = sender\n self.content = content\n self.timestamp = timestamp\n self.isRelay = isRelay\n self.originalSender = originalSender\n self.isPrivate = isPrivate\n self.recipientNickname = recipientNickname\n self.senderPeerID = senderPeerID\n self.mentions = mentions\n self.deliveryStatus = deliveryStatus ?? (isPrivate ? .sending : nil)\n }\n}\n\n// Equatable conformance for BitchatMessage\nextension BitchatMessage: Equatable {\n static func == (lhs: BitchatMessage, rhs: BitchatMessage) -> Bool {\n return lhs.id == rhs.id &&\n lhs.sender == rhs.sender &&\n lhs.content == rhs.content &&\n lhs.timestamp == rhs.timestamp &&\n lhs.isRelay == rhs.isRelay &&\n lhs.originalSender == rhs.originalSender &&\n lhs.isPrivate == rhs.isPrivate &&\n lhs.recipientNickname == rhs.recipientNickname &&\n lhs.senderPeerID == rhs.senderPeerID &&\n lhs.mentions == rhs.mentions &&\n lhs.deliveryStatus == rhs.deliveryStatus\n }\n}\n\n// MARK: - Delegate Protocol\n\nprotocol BitchatDelegate: AnyObject {\n func didReceiveMessage(_ message: BitchatMessage)\n func didConnectToPeer(_ peerID: String)\n func didDisconnectFromPeer(_ peerID: String)\n func didUpdatePeerList(_ peers: [String])\n \n // Optional method to check if a fingerprint belongs to a favorite peer\n func isFavorite(fingerprint: String) -> Bool\n \n // Delivery confirmation methods\n func didReceiveDeliveryAck(_ ack: DeliveryAck)\n func didReceiveReadReceipt(_ receipt: ReadReceipt)\n func didUpdateMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus)\n \n // Peer availability tracking\n func peerAvailabilityChanged(_ peerID: String, available: Bool)\n}\n\n// Provide default implementation to make it effectively optional\nextension BitchatDelegate {\n func isFavorite(fingerprint: String) -> Bool {\n return false\n }\n \n func didReceiveDeliveryAck(_ ack: DeliveryAck) {\n // Default empty implementation\n }\n \n func didReceiveReadReceipt(_ receipt: ReadReceipt) {\n // Default empty implementation\n }\n \n func didUpdateMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) {\n // Default empty implementation\n }\n \n func peerAvailabilityChanged(_ peerID: String, available: Bool) {\n // Default empty implementation\n }\n}\n"], ["/bitchat/bitchatShareExtension/ShareViewController.swift", "//\n// ShareViewController.swift\n// bitchatShareExtension\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport UIKit\nimport Social\nimport UniformTypeIdentifiers\n\nclass ShareViewController: SLComposeServiceViewController {\n \n override func viewDidLoad() {\n super.viewDidLoad()\n // Set placeholder text\n placeholder = \"Share to bitchat...\"\n // Set character limit (optional)\n charactersRemaining = 500\n }\n \n override func isContentValid() -> Bool {\n // Validate that we have text content or attachments\n if let text = contentText, !text.isEmpty {\n return true\n }\n // Check if we have attachments\n if let item = extensionContext?.inputItems.first as? NSExtensionItem,\n let attachments = item.attachments,\n !attachments.isEmpty {\n return true\n }\n return false\n }\n \n override func didSelectPost() {\n guard let extensionItem = extensionContext?.inputItems.first as? NSExtensionItem else {\n self.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)\n return\n }\n \n \n // Get the page title from the compose view or extension item\n let pageTitle = self.contentText ?? extensionItem.attributedContentText?.string ?? extensionItem.attributedTitle?.string\n \n var foundURL: URL? = nil\n let group = DispatchGroup()\n \n // IMPORTANT: Check if the NSExtensionItem itself has a URL\n // Safari often provides the URL as an attributedString with a link\n if let attributedText = extensionItem.attributedContentText {\n let text = attributedText.string\n let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)\n let matches = detector?.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count))\n if let firstMatch = matches?.first, let url = firstMatch.url {\n foundURL = url\n }\n }\n \n // Only check attachments if we haven't found a URL yet\n if foundURL == nil {\n for (_, itemProvider) in (extensionItem.attachments ?? []).enumerated() {\n \n // Try multiple URL type identifiers that Safari might use\n let urlTypes = [\n UTType.url.identifier,\n \"public.url\",\n \"public.file-url\"\n ]\n \n for urlType in urlTypes {\n if itemProvider.hasItemConformingToTypeIdentifier(urlType) {\n group.enter()\n itemProvider.loadItem(forTypeIdentifier: urlType, options: nil) { (item, error) in\n defer { group.leave() }\n \n if let url = item as? URL {\n foundURL = url\n } else if let data = item as? Data,\n let urlString = String(data: data, encoding: .utf8),\n let url = URL(string: urlString) {\n foundURL = url\n } else if let string = item as? String,\n let url = URL(string: string) {\n foundURL = url\n }\n }\n break // Found a URL type, no need to check other types\n }\n }\n \n // Also check for plain text that might be a URL\n if foundURL == nil && itemProvider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) {\n group.enter()\n itemProvider.loadItem(forTypeIdentifier: UTType.plainText.identifier, options: nil) { (item, error) in\n defer { group.leave() }\n \n if let text = item as? String {\n // Check if the text is actually a URL\n if let url = URL(string: text),\n (url.scheme == \"http\" || url.scheme == \"https\") {\n foundURL = url\n }\n }\n }\n }\n }\n } // End of if foundURL == nil\n \n // Process after all checks complete\n group.notify(queue: .main) { [weak self] in\n if let url = foundURL {\n // We have a URL! Create the JSON data\n let urlData: [String: String] = [\n \"url\": url.absoluteString,\n \"title\": pageTitle ?? url.host ?? \"Shared Link\"\n ]\n \n \n if let jsonData = try? JSONSerialization.data(withJSONObject: urlData),\n let jsonString = String(data: jsonData, encoding: .utf8) {\n self?.saveToSharedDefaults(content: jsonString, type: \"url\")\n }\n } else if let title = pageTitle, !title.isEmpty {\n // No URL found, just share the text\n self?.saveToSharedDefaults(content: title, type: \"text\")\n }\n \n self?.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)\n }\n }\n \n override func configurationItems() -> [Any]! {\n // No configuration items needed\n return []\n }\n \n // MARK: - Helper Methods\n \n private func handleSharedText(_ text: String) {\n // Save to shared user defaults to pass to main app\n saveToSharedDefaults(content: text, type: \"text\")\n openMainApp()\n }\n \n private func handleSharedURL(_ url: URL) {\n // Get the page title if available from the extension context\n var pageTitle: String? = nil\n if let item = extensionContext?.inputItems.first as? NSExtensionItem {\n pageTitle = item.attributedContentText?.string ?? item.attributedTitle?.string\n }\n \n // Create a structured format for URL sharing\n let urlData: [String: String] = [\n \"url\": url.absoluteString,\n \"title\": pageTitle ?? url.host ?? \"Shared Link\"\n ]\n \n // Convert to JSON string\n if let jsonData = try? JSONSerialization.data(withJSONObject: urlData),\n let jsonString = String(data: jsonData, encoding: .utf8) {\n saveToSharedDefaults(content: jsonString, type: \"url\")\n } else {\n // Fallback to simple URL\n saveToSharedDefaults(content: url.absoluteString, type: \"url\")\n }\n \n openMainApp()\n }\n \n private func handleSharedImage(_ image: UIImage) {\n // For now, we'll just notify that image sharing isn't supported\n // In the future, we could implement image sharing via the mesh\n saveToSharedDefaults(content: \"Image sharing coming soon!\", type: \"image\")\n openMainApp()\n }\n \n private func saveToSharedDefaults(content: String, type: String) {\n // Use app groups to share data between extension and main app\n guard let userDefaults = UserDefaults(suiteName: \"group.chat.bitchat\") else {\n return\n }\n \n userDefaults.set(content, forKey: \"sharedContent\")\n userDefaults.set(type, forKey: \"sharedContentType\")\n userDefaults.set(Date(), forKey: \"sharedContentDate\")\n userDefaults.synchronize()\n \n \n // Force open the main app\n self.openMainApp()\n }\n \n private func openMainApp() {\n // Share extensions cannot directly open the containing app\n // The app will check for shared content when it becomes active\n // Show success feedback to user\n DispatchQueue.main.async {\n self.textView.text = \"✓ Shared to bitchat\"\n self.textView.isEditable = false\n }\n }\n}"], ["/bitchat/bitchat/Noise/NoiseProtocol.swift", "//\n// NoiseProtocol.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # NoiseProtocol\n///\n/// A complete implementation of the Noise Protocol Framework for end-to-end\n/// encryption in BitChat. This file contains the core cryptographic primitives\n/// and handshake logic that enable secure communication between peers.\n///\n/// ## Overview\n/// The Noise Protocol Framework is a modern cryptographic framework designed\n/// for building secure protocols. BitChat uses Noise to provide:\n/// - Mutual authentication between peers\n/// - Forward secrecy for all messages\n/// - Protection against replay attacks\n/// - Minimal round trips for connection establishment\n///\n/// ## Implementation Details\n/// This implementation follows the Noise specification exactly, using:\n/// - **Pattern**: XX (most versatile, provides mutual authentication)\n/// - **DH**: Curve25519 (X25519 key exchange)\n/// - **Cipher**: ChaCha20-Poly1305 (AEAD encryption)\n/// - **Hash**: SHA-256 (for key derivation and authentication)\n///\n/// ## Security Properties\n/// The XX handshake pattern provides:\n/// 1. **Identity Hiding**: Both parties' identities are encrypted\n/// 2. **Forward Secrecy**: Past sessions remain secure if keys are compromised\n/// 3. **Key Compromise Impersonation Resistance**: Compromised static key doesn't allow impersonation to that party\n/// 4. **Mutual Authentication**: Both parties verify each other's identity\n///\n/// ## Handshake Flow (XX Pattern)\n/// ```\n/// Initiator Responder\n/// --------- ---------\n/// -> e (ephemeral key)\n/// <- e, ee, s, es (ephemeral, DH, static encrypted, DH)\n/// -> s, se (static encrypted, DH)\n/// ```\n///\n/// ## Key Components\n/// - **NoiseCipherState**: Manages symmetric encryption with nonce tracking\n/// - **NoiseSymmetricState**: Handles key derivation and handshake hashing\n/// - **NoiseHandshakeState**: Orchestrates the complete handshake process\n///\n/// ## Replay Protection\n/// Implements sliding window replay protection to prevent message replay attacks:\n/// - Tracks nonces within a 1024-message window\n/// - Rejects duplicate or too-old nonces\n/// - Handles out-of-order message delivery\n///\n/// ## Usage Example\n/// ```swift\n/// let handshake = NoiseHandshakeState(\n/// pattern: .XX,\n/// role: .initiator,\n/// localStatic: staticKeyPair\n/// )\n/// let messageBuffer = handshake.writeMessage(payload: Data())\n/// // Send messageBuffer to peer...\n/// ```\n///\n/// ## Security Considerations\n/// - Static keys must be generated using secure random sources\n/// - Keys should be stored securely (e.g., in Keychain)\n/// - Handshake state must not be reused after completion\n/// - Transport messages have a nonce limit (2^64-1)\n///\n/// ## References\n/// - Noise Protocol Framework: http://www.noiseprotocol.org/\n/// - Noise Specification: http://www.noiseprotocol.org/noise.html\n///\n\nimport Foundation\nimport CryptoKit\nimport os.log\n\n// Core Noise Protocol implementation\n// Based on the Noise Protocol Framework specification\n\n// MARK: - Constants and Types\n\n/// Supported Noise handshake patterns.\n/// Each pattern provides different security properties and authentication guarantees.\nenum NoisePattern {\n case XX // Most versatile, mutual authentication\n case IK // Initiator knows responder's static key\n case NK // Anonymous initiator\n}\n\nenum NoiseRole {\n case initiator\n case responder\n}\n\nenum NoiseMessagePattern {\n case e // Ephemeral key\n case s // Static key\n case ee // DH(ephemeral, ephemeral)\n case es // DH(ephemeral, static)\n case se // DH(static, ephemeral)\n case ss // DH(static, static)\n}\n\n// MARK: - Noise Protocol Configuration\n\nstruct NoiseProtocolName {\n let pattern: String\n let dh: String = \"25519\" // Curve25519\n let cipher: String = \"ChaChaPoly\" // ChaCha20-Poly1305\n let hash: String = \"SHA256\" // SHA-256\n \n var fullName: String {\n \"Noise_\\(pattern)_\\(dh)_\\(cipher)_\\(hash)\"\n }\n}\n\n// MARK: - Cipher State\n\n/// Manages symmetric encryption state for Noise protocol sessions.\n/// Handles ChaCha20-Poly1305 AEAD encryption with automatic nonce management\n/// and replay protection using a sliding window algorithm.\n/// - Warning: Nonce reuse would be catastrophic for security\nclass NoiseCipherState {\n // Constants for replay protection\n private static let NONCE_SIZE_BYTES = 4\n private static let REPLAY_WINDOW_SIZE = 1024\n private static let REPLAY_WINDOW_BYTES = REPLAY_WINDOW_SIZE / 8 // 128 bytes\n private static let HIGH_NONCE_WARNING_THRESHOLD: UInt64 = 1_000_000_000\n \n private var key: SymmetricKey?\n private var nonce: UInt64 = 0\n private var useExtractedNonce: Bool = false\n \n // Sliding window replay protection (only used when useExtractedNonce = true)\n private var highestReceivedNonce: UInt64 = 0\n private var replayWindow: [UInt8] = Array(repeating: 0, count: REPLAY_WINDOW_BYTES)\n \n init() {}\n \n init(key: SymmetricKey, useExtractedNonce: Bool = false) {\n self.key = key\n self.useExtractedNonce = useExtractedNonce\n }\n \n func initializeKey(_ key: SymmetricKey) {\n self.key = key\n self.nonce = 0\n }\n \n func hasKey() -> Bool {\n return key != nil\n }\n \n // MARK: - Sliding Window Replay Protection\n \n /// Check if nonce is valid for replay protection\n private func isValidNonce(_ receivedNonce: UInt64) -> Bool {\n if receivedNonce + UInt64(Self.REPLAY_WINDOW_SIZE) <= highestReceivedNonce {\n return false // Too old, outside window\n }\n \n if receivedNonce > highestReceivedNonce {\n return true // Always accept newer nonces\n }\n \n let offset = Int(highestReceivedNonce - receivedNonce)\n let byteIndex = offset / 8\n let bitIndex = offset % 8\n \n return (replayWindow[byteIndex] & (1 << bitIndex)) == 0 // Not yet seen\n }\n \n /// Mark nonce as seen in replay window\n private func markNonceAsSeen(_ receivedNonce: UInt64) {\n if receivedNonce > highestReceivedNonce {\n let shift = Int(receivedNonce - highestReceivedNonce)\n \n if shift >= Self.REPLAY_WINDOW_SIZE {\n // Clear entire window - shift is too large\n replayWindow = Array(repeating: 0, count: Self.REPLAY_WINDOW_BYTES)\n } else {\n // Shift window right by `shift` bits\n for i in stride(from: Self.REPLAY_WINDOW_BYTES - 1, through: 0, by: -1) {\n let sourceByteIndex = i - shift / 8\n var newByte: UInt8 = 0\n \n if sourceByteIndex >= 0 {\n newByte = replayWindow[sourceByteIndex] >> (shift % 8)\n if sourceByteIndex > 0 && shift % 8 != 0 {\n newByte |= replayWindow[sourceByteIndex - 1] << (8 - shift % 8)\n }\n }\n \n replayWindow[i] = newByte\n }\n }\n \n highestReceivedNonce = receivedNonce\n replayWindow[0] |= 1 // Mark most recent bit as seen\n } else {\n let offset = Int(highestReceivedNonce - receivedNonce)\n let byteIndex = offset / 8\n let bitIndex = offset % 8\n replayWindow[byteIndex] |= (1 << bitIndex)\n }\n }\n \n /// Extract nonce from combined payload \n /// Returns tuple of (nonce, ciphertext) or nil if invalid\n private func extractNonceFromCiphertextPayload(_ combinedPayload: Data) throws -> (nonce: UInt64, ciphertext: Data)? {\n guard combinedPayload.count >= Self.NONCE_SIZE_BYTES else {\n return nil\n }\n\n // Extract 4-byte nonce (big-endian)\n let nonceData = combinedPayload.prefix(Self.NONCE_SIZE_BYTES)\n let extractedNonce = nonceData.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> UInt64 in\n let byteArray = bytes.bindMemory(to: UInt8.self)\n var result: UInt64 = 0\n for i in 0.. Data {\n var bytes = Data(count: Self.NONCE_SIZE_BYTES)\n withUnsafeBytes(of: nonce.bigEndian) { ptr in\n // Copy only the last 4 bytes from the 8-byte UInt64 \n let sourceBytes = ptr.bindMemory(to: UInt8.self)\n bytes.replaceSubrange(0.. Data {\n guard let key = self.key else {\n throw NoiseError.uninitializedCipher\n }\n \n // Debug logging for nonce tracking\n let currentNonce = nonce\n \n // Check if nonce exceeds 4-byte limit (UInt32 max value)\n guard nonce <= UInt64(UInt32.max) - 1 else {\n throw NoiseError.nonceExceeded\n }\n \n // Create nonce from counter\n var nonceData = Data(count: 12)\n withUnsafeBytes(of: currentNonce.littleEndian) { bytes in\n nonceData.replaceSubrange(4..<12, with: bytes)\n }\n \n let sealedBox = try ChaChaPoly.seal(plaintext, using: key, nonce: ChaChaPoly.Nonce(data: nonceData), authenticating: associatedData)\n // increment local nonce\n nonce += 1\n \n // Create combined payload: \n let combinedPayload: Data\n if (useExtractedNonce) {\n let nonceBytes = nonceToBytes(currentNonce)\n combinedPayload = nonceBytes + sealedBox.ciphertext + sealedBox.tag\n } else {\n combinedPayload = sealedBox.ciphertext + sealedBox.tag\n }\n \n // Log high nonce values that might indicate issues\n if currentNonce > Self.HIGH_NONCE_WARNING_THRESHOLD {\n SecureLogger.log(\"High nonce value detected: \\(currentNonce) - consider rekeying\", category: SecureLogger.encryption, level: .warning)\n }\n \n return combinedPayload\n }\n \n func decrypt(ciphertext: Data, associatedData: Data = Data()) throws -> Data {\n guard let key = self.key else {\n throw NoiseError.uninitializedCipher\n }\n \n guard ciphertext.count >= 16 else {\n throw NoiseError.invalidCiphertext\n }\n \n let encryptedData: Data\n let tag: Data\n let decryptionNonce: UInt64\n \n if useExtractedNonce {\n // Extract nonce and ciphertext from combined payload\n guard let (extractedNonce, actualCiphertext) = try extractNonceFromCiphertextPayload(ciphertext) else {\n SecureLogger.log(\"Decrypt failed: Could not extract nonce from payload\")\n throw NoiseError.invalidCiphertext\n }\n \n // Validate nonce with sliding window replay protection\n guard isValidNonce(extractedNonce) else {\n SecureLogger.log(\"Replay attack detected: nonce \\(extractedNonce) rejected\")\n throw NoiseError.replayDetected\n }\n\n // Split ciphertext and tag\n encryptedData = actualCiphertext.prefix(actualCiphertext.count - 16)\n tag = actualCiphertext.suffix(16)\n decryptionNonce = extractedNonce\n } else {\n // Split ciphertext and tag\n encryptedData = ciphertext.prefix(ciphertext.count - 16)\n tag = ciphertext.suffix(16)\n decryptionNonce = nonce\n }\n \n // Create nonce from counter\n var nonceData = Data(count: 12)\n withUnsafeBytes(of: decryptionNonce.littleEndian) { bytes in\n nonceData.replaceSubrange(4..<12, with: bytes)\n }\n \n let sealedBox = try ChaChaPoly.SealedBox(\n nonce: ChaChaPoly.Nonce(data: nonceData),\n ciphertext: encryptedData,\n tag: tag\n )\n \n // Log high nonce values that might indicate issues\n if decryptionNonce > Self.HIGH_NONCE_WARNING_THRESHOLD {\n SecureLogger.log(\"High nonce value detected: \\(decryptionNonce) - consider rekeying\", category: SecureLogger.encryption, level: .warning)\n }\n \n do {\n let plaintext = try ChaChaPoly.open(sealedBox, using: key, authenticating: associatedData)\n \n if useExtractedNonce {\n // Mark nonce as seen after successful decryption\n markNonceAsSeen(decryptionNonce)\n }\n nonce += 1\n return plaintext\n } catch {\n SecureLogger.log(\"Decrypt failed: \\(error) for nonce \\(decryptionNonce)\")\n // Log authentication failures with nonce info\n SecureLogger.log(\"Decryption failed at nonce \\(decryptionNonce)\", category: SecureLogger.encryption, level: .error)\n throw error\n }\n }\n}\n\n// MARK: - Symmetric State\n\n/// Manages the symmetric cryptographic state during Noise handshakes.\n/// Responsible for key derivation, protocol name hashing, and maintaining\n/// the chaining key that provides key separation between handshake messages.\n/// - Note: This class implements the SymmetricState object from the Noise spec\nclass NoiseSymmetricState {\n private var cipherState: NoiseCipherState\n private var chainingKey: Data\n private var hash: Data\n \n init(protocolName: String) {\n self.cipherState = NoiseCipherState()\n \n // Initialize with protocol name\n let nameData = protocolName.data(using: .utf8)!\n if nameData.count <= 32 {\n self.hash = nameData + Data(repeating: 0, count: 32 - nameData.count)\n } else {\n self.hash = Data(SHA256.hash(data: nameData))\n }\n self.chainingKey = self.hash\n }\n \n func mixKey(_ inputKeyMaterial: Data) {\n let output = hkdf(chainingKey: chainingKey, inputKeyMaterial: inputKeyMaterial, numOutputs: 2)\n chainingKey = output[0]\n let tempKey = SymmetricKey(data: output[1])\n cipherState.initializeKey(tempKey)\n }\n \n func mixHash(_ data: Data) {\n hash = Data(SHA256.hash(data: hash + data))\n }\n \n func mixKeyAndHash(_ inputKeyMaterial: Data) {\n let output = hkdf(chainingKey: chainingKey, inputKeyMaterial: inputKeyMaterial, numOutputs: 3)\n chainingKey = output[0]\n mixHash(output[1])\n let tempKey = SymmetricKey(data: output[2])\n cipherState.initializeKey(tempKey)\n }\n \n func getHandshakeHash() -> Data {\n return hash\n }\n \n func hasCipherKey() -> Bool {\n return cipherState.hasKey()\n }\n \n func encryptAndHash(_ plaintext: Data) throws -> Data {\n if cipherState.hasKey() {\n let ciphertext = try cipherState.encrypt(plaintext: plaintext, associatedData: hash)\n mixHash(ciphertext)\n return ciphertext\n } else {\n mixHash(plaintext)\n return plaintext\n }\n }\n \n func decryptAndHash(_ ciphertext: Data) throws -> Data {\n if cipherState.hasKey() {\n let plaintext = try cipherState.decrypt(ciphertext: ciphertext, associatedData: hash)\n mixHash(ciphertext)\n return plaintext\n } else {\n mixHash(ciphertext)\n return ciphertext\n }\n }\n \n func split() -> (NoiseCipherState, NoiseCipherState) {\n let output = hkdf(chainingKey: chainingKey, inputKeyMaterial: Data(), numOutputs: 2)\n let tempKey1 = SymmetricKey(data: output[0])\n let tempKey2 = SymmetricKey(data: output[1])\n \n let c1 = NoiseCipherState(key: tempKey1, useExtractedNonce: true)\n let c2 = NoiseCipherState(key: tempKey2, useExtractedNonce: true)\n \n return (c1, c2)\n }\n \n // HKDF implementation\n private func hkdf(chainingKey: Data, inputKeyMaterial: Data, numOutputs: Int) -> [Data] {\n let tempKey = HMAC.authenticationCode(for: inputKeyMaterial, using: SymmetricKey(data: chainingKey))\n let tempKeyData = Data(tempKey)\n \n var outputs: [Data] = []\n var currentOutput = Data()\n \n for i in 1...numOutputs {\n currentOutput = Data(HMAC.authenticationCode(\n for: currentOutput + Data([UInt8(i)]),\n using: SymmetricKey(data: tempKeyData)\n ))\n outputs.append(currentOutput)\n }\n \n return outputs\n }\n}\n\n// MARK: - Handshake State\n\n/// Orchestrates the complete Noise handshake process.\n/// This is the main interface for establishing encrypted sessions between peers.\n/// Manages the handshake state machine, message patterns, and key derivation.\n/// - Important: Each handshake instance should only be used once\nclass NoiseHandshakeState {\n private let role: NoiseRole\n private let pattern: NoisePattern\n private var symmetricState: NoiseSymmetricState\n \n // Keys\n private var localStaticPrivate: Curve25519.KeyAgreement.PrivateKey?\n private var localStaticPublic: Curve25519.KeyAgreement.PublicKey?\n private var localEphemeralPrivate: Curve25519.KeyAgreement.PrivateKey?\n private var localEphemeralPublic: Curve25519.KeyAgreement.PublicKey?\n \n private var remoteStaticPublic: Curve25519.KeyAgreement.PublicKey?\n private var remoteEphemeralPublic: Curve25519.KeyAgreement.PublicKey?\n \n // Message patterns\n private var messagePatterns: [[NoiseMessagePattern]] = []\n private var currentPattern = 0\n \n init(role: NoiseRole, pattern: NoisePattern, localStaticKey: Curve25519.KeyAgreement.PrivateKey? = nil, remoteStaticKey: Curve25519.KeyAgreement.PublicKey? = nil) {\n self.role = role\n self.pattern = pattern\n \n // Initialize static keys\n if let localKey = localStaticKey {\n self.localStaticPrivate = localKey\n self.localStaticPublic = localKey.publicKey\n }\n self.remoteStaticPublic = remoteStaticKey\n \n // Initialize protocol name\n let protocolName = NoiseProtocolName(pattern: pattern.patternName)\n self.symmetricState = NoiseSymmetricState(protocolName: protocolName.fullName)\n \n // Initialize message patterns\n self.messagePatterns = pattern.messagePatterns\n \n // Mix pre-message keys according to pattern\n mixPreMessageKeys()\n }\n \n private func mixPreMessageKeys() {\n // Mix prologue (empty for XX pattern normally)\n symmetricState.mixHash(Data()) // Empty prologue for XX pattern\n // For XX pattern, no pre-message keys\n // For IK/NK patterns, we'd mix the responder's static key here\n switch pattern {\n case .XX:\n break // No pre-message keys\n case .IK, .NK:\n if role == .initiator, let remoteStatic = remoteStaticPublic {\n _ = symmetricState.getHandshakeHash()\n symmetricState.mixHash(remoteStatic.rawRepresentation)\n }\n }\n }\n \n func writeMessage(payload: Data = Data()) throws -> Data {\n guard currentPattern < messagePatterns.count else {\n throw NoiseError.handshakeComplete\n }\n \n var messageBuffer = Data()\n let patterns = messagePatterns[currentPattern]\n \n for pattern in patterns {\n switch pattern {\n case .e:\n // Generate ephemeral key\n localEphemeralPrivate = Curve25519.KeyAgreement.PrivateKey()\n localEphemeralPublic = localEphemeralPrivate!.publicKey\n messageBuffer.append(localEphemeralPublic!.rawRepresentation)\n symmetricState.mixHash(localEphemeralPublic!.rawRepresentation)\n \n case .s:\n // Send static key (encrypted if cipher is initialized)\n guard let staticPublic = localStaticPublic else {\n throw NoiseError.missingLocalStaticKey\n }\n let encrypted = try symmetricState.encryptAndHash(staticPublic.rawRepresentation)\n messageBuffer.append(encrypted)\n \n case .ee:\n // DH(local ephemeral, remote ephemeral)\n guard let localEphemeral = localEphemeralPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n \n case .es:\n // DH(ephemeral, static) - direction depends on role\n if role == .initiator {\n guard let localEphemeral = localEphemeralPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n } else {\n guard let localStatic = localStaticPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n }\n \n case .se:\n // DH(static, ephemeral) - direction depends on role\n if role == .initiator {\n guard let localStatic = localStaticPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n } else {\n guard let localEphemeral = localEphemeralPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n }\n \n case .ss:\n // DH(static, static)\n guard let localStatic = localStaticPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n }\n }\n \n // Encrypt payload\n let encryptedPayload = try symmetricState.encryptAndHash(payload)\n messageBuffer.append(encryptedPayload)\n \n currentPattern += 1\n return messageBuffer\n }\n \n func readMessage(_ message: Data, expectedPayloadLength: Int = 0) throws -> Data {\n \n guard currentPattern < messagePatterns.count else {\n throw NoiseError.handshakeComplete\n }\n \n var buffer = message\n let patterns = messagePatterns[currentPattern]\n \n for pattern in patterns {\n switch pattern {\n case .e:\n // Read ephemeral key\n guard buffer.count >= 32 else {\n throw NoiseError.invalidMessage\n }\n let ephemeralData = buffer.prefix(32)\n buffer = buffer.dropFirst(32)\n \n do {\n remoteEphemeralPublic = try NoiseHandshakeState.validatePublicKey(ephemeralData)\n } catch {\n SecureLogger.log(\"Invalid ephemeral public key received\", category: SecureLogger.security, level: .warning)\n throw NoiseError.invalidMessage\n }\n symmetricState.mixHash(ephemeralData)\n \n case .s:\n // Read static key (may be encrypted)\n let keyLength = symmetricState.hasCipherKey() ? 48 : 32 // 32 + 16 byte tag if encrypted\n guard buffer.count >= keyLength else {\n throw NoiseError.invalidMessage\n }\n let staticData = buffer.prefix(keyLength)\n buffer = buffer.dropFirst(keyLength)\n do {\n let decrypted = try symmetricState.decryptAndHash(staticData)\n remoteStaticPublic = try NoiseHandshakeState.validatePublicKey(decrypted)\n } catch {\n SecureLogger.logSecurityEvent(.authenticationFailed(peerID: \"Unknown - handshake\"), level: .error)\n throw NoiseError.authenticationFailure\n }\n \n case .ee, .es, .se, .ss:\n // Same DH operations as in writeMessage\n try performDHOperation(pattern)\n }\n }\n \n // Decrypt payload\n let payload = try symmetricState.decryptAndHash(buffer)\n currentPattern += 1\n \n return payload\n }\n \n private func performDHOperation(_ pattern: NoiseMessagePattern) throws {\n switch pattern {\n case .ee:\n guard let localEphemeral = localEphemeralPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n \n case .es:\n if role == .initiator {\n guard let localEphemeral = localEphemeralPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n } else {\n guard let localStatic = localStaticPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n }\n \n case .se:\n if role == .initiator {\n guard let localStatic = localStaticPrivate,\n let remoteEphemeral = remoteEphemeralPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteEphemeral)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n } else {\n guard let localEphemeral = localEphemeralPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localEphemeral.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n }\n \n case .ss:\n guard let localStatic = localStaticPrivate,\n let remoteStatic = remoteStaticPublic else {\n throw NoiseError.missingKeys\n }\n let shared = try localStatic.sharedSecretFromKeyAgreement(with: remoteStatic)\n symmetricState.mixKey(shared.withUnsafeBytes { Data($0) })\n \n default:\n break\n }\n }\n \n func isHandshakeComplete() -> Bool {\n return currentPattern >= messagePatterns.count\n }\n \n func getTransportCiphers() throws -> (send: NoiseCipherState, receive: NoiseCipherState) {\n guard isHandshakeComplete() else {\n throw NoiseError.handshakeNotComplete\n }\n \n let (c1, c2) = symmetricState.split()\n \n // Initiator uses c1 for sending, c2 for receiving\n // Responder uses c2 for sending, c1 for receiving\n return role == .initiator ? (c1, c2) : (c2, c1)\n }\n \n func getRemoteStaticPublicKey() -> Curve25519.KeyAgreement.PublicKey? {\n return remoteStaticPublic\n }\n \n func getHandshakeHash() -> Data {\n return symmetricState.getHandshakeHash()\n }\n}\n\n// MARK: - Pattern Extensions\n\nextension NoisePattern {\n var patternName: String {\n switch self {\n case .XX: return \"XX\"\n case .IK: return \"IK\"\n case .NK: return \"NK\"\n }\n }\n \n var messagePatterns: [[NoiseMessagePattern]] {\n switch self {\n case .XX:\n return [\n [.e], // -> e\n [.e, .ee, .s, .es], // <- e, ee, s, es\n [.s, .se] // -> s, se\n ]\n case .IK:\n return [\n [.e, .es, .s, .ss], // -> e, es, s, ss\n [.e, .ee, .se] // <- e, ee, se\n ]\n case .NK:\n return [\n [.e, .es], // -> e, es\n [.e, .ee] // <- e, ee\n ]\n }\n }\n}\n\n// MARK: - Errors\n\nenum NoiseError: Error {\n case uninitializedCipher\n case invalidCiphertext\n case handshakeComplete\n case handshakeNotComplete\n case missingLocalStaticKey\n case missingKeys\n case invalidMessage\n case authenticationFailure\n case invalidPublicKey\n case replayDetected\n case nonceExceeded\n}\n\n// MARK: - Key Validation\n\nextension NoiseHandshakeState {\n /// Validate a Curve25519 public key\n /// Checks for weak/invalid keys that could compromise security\n static func validatePublicKey(_ keyData: Data) throws -> Curve25519.KeyAgreement.PublicKey {\n // Check key length\n guard keyData.count == 32 else {\n throw NoiseError.invalidPublicKey\n }\n \n // Check for all-zero key (point at infinity)\n if keyData.allSatisfy({ $0 == 0 }) {\n throw NoiseError.invalidPublicKey\n }\n \n // Check for low-order points that could enable small subgroup attacks\n // These are the known bad points for Curve25519\n let lowOrderPoints: [Data] = [\n Data(repeating: 0x00, count: 32), // Already checked above\n Data([0x01] + Data(repeating: 0x00, count: 31)), // Point of order 1\n Data([0x00] + Data(repeating: 0x00, count: 30) + [0x01]), // Another low-order point\n Data([0xe0, 0xeb, 0x7a, 0x7c, 0x3b, 0x41, 0xb8, 0xae, 0x16, 0x56, 0xe3,\n 0xfa, 0xf1, 0x9f, 0xc4, 0x6a, 0xda, 0x09, 0x8d, 0xeb, 0x9c, 0x32,\n 0xb1, 0xfd, 0x86, 0x62, 0x05, 0x16, 0x5f, 0x49, 0xb8, 0x00]), // Low order point\n Data([0x5f, 0x9c, 0x95, 0xbc, 0xa3, 0x50, 0x8c, 0x24, 0xb1, 0xd0, 0xb1,\n 0x55, 0x9c, 0x83, 0xef, 0x5b, 0x04, 0x44, 0x5c, 0xc4, 0x58, 0x1c,\n 0x8e, 0x86, 0xd8, 0x22, 0x4e, 0xdd, 0xd0, 0x9f, 0x11, 0x57]), // Low order point\n Data(repeating: 0xFF, count: 32), // All ones\n Data([0xda, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), // Another bad point\n Data([0xdb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]) // Another bad point\n ]\n \n // Check against known bad points\n if lowOrderPoints.contains(keyData) {\n SecureLogger.log(\"Low-order point detected\", category: SecureLogger.security, level: .warning)\n throw NoiseError.invalidPublicKey\n }\n \n // Try to create the key - CryptoKit will validate curve points internally\n do {\n let publicKey = try Curve25519.KeyAgreement.PublicKey(rawRepresentation: keyData)\n return publicKey\n } catch {\n // If CryptoKit rejects it, it's invalid\n SecureLogger.log(\"CryptoKit validation failed\", category: SecureLogger.security, level: .warning)\n throw NoiseError.invalidPublicKey\n }\n }\n}\n"], ["/bitchat/bitchat/Noise/NoiseSession.swift", "//\n// NoiseSession.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport CryptoKit\nimport os.log\n\n// MARK: - Noise Session State\n\nenum NoiseSessionState: Equatable {\n case uninitialized\n case handshaking\n case established\n case failed(Error)\n \n static func == (lhs: NoiseSessionState, rhs: NoiseSessionState) -> Bool {\n switch (lhs, rhs) {\n case (.uninitialized, .uninitialized),\n (.handshaking, .handshaking),\n (.established, .established):\n return true\n case (.failed, .failed):\n return true // We don't compare the errors\n default:\n return false\n }\n }\n}\n\n// MARK: - Noise Session\n\nclass NoiseSession {\n let peerID: String\n let role: NoiseRole\n private var state: NoiseSessionState = .uninitialized\n private var handshakeState: NoiseHandshakeState?\n private var sendCipher: NoiseCipherState?\n private var receiveCipher: NoiseCipherState?\n \n // Keys\n private let localStaticKey: Curve25519.KeyAgreement.PrivateKey\n private var remoteStaticPublicKey: Curve25519.KeyAgreement.PublicKey?\n \n // Handshake messages for retransmission\n private var sentHandshakeMessages: [Data] = []\n private var handshakeHash: Data?\n \n // Thread safety\n private let sessionQueue = DispatchQueue(label: \"chat.bitchat.noise.session\", attributes: .concurrent)\n \n init(peerID: String, role: NoiseRole, localStaticKey: Curve25519.KeyAgreement.PrivateKey, remoteStaticKey: Curve25519.KeyAgreement.PublicKey? = nil) {\n self.peerID = peerID\n self.role = role\n self.localStaticKey = localStaticKey\n self.remoteStaticPublicKey = remoteStaticKey\n }\n \n // MARK: - Handshake\n \n func startHandshake() throws -> Data {\n return try sessionQueue.sync(flags: .barrier) {\n guard case .uninitialized = state else {\n throw NoiseSessionError.invalidState\n }\n \n // For XX pattern, we don't need remote static key upfront\n handshakeState = NoiseHandshakeState(\n role: role,\n pattern: .XX,\n localStaticKey: localStaticKey,\n remoteStaticKey: nil\n )\n \n state = .handshaking\n \n // Only initiator writes the first message\n if role == .initiator {\n let message = try handshakeState!.writeMessage()\n sentHandshakeMessages.append(message)\n return message\n } else {\n // Responder doesn't send first message in XX pattern\n return Data()\n }\n }\n }\n \n func processHandshakeMessage(_ message: Data) throws -> Data? {\n return try sessionQueue.sync(flags: .barrier) {\n SecureLogger.log(\"NoiseSession[\\(peerID)]: Processing handshake message, current state: \\(state), role: \\(role)\", category: SecureLogger.noise, level: .info)\n \n // Initialize handshake state if needed (for responders)\n if state == .uninitialized && role == .responder {\n handshakeState = NoiseHandshakeState(\n role: role,\n pattern: .XX,\n localStaticKey: localStaticKey,\n remoteStaticKey: nil\n )\n state = .handshaking\n SecureLogger.log(\"NoiseSession[\\(peerID)]: Initialized handshake state for responder\", category: SecureLogger.noise, level: .info)\n }\n \n guard case .handshaking = state, let handshake = handshakeState else {\n throw NoiseSessionError.invalidState\n }\n \n // Process incoming message\n _ = try handshake.readMessage(message)\n SecureLogger.log(\"NoiseSession[\\(peerID)]: Read handshake message, checking if complete\", category: SecureLogger.noise, level: .info)\n \n // Check if handshake is complete\n if handshake.isHandshakeComplete() {\n // Get transport ciphers\n let (send, receive) = try handshake.getTransportCiphers()\n sendCipher = send\n receiveCipher = receive\n \n // Store remote static key\n remoteStaticPublicKey = handshake.getRemoteStaticPublicKey()\n \n // Store handshake hash for channel binding\n handshakeHash = handshake.getHandshakeHash()\n \n state = .established\n handshakeState = nil // Clear handshake state\n \n SecureLogger.log(\"NoiseSession[\\(peerID)]: Handshake complete (no response needed), transitioning to established\", category: SecureLogger.noise, level: .info)\n SecureLogger.logSecurityEvent(.handshakeCompleted(peerID: peerID))\n \n return nil\n } else {\n // Generate response\n let response = try handshake.writeMessage()\n sentHandshakeMessages.append(response)\n SecureLogger.log(\"NoiseSession[\\(peerID)]: Generated handshake response of size \\(response.count)\", category: SecureLogger.noise, level: .info)\n \n // Check if handshake is complete after writing\n if handshake.isHandshakeComplete() {\n // Get transport ciphers\n let (send, receive) = try handshake.getTransportCiphers()\n sendCipher = send\n receiveCipher = receive\n \n // Store remote static key\n remoteStaticPublicKey = handshake.getRemoteStaticPublicKey()\n \n // Store handshake hash for channel binding\n handshakeHash = handshake.getHandshakeHash()\n \n state = .established\n handshakeState = nil // Clear handshake state\n \n SecureLogger.log(\"NoiseSession[\\(peerID)]: Handshake complete after writing response, transitioning to established\", category: SecureLogger.noise, level: .info)\n SecureLogger.logSecurityEvent(.handshakeCompleted(peerID: peerID))\n }\n \n return response\n }\n }\n }\n \n // MARK: - Transport\n \n func encrypt(_ plaintext: Data) throws -> Data {\n return try sessionQueue.sync(flags: .barrier) {\n guard case .established = state, let cipher = sendCipher else {\n throw NoiseSessionError.notEstablished\n }\n \n return try cipher.encrypt(plaintext: plaintext)\n }\n }\n \n func decrypt(_ ciphertext: Data) throws -> Data {\n return try sessionQueue.sync(flags: .barrier) {\n guard case .established = state, let cipher = receiveCipher else {\n throw NoiseSessionError.notEstablished\n }\n \n return try cipher.decrypt(ciphertext: ciphertext)\n }\n }\n \n // MARK: - State Management\n \n func getState() -> NoiseSessionState {\n return sessionQueue.sync {\n return state\n }\n }\n \n func isEstablished() -> Bool {\n return sessionQueue.sync {\n if case .established = state {\n return true\n }\n return false\n }\n }\n \n func getRemoteStaticPublicKey() -> Curve25519.KeyAgreement.PublicKey? {\n return sessionQueue.sync {\n return remoteStaticPublicKey\n }\n }\n \n func getHandshakeHash() -> Data? {\n return sessionQueue.sync {\n return handshakeHash\n }\n }\n \n func reset() {\n sessionQueue.sync(flags: .barrier) {\n let wasEstablished = state == .established\n state = .uninitialized\n handshakeState = nil\n sendCipher = nil\n receiveCipher = nil\n sentHandshakeMessages.removeAll()\n handshakeHash = nil\n \n if wasEstablished {\n SecureLogger.logSecurityEvent(.sessionExpired(peerID: peerID))\n }\n }\n }\n}\n\n// MARK: - Session Manager\n\nclass NoiseSessionManager {\n private var sessions: [String: NoiseSession] = [:]\n private let localStaticKey: Curve25519.KeyAgreement.PrivateKey\n private let managerQueue = DispatchQueue(label: \"chat.bitchat.noise.manager\", attributes: .concurrent)\n \n // Callbacks\n var onSessionEstablished: ((String, Curve25519.KeyAgreement.PublicKey) -> Void)?\n var onSessionFailed: ((String, Error) -> Void)?\n \n init(localStaticKey: Curve25519.KeyAgreement.PrivateKey) {\n self.localStaticKey = localStaticKey\n }\n \n // MARK: - Session Management\n \n func createSession(for peerID: String, role: NoiseRole) -> NoiseSession {\n return managerQueue.sync(flags: .barrier) {\n let session = SecureNoiseSession(\n peerID: peerID,\n role: role,\n localStaticKey: localStaticKey\n )\n sessions[peerID] = session\n return session\n }\n }\n \n func getSession(for peerID: String) -> NoiseSession? {\n return managerQueue.sync {\n return sessions[peerID]\n }\n }\n \n func removeSession(for peerID: String) {\n managerQueue.sync(flags: .barrier) {\n if let session = sessions[peerID], session.isEstablished() {\n SecureLogger.logSecurityEvent(.sessionExpired(peerID: peerID))\n }\n _ = sessions.removeValue(forKey: peerID)\n }\n }\n \n func migrateSession(from oldPeerID: String, to newPeerID: String) {\n managerQueue.sync(flags: .barrier) {\n // Check if we have a session for the old peer ID\n if let session = sessions[oldPeerID] {\n // Move the session to the new peer ID\n sessions[newPeerID] = session\n _ = sessions.removeValue(forKey: oldPeerID)\n \n SecureLogger.log(\"Migrated Noise session from \\(oldPeerID) to \\(newPeerID)\", category: SecureLogger.noise, level: .info)\n }\n }\n }\n \n func getEstablishedSessions() -> [String: NoiseSession] {\n return managerQueue.sync {\n return sessions.filter { $0.value.isEstablished() }\n }\n }\n \n // MARK: - Handshake Helpers\n \n func initiateHandshake(with peerID: String) throws -> Data {\n return try managerQueue.sync(flags: .barrier) {\n // Check if we already have an established session\n if let existingSession = sessions[peerID], existingSession.isEstablished() {\n // Session already established, don't recreate\n throw NoiseSessionError.alreadyEstablished\n }\n \n // Remove any existing non-established session\n if let existingSession = sessions[peerID], !existingSession.isEstablished() {\n _ = sessions.removeValue(forKey: peerID)\n }\n \n // Create new initiator session\n let session = SecureNoiseSession(\n peerID: peerID,\n role: .initiator,\n localStaticKey: localStaticKey\n )\n sessions[peerID] = session\n \n do {\n let handshakeData = try session.startHandshake()\n return handshakeData\n } catch {\n // Clean up failed session\n _ = sessions.removeValue(forKey: peerID)\n SecureLogger.logSecurityEvent(.handshakeFailed(peerID: peerID, error: error.localizedDescription), level: .error)\n throw error\n }\n }\n }\n \n func handleIncomingHandshake(from peerID: String, message: Data) throws -> Data? {\n // Process everything within the synchronized block to prevent race conditions\n return try managerQueue.sync(flags: .barrier) {\n var shouldCreateNew = false\n var existingSession: NoiseSession? = nil\n \n if let existing = sessions[peerID] {\n // If we have an established session, the peer must have cleared their session\n // for a good reason (e.g., decryption failure, restart, etc.)\n // We should accept the new handshake to re-establish encryption\n if existing.isEstablished() {\n SecureLogger.log(\"Accepting handshake from \\(peerID) despite existing session - peer likely cleared their session\", \n category: SecureLogger.session, level: .info)\n _ = sessions.removeValue(forKey: peerID)\n shouldCreateNew = true\n } else {\n // If we're in the middle of a handshake and receive a new initiation,\n // reset and start fresh (the other side may have restarted)\n if existing.getState() == .handshaking && message.count == 32 {\n _ = sessions.removeValue(forKey: peerID)\n shouldCreateNew = true\n } else {\n existingSession = existing\n }\n }\n } else {\n shouldCreateNew = true\n }\n \n // Get or create session\n let session: NoiseSession\n if shouldCreateNew {\n let newSession = SecureNoiseSession(\n peerID: peerID,\n role: .responder,\n localStaticKey: localStaticKey\n )\n sessions[peerID] = newSession\n session = newSession\n } else {\n session = existingSession!\n }\n \n // Process the handshake message within the synchronized block\n do {\n let response = try session.processHandshakeMessage(message)\n \n // Check if session is established after processing\n if session.isEstablished() {\n if let remoteKey = session.getRemoteStaticPublicKey() {\n // Schedule callback outside the synchronized block to prevent deadlock\n DispatchQueue.global().async { [weak self] in\n self?.onSessionEstablished?(peerID, remoteKey)\n }\n }\n }\n \n return response\n } catch {\n // Reset the session on handshake failure so next attempt can start fresh\n _ = sessions.removeValue(forKey: peerID)\n \n // Schedule callback outside the synchronized block to prevent deadlock\n DispatchQueue.global().async { [weak self] in\n self?.onSessionFailed?(peerID, error)\n }\n \n SecureLogger.logSecurityEvent(.handshakeFailed(peerID: peerID, error: error.localizedDescription), level: .error)\n throw error\n }\n }\n }\n \n // MARK: - Encryption/Decryption\n \n func encrypt(_ plaintext: Data, for peerID: String) throws -> Data {\n guard let session = getSession(for: peerID) else {\n throw NoiseSessionError.sessionNotFound\n }\n \n return try session.encrypt(plaintext)\n }\n \n func decrypt(_ ciphertext: Data, from peerID: String) throws -> Data {\n guard let session = getSession(for: peerID) else {\n throw NoiseSessionError.sessionNotFound\n }\n \n return try session.decrypt(ciphertext)\n }\n \n // MARK: - Key Management\n \n func getRemoteStaticKey(for peerID: String) -> Curve25519.KeyAgreement.PublicKey? {\n return getSession(for: peerID)?.getRemoteStaticPublicKey()\n }\n \n func getHandshakeHash(for peerID: String) -> Data? {\n return getSession(for: peerID)?.getHandshakeHash()\n }\n \n // MARK: - Session Rekeying\n \n func getSessionsNeedingRekey() -> [(peerID: String, needsRekey: Bool)] {\n return managerQueue.sync {\n var needingRekey: [(peerID: String, needsRekey: Bool)] = []\n \n for (peerID, session) in sessions {\n if let secureSession = session as? SecureNoiseSession,\n secureSession.isEstablished(),\n secureSession.needsRenegotiation() {\n needingRekey.append((peerID: peerID, needsRekey: true))\n }\n }\n \n return needingRekey\n }\n }\n \n func initiateRekey(for peerID: String) throws {\n // Remove old session\n removeSession(for: peerID)\n \n // Initiate new handshake\n _ = try initiateHandshake(with: peerID)\n \n }\n}\n\n// MARK: - Errors\n\nenum NoiseSessionError: Error {\n case invalidState\n case notEstablished\n case sessionNotFound\n case handshakeFailed(Error)\n case alreadyEstablished\n}"], ["/bitchat/bitchat/Protocols/BinaryProtocol.swift", "//\n// BinaryProtocol.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # BinaryProtocol\n///\n/// Low-level binary encoding and decoding for BitChat protocol messages.\n/// Optimized for Bluetooth LE's limited bandwidth and MTU constraints.\n///\n/// ## Overview\n/// BinaryProtocol implements an efficient binary wire format that minimizes\n/// overhead while maintaining extensibility. It handles:\n/// - Compact binary encoding with fixed headers\n/// - Optional field support via flags\n/// - Automatic compression for large payloads\n/// - Endianness handling for cross-platform compatibility\n///\n/// ## Wire Format\n/// ```\n/// Header (Fixed 13 bytes):\n/// +--------+------+-----+-----------+-------+----------------+\n/// |Version | Type | TTL | Timestamp | Flags | PayloadLength |\n/// |1 byte |1 byte|1byte| 8 bytes | 1 byte| 2 bytes |\n/// +--------+------+-----+-----------+-------+----------------+\n///\n/// Variable sections:\n/// +----------+-------------+---------+------------+\n/// | SenderID | RecipientID | Payload | Signature |\n/// | 8 bytes | 8 bytes* | Variable| 64 bytes* |\n/// +----------+-------------+---------+------------+\n/// * Optional fields based on flags\n/// ```\n///\n/// ## Design Rationale\n/// The protocol is designed for:\n/// - **Efficiency**: Minimal overhead for small messages\n/// - **Flexibility**: Optional fields via flag bits\n/// - **Compatibility**: Network byte order (big-endian)\n/// - **Performance**: Zero-copy where possible\n///\n/// ## Compression Strategy\n/// - Automatic compression for payloads > 256 bytes\n/// - LZ4 algorithm for speed over ratio\n/// - Original size stored for decompression\n/// - Flag bit indicates compressed payload\n///\n/// ## Flag Bits\n/// - Bit 0: Has recipient ID (directed message)\n/// - Bit 1: Has signature (authenticated message)\n/// - Bit 2: Is compressed (LZ4 compression applied)\n/// - Bits 3-7: Reserved for future use\n///\n/// ## Size Constraints\n/// - Maximum packet size: 65,535 bytes (16-bit length field)\n/// - Typical packet size: < 512 bytes (BLE MTU)\n/// - Minimum packet size: 21 bytes (header + sender ID)\n///\n/// ## Encoding Process\n/// 1. Construct header with fixed fields\n/// 2. Set appropriate flags\n/// 3. Compress payload if beneficial\n/// 4. Append variable-length fields\n/// 5. Calculate and append signature if needed\n///\n/// ## Decoding Process\n/// 1. Validate minimum packet size\n/// 2. Parse fixed header\n/// 3. Extract flags and determine field presence\n/// 4. Parse variable fields based on flags\n/// 5. Decompress payload if compressed\n/// 6. Verify signature if present\n///\n/// ## Error Handling\n/// - Graceful handling of malformed packets\n/// - Clear error messages for debugging\n/// - No crashes on invalid input\n/// - Logging of protocol violations\n///\n/// ## Performance Notes\n/// - Allocation-free for small messages\n/// - Streaming support for large payloads\n/// - Efficient bit manipulation\n/// - Platform-optimized byte swapping\n///\n\nimport Foundation\n\nextension Data {\n func trimmingNullBytes() -> Data {\n // Find the first null byte\n if let nullIndex = self.firstIndex(of: 0) {\n return self.prefix(nullIndex)\n }\n return self\n }\n}\n\n/// Implements binary encoding and decoding for BitChat protocol messages.\n/// Provides static methods for converting between BitchatPacket objects and\n/// their binary wire format representation.\n/// - Note: All multi-byte values use network byte order (big-endian)\nstruct BinaryProtocol {\n static let headerSize = 13\n static let senderIDSize = 8\n static let recipientIDSize = 8\n static let signatureSize = 64\n \n struct Flags {\n static let hasRecipient: UInt8 = 0x01\n static let hasSignature: UInt8 = 0x02\n static let isCompressed: UInt8 = 0x04\n }\n \n // Encode BitchatPacket to binary format\n static func encode(_ packet: BitchatPacket) -> Data? {\n var data = Data()\n \n \n // Try to compress payload if beneficial\n var payload = packet.payload\n var originalPayloadSize: UInt16? = nil\n var isCompressed = false\n \n if CompressionUtil.shouldCompress(payload) {\n if let compressedPayload = CompressionUtil.compress(payload) {\n // Store original size for decompression (2 bytes after payload)\n originalPayloadSize = UInt16(payload.count)\n payload = compressedPayload\n isCompressed = true\n \n } else {\n }\n } else {\n }\n \n // Header\n data.append(packet.version)\n data.append(packet.type)\n data.append(packet.ttl)\n \n // Timestamp (8 bytes, big-endian)\n for i in (0..<8).reversed() {\n data.append(UInt8((packet.timestamp >> (i * 8)) & 0xFF))\n }\n \n // Flags\n var flags: UInt8 = 0\n if packet.recipientID != nil {\n flags |= Flags.hasRecipient\n }\n if packet.signature != nil {\n flags |= Flags.hasSignature\n }\n if isCompressed {\n flags |= Flags.isCompressed\n }\n data.append(flags)\n \n // Payload length (2 bytes, big-endian) - includes original size if compressed\n let payloadDataSize = payload.count + (isCompressed ? 2 : 0)\n let payloadLength = UInt16(payloadDataSize)\n \n \n data.append(UInt8((payloadLength >> 8) & 0xFF))\n data.append(UInt8(payloadLength & 0xFF))\n \n // SenderID (exactly 8 bytes)\n let senderBytes = packet.senderID.prefix(senderIDSize)\n data.append(senderBytes)\n if senderBytes.count < senderIDSize {\n data.append(Data(repeating: 0, count: senderIDSize - senderBytes.count))\n }\n \n // RecipientID (if present)\n if let recipientID = packet.recipientID {\n let recipientBytes = recipientID.prefix(recipientIDSize)\n data.append(recipientBytes)\n if recipientBytes.count < recipientIDSize {\n data.append(Data(repeating: 0, count: recipientIDSize - recipientBytes.count))\n }\n }\n \n // Payload (with original size prepended if compressed)\n if isCompressed, let originalSize = originalPayloadSize {\n // Prepend original size (2 bytes, big-endian)\n data.append(UInt8((originalSize >> 8) & 0xFF))\n data.append(UInt8(originalSize & 0xFF))\n }\n data.append(payload)\n \n // Signature (if present)\n if let signature = packet.signature {\n data.append(signature.prefix(signatureSize))\n }\n \n \n // Apply padding to standard block sizes for traffic analysis resistance\n let optimalSize = MessagePadding.optimalBlockSize(for: data.count)\n let paddedData = MessagePadding.pad(data, toSize: optimalSize)\n \n \n return paddedData\n }\n \n // Decode binary data to BitchatPacket\n static func decode(_ data: Data) -> BitchatPacket? {\n // Remove padding first\n let unpaddedData = MessagePadding.unpad(data)\n \n \n guard unpaddedData.count >= headerSize + senderIDSize else { \n return nil \n }\n \n var offset = 0\n \n // Header\n let version = unpaddedData[offset]; offset += 1\n // Check if version is supported\n guard ProtocolVersion.isSupported(version) else { \n // Log unsupported version for debugging\n return nil \n }\n let type = unpaddedData[offset]; offset += 1\n let ttl = unpaddedData[offset]; offset += 1\n \n // Timestamp\n let timestampData = unpaddedData[offset..= expectedSize else { \n return nil \n }\n \n // SenderID\n let senderID = unpaddedData[offset..= 2 else { return nil }\n let originalSizeData = unpaddedData[offset.. Data? {\n var data = Data()\n \n // Message format:\n // - Flags: 1 byte (bit 0: isRelay, bit 1: isPrivate, bit 2: hasOriginalSender, bit 3: hasRecipientNickname, bit 4: hasSenderPeerID, bit 5: hasMentions)\n // - Timestamp: 8 bytes (seconds since epoch)\n // - ID length: 1 byte\n // - ID: variable\n // - Sender length: 1 byte\n // - Sender: variable\n // - Content length: 2 bytes\n // - Content: variable\n // Optional fields based on flags:\n // - Original sender length + data\n // - Recipient nickname length + data\n // - Sender peer ID length + data\n // - Mentions array\n \n var flags: UInt8 = 0\n if isRelay { flags |= 0x01 }\n if isPrivate { flags |= 0x02 }\n if originalSender != nil { flags |= 0x04 }\n if recipientNickname != nil { flags |= 0x08 }\n if senderPeerID != nil { flags |= 0x10 }\n if mentions != nil && !mentions!.isEmpty { flags |= 0x20 }\n \n data.append(flags)\n \n // Timestamp (in milliseconds)\n let timestampMillis = UInt64(timestamp.timeIntervalSince1970 * 1000)\n // Encode as 8 bytes, big-endian\n for i in (0..<8).reversed() {\n data.append(UInt8((timestampMillis >> (i * 8)) & 0xFF))\n }\n \n // ID\n if let idData = id.data(using: .utf8) {\n data.append(UInt8(min(idData.count, 255)))\n data.append(idData.prefix(255))\n } else {\n data.append(0)\n }\n \n // Sender\n if let senderData = sender.data(using: .utf8) {\n data.append(UInt8(min(senderData.count, 255)))\n data.append(senderData.prefix(255))\n } else {\n data.append(0)\n }\n \n // Content\n if let contentData = content.data(using: .utf8) {\n let length = UInt16(min(contentData.count, 65535))\n // Encode length as 2 bytes, big-endian\n data.append(UInt8((length >> 8) & 0xFF))\n data.append(UInt8(length & 0xFF))\n data.append(contentData.prefix(Int(length)))\n } else {\n data.append(contentsOf: [0, 0])\n }\n \n // Optional fields\n if let originalSender = originalSender, let origData = originalSender.data(using: .utf8) {\n data.append(UInt8(min(origData.count, 255)))\n data.append(origData.prefix(255))\n }\n \n if let recipientNickname = recipientNickname, let recipData = recipientNickname.data(using: .utf8) {\n data.append(UInt8(min(recipData.count, 255)))\n data.append(recipData.prefix(255))\n }\n \n if let senderPeerID = senderPeerID, let peerData = senderPeerID.data(using: .utf8) {\n data.append(UInt8(min(peerData.count, 255)))\n data.append(peerData.prefix(255))\n }\n \n // Mentions array\n if let mentions = mentions {\n data.append(UInt8(min(mentions.count, 255))) // Number of mentions\n for mention in mentions.prefix(255) {\n if let mentionData = mention.data(using: .utf8) {\n data.append(UInt8(min(mentionData.count, 255)))\n data.append(mentionData.prefix(255))\n } else {\n data.append(0)\n }\n }\n }\n \n \n return data\n }\n \n static func fromBinaryPayload(_ data: Data) -> BitchatMessage? {\n // Create an immutable copy to prevent threading issues\n let dataCopy = Data(data)\n \n \n guard dataCopy.count >= 13 else { \n return nil \n }\n \n var offset = 0\n \n // Flags\n guard offset < dataCopy.count else { \n return nil \n }\n let flags = dataCopy[offset]; offset += 1\n let isRelay = (flags & 0x01) != 0\n let isPrivate = (flags & 0x02) != 0\n let hasOriginalSender = (flags & 0x04) != 0\n let hasRecipientNickname = (flags & 0x08) != 0\n let hasSenderPeerID = (flags & 0x10) != 0\n let hasMentions = (flags & 0x20) != 0\n \n // Timestamp\n guard offset + 8 <= dataCopy.count else { \n return nil \n }\n let timestampData = dataCopy[offset.. 0 {\n mentions = []\n for _ in 0..\n//\n\nimport Foundation\nimport Combine\nimport CryptoKit\n\nstruct RetryableMessage {\n let id: String\n let originalMessageID: String? \n let originalTimestamp: Date?\n let content: String\n let mentions: [String]?\n let isPrivate: Bool\n let recipientPeerID: String?\n let recipientNickname: String?\n let retryCount: Int\n let maxRetries: Int = 3\n let nextRetryTime: Date\n}\n\nclass MessageRetryService {\n static let shared = MessageRetryService()\n \n private var retryQueue: [RetryableMessage] = []\n private var retryTimer: Timer?\n private let retryInterval: TimeInterval = 2.0 // Retry every 2 seconds for faster sync\n private let maxQueueSize = 50\n \n weak var meshService: BluetoothMeshService?\n \n private init() {\n startRetryTimer()\n }\n \n deinit {\n retryTimer?.invalidate()\n }\n \n private func startRetryTimer() {\n retryTimer = Timer.scheduledTimer(withTimeInterval: retryInterval, repeats: true) { [weak self] _ in\n self?.processRetryQueue()\n }\n }\n \n func addMessageForRetry(\n content: String,\n mentions: [String]? = nil,\n isPrivate: Bool = false,\n recipientPeerID: String? = nil,\n recipientNickname: String? = nil,\n originalMessageID: String? = nil,\n originalTimestamp: Date? = nil\n ) {\n // Don't queue empty or whitespace-only messages\n guard !content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {\n return\n }\n \n // Don't queue if we're at capacity\n guard retryQueue.count < maxQueueSize else {\n return\n }\n \n // Check if this message is already in the queue\n if let messageID = originalMessageID {\n let alreadyQueued = retryQueue.contains { msg in\n msg.originalMessageID == messageID\n }\n if alreadyQueued {\n return // Don't add duplicate\n }\n }\n \n let retryMessage = RetryableMessage(\n id: UUID().uuidString,\n originalMessageID: originalMessageID,\n originalTimestamp: originalTimestamp,\n content: content,\n mentions: mentions,\n isPrivate: isPrivate,\n recipientPeerID: recipientPeerID,\n recipientNickname: recipientNickname,\n retryCount: 0,\n nextRetryTime: Date().addingTimeInterval(retryInterval)\n )\n \n retryQueue.append(retryMessage)\n \n // Sort the queue by original timestamp to maintain message order\n retryQueue.sort { (msg1, msg2) in\n let time1 = msg1.originalTimestamp ?? Date.distantPast\n let time2 = msg2.originalTimestamp ?? Date.distantPast\n return time1 < time2\n }\n }\n \n private func processRetryQueue() {\n guard meshService != nil else { return }\n \n let now = Date()\n var messagesToRetry: [RetryableMessage] = []\n var updatedQueue: [RetryableMessage] = []\n \n for message in retryQueue {\n if message.nextRetryTime <= now {\n messagesToRetry.append(message)\n } else {\n updatedQueue.append(message)\n }\n }\n \n retryQueue = updatedQueue\n \n // Sort messages by original timestamp to maintain order\n messagesToRetry.sort { (msg1, msg2) in\n let time1 = msg1.originalTimestamp ?? Date.distantPast\n let time2 = msg2.originalTimestamp ?? Date.distantPast\n return time1 < time2\n }\n \n // Send messages with delay to maintain order\n for (index, message) in messagesToRetry.enumerated() {\n // Check if we should still retry\n if message.retryCount >= message.maxRetries {\n continue\n }\n \n // Add delay between messages to ensure proper ordering\n let delay = Double(index) * 0.05 // 50ms between messages\n \n DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in\n guard let self = self,\n let meshService = self.meshService else { return }\n \n // Check connectivity before retrying\n let viewModel = meshService.delegate as? ChatViewModel\n let connectedPeers = viewModel?.connectedPeers ?? []\n \n if message.isPrivate {\n // For private messages, check if recipient is connected\n if let recipientID = message.recipientPeerID,\n connectedPeers.contains(recipientID) {\n // Retry private message\n meshService.sendPrivateMessage(\n message.content,\n to: recipientID,\n recipientNickname: message.recipientNickname ?? \"unknown\",\n messageID: message.originalMessageID\n )\n } else {\n // Recipient not connected, keep in queue with updated retry time\n var updatedMessage = message\n updatedMessage = RetryableMessage(\n id: message.id,\n originalMessageID: message.originalMessageID,\n originalTimestamp: message.originalTimestamp,\n content: message.content,\n mentions: message.mentions,\n isPrivate: message.isPrivate,\n recipientPeerID: message.recipientPeerID,\n recipientNickname: message.recipientNickname,\n retryCount: message.retryCount + 1,\n nextRetryTime: Date().addingTimeInterval(self.retryInterval * Double(message.retryCount + 2))\n )\n self.retryQueue.append(updatedMessage)\n }\n } else {\n // Regular message\n if !connectedPeers.isEmpty {\n meshService.sendMessage(\n message.content,\n mentions: message.mentions ?? [],\n to: nil,\n messageID: message.originalMessageID,\n timestamp: message.originalTimestamp\n )\n } else {\n // No peers connected, keep in queue\n var updatedMessage = message\n updatedMessage = RetryableMessage(\n id: message.id,\n originalMessageID: message.originalMessageID,\n originalTimestamp: message.originalTimestamp,\n content: message.content,\n mentions: message.mentions,\n isPrivate: message.isPrivate,\n recipientPeerID: message.recipientPeerID,\n recipientNickname: message.recipientNickname,\n retryCount: message.retryCount + 1,\n nextRetryTime: Date().addingTimeInterval(self.retryInterval * Double(message.retryCount + 2))\n )\n self.retryQueue.append(updatedMessage)\n }\n }\n }\n }\n }\n \n func clearRetryQueue() {\n retryQueue.removeAll()\n }\n \n func getRetryQueueCount() -> Int {\n return retryQueue.count\n }\n}\n"], ["/bitchat/bitchat/Services/KeychainManager.swift", "//\n// KeychainManager.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport Security\nimport os.log\n\nclass KeychainManager {\n static let shared = KeychainManager()\n \n // Use consistent service name for all keychain items\n private let service = \"chat.bitchat\"\n private let appGroup = \"group.chat.bitchat\"\n \n private init() {\n // Clean up legacy keychain items on first run\n cleanupLegacyKeychainItems()\n }\n \n private func cleanupLegacyKeychainItems() {\n // Check if we've already done cleanup\n let cleanupKey = \"bitchat.keychain.cleanup.v2\"\n if UserDefaults.standard.bool(forKey: cleanupKey) {\n return\n }\n \n \n // List of old service names to migrate from\n let legacyServices = [\n \"com.bitchat.passwords\",\n \"com.bitchat.deviceidentity\",\n \"com.bitchat.noise.identity\",\n \"chat.bitchat.passwords\",\n \"bitchat.keychain\"\n ]\n \n var migratedItems = 0\n \n // Try to migrate identity keys\n for oldService in legacyServices {\n // Check for noise identity key\n let query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: oldService,\n kSecAttrAccount as String: \"identity_noiseStaticKey\",\n kSecReturnData as String: true\n ]\n \n var result: AnyObject?\n let status = SecItemCopyMatching(query as CFDictionary, &result)\n \n if status == errSecSuccess, let data = result as? Data {\n // Save to new service\n if saveIdentityKey(data, forKey: \"noiseStaticKey\") {\n migratedItems += 1\n SecureLogger.logKeyOperation(\"migrate\", keyType: \"noiseStaticKey\", success: true)\n }\n // Delete from old service\n let deleteQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: oldService,\n kSecAttrAccount as String: \"identity_noiseStaticKey\"\n ]\n SecItemDelete(deleteQuery as CFDictionary)\n }\n }\n \n // Clean up all other legacy items\n for oldService in legacyServices {\n let deleteQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: oldService\n ]\n \n SecItemDelete(deleteQuery as CFDictionary)\n }\n \n \n // Mark cleanup as done\n UserDefaults.standard.set(true, forKey: cleanupKey)\n }\n \n \n private func isSandboxed() -> Bool {\n #if os(macOS)\n let environment = ProcessInfo.processInfo.environment\n return environment[\"APP_SANDBOX_CONTAINER_ID\"] != nil\n #else\n return false\n #endif\n }\n \n // MARK: - Identity Keys\n \n func saveIdentityKey(_ keyData: Data, forKey key: String) -> Bool {\n let fullKey = \"identity_\\(key)\"\n let result = saveData(keyData, forKey: fullKey)\n SecureLogger.logKeyOperation(\"save\", keyType: key, success: result)\n return result\n }\n \n func getIdentityKey(forKey key: String) -> Data? {\n let fullKey = \"identity_\\(key)\"\n return retrieveData(forKey: fullKey)\n }\n \n func deleteIdentityKey(forKey key: String) -> Bool {\n let result = delete(forKey: \"identity_\\(key)\")\n SecureLogger.logKeyOperation(\"delete\", keyType: key, success: result)\n return result\n }\n \n // MARK: - Generic Operations\n \n private func save(_ value: String, forKey key: String) -> Bool {\n guard let data = value.data(using: .utf8) else { return false }\n return saveData(data, forKey: key)\n }\n \n private func saveData(_ data: Data, forKey key: String) -> Bool {\n // Delete any existing item first to ensure clean state\n _ = delete(forKey: key)\n \n // Build query with all necessary attributes for sandboxed apps\n var query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrAccount as String: key,\n kSecValueData as String: data,\n kSecAttrService as String: service,\n // Important for sandboxed apps: make it accessible when unlocked\n kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlocked\n ]\n \n // Add a label for easier debugging\n query[kSecAttrLabel as String] = \"bitchat-\\(key)\"\n \n // For sandboxed apps, use the app group for sharing between app instances\n if isSandboxed() {\n query[kSecAttrAccessGroup as String] = appGroup\n }\n \n // For sandboxed macOS apps, we need to ensure the item is NOT synchronized\n #if os(macOS)\n query[kSecAttrSynchronizable as String] = false\n #endif\n \n let status = SecItemAdd(query as CFDictionary, nil)\n \n if status == errSecSuccess {\n return true\n } else if status == -34018 {\n SecureLogger.logError(NSError(domain: \"Keychain\", code: -34018), context: \"Missing keychain entitlement\", category: SecureLogger.keychain)\n } else if status != errSecDuplicateItem {\n SecureLogger.logError(NSError(domain: \"Keychain\", code: Int(status)), context: \"Error saving to keychain\", category: SecureLogger.keychain)\n }\n \n return false\n }\n \n private func retrieve(forKey key: String) -> String? {\n guard let data = retrieveData(forKey: key) else { return nil }\n return String(data: data, encoding: .utf8)\n }\n \n private func retrieveData(forKey key: String) -> Data? {\n var query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrAccount as String: key,\n kSecAttrService as String: service,\n kSecReturnData as String: true,\n kSecMatchLimit as String: kSecMatchLimitOne\n ]\n \n // For sandboxed apps, use the app group\n if isSandboxed() {\n query[kSecAttrAccessGroup as String] = appGroup\n }\n \n var result: AnyObject?\n let status = SecItemCopyMatching(query as CFDictionary, &result)\n \n if status == errSecSuccess {\n return result as? Data\n } else if status == -34018 {\n SecureLogger.logError(NSError(domain: \"Keychain\", code: -34018), context: \"Missing keychain entitlement\", category: SecureLogger.keychain)\n }\n \n return nil\n }\n \n private func delete(forKey key: String) -> Bool {\n // Build basic query\n var query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrAccount as String: key,\n kSecAttrService as String: service\n ]\n \n // For sandboxed apps, use the app group\n if isSandboxed() {\n query[kSecAttrAccessGroup as String] = appGroup\n }\n \n let status = SecItemDelete(query as CFDictionary)\n return status == errSecSuccess || status == errSecItemNotFound\n }\n \n // MARK: - Cleanup\n \n func deleteAllPasswords() -> Bool {\n var query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword\n ]\n \n // Add service if not empty\n if !service.isEmpty {\n query[kSecAttrService as String] = service\n }\n \n let status = SecItemDelete(query as CFDictionary)\n return status == errSecSuccess || status == errSecItemNotFound\n }\n \n // Force cleanup to run again (for development/testing)\n func resetCleanupFlag() {\n UserDefaults.standard.removeObject(forKey: \"bitchat.keychain.cleanup.v2\")\n }\n \n \n // Delete ALL keychain data for panic mode\n func deleteAllKeychainData() -> Bool {\n SecureLogger.log(\"Panic mode - deleting all keychain data\", category: SecureLogger.security, level: .warning)\n \n var totalDeleted = 0\n \n // Search without service restriction to catch all items\n let searchQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecMatchLimit as String: kSecMatchLimitAll,\n kSecReturnAttributes as String: true\n ]\n \n var result: AnyObject?\n let searchStatus = SecItemCopyMatching(searchQuery as CFDictionary, &result)\n \n if searchStatus == errSecSuccess, let items = result as? [[String: Any]] {\n for item in items {\n var shouldDelete = false\n let account = item[kSecAttrAccount as String] as? String ?? \"\"\n let service = item[kSecAttrService as String] as? String ?? \"\"\n \n // ONLY delete if service name contains \"bitchat\"\n // This is the safest approach - we only touch items we know are ours\n if service.lowercased().contains(\"bitchat\") {\n shouldDelete = true\n }\n \n if shouldDelete {\n // Build delete query with all available attributes for precise deletion\n var deleteQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword\n ]\n \n if !account.isEmpty {\n deleteQuery[kSecAttrAccount as String] = account\n }\n if !service.isEmpty {\n deleteQuery[kSecAttrService as String] = service\n }\n \n // Add access group if present\n if let accessGroup = item[kSecAttrAccessGroup as String] as? String,\n !accessGroup.isEmpty && accessGroup != \"test\" {\n deleteQuery[kSecAttrAccessGroup as String] = accessGroup\n }\n \n let deleteStatus = SecItemDelete(deleteQuery as CFDictionary)\n if deleteStatus == errSecSuccess {\n totalDeleted += 1\n SecureLogger.log(\"Deleted keychain item: \\(account) from \\(service)\", category: SecureLogger.keychain, level: .info)\n }\n }\n }\n }\n \n // Also try to delete by known service names (in case we missed any)\n let knownServices = [\n \"chat.bitchat\",\n \"com.bitchat.passwords\",\n \"com.bitchat.deviceidentity\", \n \"com.bitchat.noise.identity\",\n \"chat.bitchat.passwords\",\n \"bitchat.keychain\",\n \"bitchat\",\n \"com.bitchat\"\n ]\n \n for serviceName in knownServices {\n let query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: serviceName\n ]\n \n let status = SecItemDelete(query as CFDictionary)\n if status == errSecSuccess {\n totalDeleted += 1\n }\n }\n \n SecureLogger.log(\"Panic mode cleanup completed. Total items deleted: \\(totalDeleted)\", category: SecureLogger.keychain, level: .warning)\n \n return totalDeleted > 0\n }\n \n // MARK: - Debug\n \n func verifyIdentityKeyExists() -> Bool {\n let key = \"identity_noiseStaticKey\"\n return retrieveData(forKey: key) != nil\n }\n \n // Aggressive cleanup for legacy items - can be called manually\n func aggressiveCleanupLegacyItems() -> Int {\n var deletedCount = 0\n \n // List of KNOWN bitchat service names from our development history\n let knownBitchatServices = [\n \"com.bitchat.passwords\",\n \"com.bitchat.deviceidentity\",\n \"com.bitchat.noise.identity\",\n \"chat.bitchat.passwords\",\n \"bitchat.keychain\",\n \"Bitchat\",\n \"BitChat\"\n ]\n \n // First, delete all items from known legacy services\n for legacyService in knownBitchatServices {\n let deleteQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: legacyService\n ]\n \n let status = SecItemDelete(deleteQuery as CFDictionary)\n if status == errSecSuccess {\n deletedCount += 1\n }\n }\n \n // Now search for items that have our specific account patterns with bitchat service names\n let searchQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecMatchLimit as String: kSecMatchLimitAll,\n kSecReturnAttributes as String: true\n ]\n \n var result: AnyObject?\n let status = SecItemCopyMatching(searchQuery as CFDictionary, &result)\n \n if status == errSecSuccess, let items = result as? [[String: Any]] {\n for item in items {\n let account = item[kSecAttrAccount as String] as? String ?? \"\"\n let service = item[kSecAttrService as String] as? String ?? \"\"\n \n // ONLY delete if service name contains \"bitchat\" somewhere\n // This ensures we never touch other apps' keychain items\n var shouldDelete = false\n \n // Check if service contains \"bitchat\" (case insensitive) but NOT our current service\n let serviceLower = service.lowercased()\n if service != self.service && serviceLower.contains(\"bitchat\") {\n shouldDelete = true\n }\n \n if shouldDelete {\n // Build precise delete query\n let deleteQuery: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrService as String: service,\n kSecAttrAccount as String: account\n ]\n \n let deleteStatus = SecItemDelete(deleteQuery as CFDictionary)\n if deleteStatus == errSecSuccess {\n deletedCount += 1\n }\n }\n }\n }\n \n return deletedCount\n }\n}"], ["/bitchat/bitchat/Noise/NoiseHandshakeCoordinator.swift", "//\n// NoiseHandshakeCoordinator.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\n\n/// Coordinates Noise handshakes to prevent race conditions and ensure reliable encryption establishment\nclass NoiseHandshakeCoordinator {\n \n // MARK: - Handshake State\n \n enum HandshakeState: Equatable {\n case idle\n case waitingToInitiate(since: Date)\n case initiating(attempt: Int, lastAttempt: Date)\n case responding(since: Date)\n case waitingForResponse(messagesSent: [Data], timeout: Date)\n case established(since: Date)\n case failed(reason: String, canRetry: Bool, lastAttempt: Date)\n \n var isActive: Bool {\n switch self {\n case .idle, .established, .failed:\n return false\n default:\n return true\n }\n }\n }\n \n // MARK: - Properties\n \n private var handshakeStates: [String: HandshakeState] = [:]\n private var handshakeQueue = DispatchQueue(label: \"chat.bitchat.noise.handshake\", attributes: .concurrent)\n \n // Configuration\n private let maxHandshakeAttempts = 3\n private let handshakeTimeout: TimeInterval = 10.0\n private let retryDelay: TimeInterval = 2.0\n private let minTimeBetweenHandshakes: TimeInterval = 1.0 // Reduced from 5.0 for faster recovery\n \n // Track handshake messages to detect duplicates\n private var processedHandshakeMessages: Set = []\n private let messageHistoryLimit = 100\n \n // MARK: - Role Determination\n \n /// Deterministically determine who should initiate the handshake\n /// Lower peer ID becomes the initiator to prevent simultaneous attempts\n func determineHandshakeRole(myPeerID: String, remotePeerID: String) -> NoiseRole {\n // Use simple string comparison for deterministic ordering\n return myPeerID < remotePeerID ? .initiator : .responder\n }\n \n /// Check if we should initiate handshake with a peer\n func shouldInitiateHandshake(myPeerID: String, remotePeerID: String, forceIfStale: Bool = false) -> Bool {\n return handshakeQueue.sync {\n // Check if we're already in an active handshake\n if let state = handshakeStates[remotePeerID], state.isActive {\n // Check if the handshake is stale and we should force a new one\n if forceIfStale {\n switch state {\n case .initiating(_, let lastAttempt):\n if Date().timeIntervalSince(lastAttempt) > handshakeTimeout {\n SecureLogger.log(\"Forcing new handshake with \\(remotePeerID) - previous stuck in initiating\", \n category: SecureLogger.handshake, level: .warning)\n return true\n }\n default:\n break\n }\n }\n \n SecureLogger.log(\"Already in active handshake with \\(remotePeerID), state: \\(state)\", \n category: SecureLogger.handshake, level: .debug)\n return false\n }\n \n // Check role\n let role = determineHandshakeRole(myPeerID: myPeerID, remotePeerID: remotePeerID)\n if role != .initiator {\n SecureLogger.log(\"Not initiator for handshake with \\(remotePeerID) (my: \\(myPeerID), their: \\(remotePeerID))\", \n category: SecureLogger.handshake, level: .debug)\n return false\n }\n \n // Check if we've failed recently and can't retry yet\n if case .failed(_, let canRetry, let lastAttempt) = handshakeStates[remotePeerID] {\n if !canRetry {\n return false\n }\n if Date().timeIntervalSince(lastAttempt) < retryDelay {\n return false\n }\n }\n \n return true\n }\n }\n \n /// Record that we're initiating a handshake\n func recordHandshakeInitiation(peerID: String) {\n handshakeQueue.async(flags: .barrier) {\n let attempt = self.getCurrentAttempt(for: peerID) + 1\n self.handshakeStates[peerID] = .initiating(attempt: attempt, lastAttempt: Date())\n SecureLogger.log(\"Recording handshake initiation with \\(peerID), attempt \\(attempt)\", \n category: SecureLogger.handshake, level: .info)\n }\n }\n \n /// Record that we're responding to a handshake\n func recordHandshakeResponse(peerID: String) {\n handshakeQueue.async(flags: .barrier) {\n self.handshakeStates[peerID] = .responding(since: Date())\n SecureLogger.log(\"Recording handshake response to \\(peerID)\", \n category: SecureLogger.handshake, level: .info)\n }\n }\n \n /// Record successful handshake completion\n func recordHandshakeSuccess(peerID: String) {\n handshakeQueue.async(flags: .barrier) {\n self.handshakeStates[peerID] = .established(since: Date())\n SecureLogger.log(\"Handshake successfully established with \\(peerID)\", \n category: SecureLogger.handshake, level: .info)\n }\n }\n \n /// Record handshake failure\n func recordHandshakeFailure(peerID: String, reason: String) {\n handshakeQueue.async(flags: .barrier) {\n let attempts = self.getCurrentAttempt(for: peerID)\n let canRetry = attempts < self.maxHandshakeAttempts\n self.handshakeStates[peerID] = .failed(reason: reason, canRetry: canRetry, lastAttempt: Date())\n SecureLogger.log(\"Handshake failed with \\(peerID): \\(reason), canRetry: \\(canRetry)\", \n category: SecureLogger.handshake, level: .warning)\n }\n }\n \n /// Check if we should accept an incoming handshake initiation\n func shouldAcceptHandshakeInitiation(myPeerID: String, remotePeerID: String) -> Bool {\n return handshakeQueue.sync {\n // If we're already established, reject new handshakes\n if case .established = handshakeStates[remotePeerID] {\n SecureLogger.log(\"Rejecting handshake from \\(remotePeerID) - already established\", \n category: SecureLogger.handshake, level: .debug)\n return false\n }\n \n let role = determineHandshakeRole(myPeerID: myPeerID, remotePeerID: remotePeerID)\n \n // If we're the initiator and already initiating, this is a race condition\n if role == .initiator {\n if case .initiating = handshakeStates[remotePeerID] {\n // They shouldn't be initiating, but accept it to recover from race condition\n SecureLogger.log(\"Accepting handshake from \\(remotePeerID) despite being initiator (race condition recovery)\", \n category: SecureLogger.handshake, level: .warning)\n return true\n }\n }\n \n // If we're the responder, we should accept\n return true\n }\n }\n \n /// Check if this is a duplicate handshake message\n func isDuplicateHandshakeMessage(_ data: Data) -> Bool {\n return handshakeQueue.sync {\n if processedHandshakeMessages.contains(data) {\n return true\n }\n \n // Add to processed messages with size limit\n if processedHandshakeMessages.count >= messageHistoryLimit {\n processedHandshakeMessages.removeAll()\n }\n processedHandshakeMessages.insert(data)\n return false\n }\n }\n \n /// Get time to wait before next handshake attempt\n func getRetryDelay(for peerID: String) -> TimeInterval? {\n return handshakeQueue.sync {\n guard let state = handshakeStates[peerID] else { return nil }\n \n switch state {\n case .failed(_, let canRetry, let lastAttempt):\n if !canRetry { return nil }\n let timeSinceFailure = Date().timeIntervalSince(lastAttempt)\n if timeSinceFailure >= retryDelay {\n return 0\n }\n return retryDelay - timeSinceFailure\n \n case .initiating(_, let lastAttempt):\n let timeSinceAttempt = Date().timeIntervalSince(lastAttempt)\n if timeSinceAttempt >= minTimeBetweenHandshakes {\n return 0\n }\n return minTimeBetweenHandshakes - timeSinceAttempt\n \n default:\n return nil\n }\n }\n }\n \n /// Reset handshake state for a peer\n func resetHandshakeState(for peerID: String) {\n handshakeQueue.async(flags: .barrier) {\n self.handshakeStates.removeValue(forKey: peerID)\n SecureLogger.log(\"Reset handshake state for \\(peerID)\", \n category: SecureLogger.handshake, level: .debug)\n }\n }\n \n /// Clean up stale handshake states\n func cleanupStaleHandshakes(staleTimeout: TimeInterval = 30.0) -> [String] {\n return handshakeQueue.sync {\n let now = Date()\n var stalePeerIDs: [String] = []\n \n for (peerID, state) in handshakeStates {\n var isStale = false\n \n switch state {\n case .initiating(_, let lastAttempt):\n if now.timeIntervalSince(lastAttempt) > staleTimeout {\n isStale = true\n }\n case .responding(let since):\n if now.timeIntervalSince(since) > staleTimeout {\n isStale = true\n }\n case .waitingForResponse(_, let timeout):\n if now > timeout {\n isStale = true\n }\n default:\n break\n }\n \n if isStale {\n stalePeerIDs.append(peerID)\n SecureLogger.log(\"Found stale handshake state for \\(peerID): \\(state)\", \n category: SecureLogger.handshake, level: .warning)\n }\n }\n \n // Clean up stale states\n for peerID in stalePeerIDs {\n handshakeStates.removeValue(forKey: peerID)\n }\n \n return stalePeerIDs\n }\n }\n \n /// Get current handshake state\n func getHandshakeState(for peerID: String) -> HandshakeState {\n return handshakeQueue.sync {\n return handshakeStates[peerID] ?? .idle\n }\n }\n \n /// Get current retry count for a peer\n func getRetryCount(for peerID: String) -> Int {\n return handshakeQueue.sync {\n switch handshakeStates[peerID] {\n case .initiating(let attempt, _):\n return attempt - 1 // Attempts start at 1, retries start at 0\n default:\n return 0\n }\n }\n }\n \n /// Increment retry count for a peer\n func incrementRetryCount(for peerID: String) {\n handshakeQueue.async(flags: .barrier) {\n let currentAttempt = self.getCurrentAttempt(for: peerID)\n self.handshakeStates[peerID] = .initiating(attempt: currentAttempt + 1, lastAttempt: Date())\n }\n }\n \n // MARK: - Private Helpers\n \n private func getCurrentAttempt(for peerID: String) -> Int {\n switch handshakeStates[peerID] {\n case .initiating(let attempt, _):\n return attempt\n case .failed(_, _, _):\n // Count previous attempts\n return 1 // Simplified for now\n default:\n return 0\n }\n }\n \n /// Log current handshake states for debugging\n func logHandshakeStates() {\n handshakeQueue.sync {\n SecureLogger.log(\"=== Handshake States ===\", category: SecureLogger.handshake, level: .debug)\n for (peerID, state) in handshakeStates {\n let stateDesc: String\n switch state {\n case .idle:\n stateDesc = \"idle\"\n case .waitingToInitiate(let since):\n stateDesc = \"waiting to initiate (since \\(since))\"\n case .initiating(let attempt, let lastAttempt):\n stateDesc = \"initiating (attempt \\(attempt), last: \\(lastAttempt))\"\n case .responding(let since):\n stateDesc = \"responding (since: \\(since))\"\n case .waitingForResponse(let messages, let timeout):\n stateDesc = \"waiting for response (\\(messages.count) messages, timeout: \\(timeout))\"\n case .established(let since):\n stateDesc = \"established (since \\(since))\"\n case .failed(let reason, let canRetry, let lastAttempt):\n stateDesc = \"failed: \\(reason) (canRetry: \\(canRetry), last: \\(lastAttempt))\"\n }\n SecureLogger.log(\" \\(peerID): \\(stateDesc)\", category: SecureLogger.handshake, level: .debug)\n }\n SecureLogger.log(\"========================\", category: SecureLogger.handshake, level: .debug)\n }\n }\n \n /// Clear all handshake states - used during panic mode\n func clearAllHandshakeStates() {\n handshakeQueue.async(flags: .barrier) {\n SecureLogger.log(\"Clearing all handshake states for panic mode\", category: SecureLogger.handshake, level: .warning)\n self.handshakeStates.removeAll()\n self.processedHandshakeMessages.removeAll()\n }\n }\n}"], ["/bitchat/bitchat/Identity/IdentityModels.swift", "//\n// IdentityModels.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\n///\n/// # IdentityModels\n///\n/// Defines BitChat's innovative three-layer identity model that balances\n/// privacy, security, and usability in a decentralized mesh network.\n///\n/// ## Overview\n/// BitChat's identity system separates concerns across three distinct layers:\n/// 1. **Ephemeral Identity**: Short-lived, rotatable peer IDs for privacy\n/// 2. **Cryptographic Identity**: Long-term Noise static keys for security\n/// 3. **Social Identity**: User-assigned names and trust relationships\n///\n/// This separation allows users to maintain stable cryptographic identities\n/// while frequently rotating their network identifiers for privacy.\n///\n/// ## Three-Layer Architecture\n///\n/// ### Layer 1: Ephemeral Identity\n/// - Random 8-byte peer IDs that rotate periodically\n/// - Provides network-level privacy and prevents tracking\n/// - Changes don't affect cryptographic relationships\n/// - Includes handshake state tracking\n///\n/// ### Layer 2: Cryptographic Identity\n/// - Based on Noise Protocol static key pairs\n/// - Fingerprint derived from SHA256 of public key\n/// - Enables end-to-end encryption and authentication\n/// - Persists across peer ID rotations\n///\n/// ### Layer 3: Social Identity\n/// - User-assigned names (petnames) for contacts\n/// - Trust levels from unknown to verified\n/// - Favorite/blocked status\n/// - Personal notes and metadata\n///\n/// ## Privacy Design\n/// The model is designed with privacy-first principles:\n/// - No mandatory persistent storage\n/// - Optional identity caching with user consent\n/// - Ephemeral IDs prevent long-term tracking\n/// - Social mappings stored locally only\n///\n/// ## Trust Model\n/// Four levels of trust:\n/// 1. **Unknown**: New or unverified peers\n/// 2. **Casual**: Basic interaction history\n/// 3. **Trusted**: User has explicitly trusted\n/// 4. **Verified**: Cryptographic verification completed\n///\n/// ## Identity Resolution\n/// When a peer rotates their ephemeral ID:\n/// 1. Cryptographic handshake reveals their fingerprint\n/// 2. System looks up social identity by fingerprint\n/// 3. UI seamlessly maintains user relationships\n/// 4. Historical messages remain properly attributed\n///\n/// ## Conflict Resolution\n/// Handles edge cases like:\n/// - Multiple peers claiming same nickname\n/// - Nickname changes and conflicts\n/// - Identity rotation during active chats\n/// - Network partitions and rejoins\n///\n/// ## Usage Example\n/// ```swift\n/// // When peer connects with new ID\n/// let ephemeral = EphemeralIdentity(peerID: \"abc123\", ...)\n/// // After handshake\n/// let crypto = CryptographicIdentity(fingerprint: \"sha256...\", ...)\n/// // User assigns name\n/// let social = SocialIdentity(localPetname: \"Alice\", ...)\n/// ```\n///\n\nimport Foundation\n\n// MARK: - Three-Layer Identity Model\n\n/// Represents the ephemeral layer of identity - short-lived peer IDs that provide network privacy.\n/// These IDs rotate periodically to prevent tracking while maintaining cryptographic relationships.\nstruct EphemeralIdentity {\n let peerID: String // 8 random bytes\n let sessionStart: Date\n var handshakeState: HandshakeState\n}\n\nenum HandshakeState {\n case none\n case initiated\n case inProgress\n case completed(fingerprint: String)\n case failed(reason: String)\n}\n\n/// Represents the cryptographic layer of identity - the stable Noise Protocol static key pair.\n/// This identity persists across ephemeral ID rotations and enables secure communication.\n/// The fingerprint serves as the permanent identifier for a peer's cryptographic identity.\nstruct CryptographicIdentity: Codable {\n let fingerprint: String // SHA256 of public key\n let publicKey: Data // Noise static public key\n let firstSeen: Date\n let lastHandshake: Date?\n}\n\n/// Represents the social layer of identity - user-assigned names and trust relationships.\n/// This layer provides human-friendly identification and relationship management.\n/// All data in this layer is local-only and never transmitted over the network.\nstruct SocialIdentity: Codable {\n let fingerprint: String\n var localPetname: String? // User's name for this peer\n var claimedNickname: String // What peer calls themselves\n var trustLevel: TrustLevel\n var isFavorite: Bool\n var isBlocked: Bool\n var notes: String?\n}\n\nenum TrustLevel: String, Codable {\n case unknown = \"unknown\"\n case casual = \"casual\"\n case trusted = \"trusted\"\n case verified = \"verified\"\n}\n\n// MARK: - Identity Cache\n\n/// Persistent storage for identity mappings and relationships.\n/// Provides efficient lookup between fingerprints, nicknames, and social identities.\n/// Storage is optional and controlled by user privacy settings.\nstruct IdentityCache: Codable {\n // Fingerprint -> Social mapping\n var socialIdentities: [String: SocialIdentity] = [:]\n \n // Nickname -> [Fingerprints] reverse index\n // Multiple fingerprints can claim same nickname\n var nicknameIndex: [String: Set] = [:]\n \n // Verified fingerprints (cryptographic proof)\n var verifiedFingerprints: Set = []\n \n // Last interaction timestamps (privacy: optional)\n var lastInteractions: [String: Date] = [:] \n \n // Schema version for future migrations\n var version: Int = 1\n}\n\n// MARK: - Identity Resolution\n\nenum IdentityHint {\n case unknown\n case likelyKnown(fingerprint: String)\n case ambiguous(candidates: Set)\n case verified(fingerprint: String)\n}\n\n// MARK: - Pending Actions\n\nstruct PendingActions {\n var toggleFavorite: Bool?\n var setTrustLevel: TrustLevel?\n var setPetname: String?\n}\n\n// MARK: - Privacy Settings\n\nstruct PrivacySettings: Codable {\n // Level 1: Maximum privacy (default)\n var persistIdentityCache = false\n var showLastSeen = false\n \n // Level 2: Convenience\n var autoAcceptKnownFingerprints = false\n var rememberNicknameHistory = false\n \n // Level 3: Social\n var shareTrustNetworkHints = false // \"3 mutual contacts trust this person\"\n}\n\n// MARK: - Conflict Resolution\n\n/// Strategies for resolving identity conflicts in the decentralized network.\n/// Handles cases where multiple peers claim the same nickname or when\n/// identity mappings become ambiguous due to network partitions.\nenum ConflictResolution {\n case acceptNew(petname: String) // \"John (2)\"\n case rejectNew\n case blockFingerprint(String)\n case alertUser(message: String)\n}\n\n// MARK: - UI State\n\nstruct PeerUIState {\n let peerID: String\n let nickname: String\n var identityState: IdentityState\n var connectionQuality: ConnectionQuality\n \n enum IdentityState {\n case unknown // Gray - No identity info\n case unverifiedKnown(String) // Blue - Handshake done, matches cache\n case verified(String) // Green - Cryptographically verified\n case conflict(String, String) // Red - Nickname doesn't match fingerprint\n case pending // Yellow - Handshake in progress\n }\n}\n\nenum ConnectionQuality {\n case excellent\n case good\n case poor\n case disconnected\n}\n\n// MARK: - Migration Support\n// Removed LegacyFavorite - no longer needed"], ["/bitchat/bitchat/Services/DeliveryTracker.swift", "//\n// DeliveryTracker.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport Combine\n\nclass DeliveryTracker {\n static let shared = DeliveryTracker()\n \n // Track pending deliveries\n private var pendingDeliveries: [String: PendingDelivery] = [:]\n private let pendingLock = NSLock()\n \n // Track received ACKs to prevent duplicates\n private var receivedAckIDs = Set()\n private var sentAckIDs = Set()\n \n // Timeout configuration\n private let privateMessageTimeout: TimeInterval = 120 // 2 minutes\n private let roomMessageTimeout: TimeInterval = 180 // 3 minutes\n private let favoriteTimeout: TimeInterval = 600 // 10 minutes for favorites\n \n // Retry configuration\n private let maxRetries = 3\n private let retryDelay: TimeInterval = 5 // Base retry delay\n \n // Publishers for UI updates\n let deliveryStatusUpdated = PassthroughSubject<(messageID: String, status: DeliveryStatus), Never>()\n \n // Cleanup timer\n private var cleanupTimer: Timer?\n \n struct PendingDelivery {\n let messageID: String\n let sentAt: Date\n let recipientID: String\n let recipientNickname: String\n let retryCount: Int\n let isFavorite: Bool\n var timeoutTimer: Timer?\n \n var isTimedOut: Bool {\n let timeout: TimeInterval = isFavorite ? 300 : 30\n return Date().timeIntervalSince(sentAt) > timeout\n }\n \n var shouldRetry: Bool {\n return retryCount < 3 && isFavorite\n }\n }\n \n private init() {\n startCleanupTimer()\n }\n \n deinit {\n cleanupTimer?.invalidate()\n }\n \n // MARK: - Public Methods\n \n func trackMessage(_ message: BitchatMessage, recipientID: String, recipientNickname: String, isFavorite: Bool = false, expectedRecipients: Int = 1) {\n // Only track private messages\n guard message.isPrivate else { return }\n \n SecureLogger.log(\"Tracking message \\(message.id) - private: \\(message.isPrivate), recipient: \\(recipientNickname)\", category: SecureLogger.session, level: .info)\n \n \n let delivery = PendingDelivery(\n messageID: message.id,\n sentAt: Date(),\n recipientID: recipientID,\n recipientNickname: recipientNickname,\n retryCount: 0,\n isFavorite: isFavorite,\n timeoutTimer: nil\n )\n \n // Store the delivery with lock\n pendingLock.lock()\n pendingDeliveries[message.id] = delivery\n pendingLock.unlock()\n \n // Update status to sent (only if not already delivered)\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in\n guard let self = self else { return }\n \n self.pendingLock.lock()\n let stillPending = self.pendingDeliveries[message.id] != nil\n self.pendingLock.unlock()\n \n // Only update to sent if still pending (not already delivered)\n if stillPending {\n SecureLogger.log(\"Updating message \\(message.id) to sent status (still pending)\", category: SecureLogger.session, level: .debug)\n self.updateDeliveryStatus(message.id, status: .sent)\n } else {\n SecureLogger.log(\"Skipping sent status update for \\(message.id) - already delivered\", category: SecureLogger.session, level: .debug)\n }\n }\n \n // Schedule timeout (outside of lock)\n scheduleTimeout(for: message.id)\n }\n \n func processDeliveryAck(_ ack: DeliveryAck) {\n pendingLock.lock()\n defer { pendingLock.unlock() }\n \n SecureLogger.log(\"Processing delivery ACK for message \\(ack.originalMessageID) from \\(ack.recipientNickname)\", category: SecureLogger.session, level: .info)\n \n // Prevent duplicate ACK processing\n guard !receivedAckIDs.contains(ack.ackID) else {\n SecureLogger.log(\"Duplicate ACK \\(ack.ackID) - ignoring\", category: SecureLogger.session, level: .warning)\n return\n }\n receivedAckIDs.insert(ack.ackID)\n \n // Find the pending delivery\n guard let delivery = pendingDeliveries[ack.originalMessageID] else {\n // Message might have already been delivered or timed out\n SecureLogger.log(\"No pending delivery found for message \\(ack.originalMessageID)\", category: SecureLogger.session, level: .warning)\n return\n }\n \n // Cancel timeout timer\n delivery.timeoutTimer?.invalidate()\n \n // Direct message - mark as delivered\n SecureLogger.log(\"Marking private message \\(ack.originalMessageID) as delivered to \\(ack.recipientNickname)\", category: SecureLogger.session, level: .info)\n updateDeliveryStatus(ack.originalMessageID, status: .delivered(to: ack.recipientNickname, at: Date()))\n pendingDeliveries.removeValue(forKey: ack.originalMessageID)\n }\n \n func generateAck(for message: BitchatMessage, myPeerID: String, myNickname: String, hopCount: UInt8) -> DeliveryAck? {\n // Don't ACK our own messages\n guard message.senderPeerID != myPeerID else { \n return nil \n }\n \n // Only ACK private messages\n guard message.isPrivate else { \n return nil \n }\n \n // Don't ACK if we've already sent an ACK for this message\n guard !sentAckIDs.contains(message.id) else { \n return nil \n }\n sentAckIDs.insert(message.id)\n \n \n return DeliveryAck(\n originalMessageID: message.id,\n recipientID: myPeerID,\n recipientNickname: myNickname,\n hopCount: hopCount\n )\n }\n \n func clearDeliveryStatus(for messageID: String) {\n pendingLock.lock()\n defer { pendingLock.unlock() }\n \n if let delivery = pendingDeliveries[messageID] {\n delivery.timeoutTimer?.invalidate()\n }\n pendingDeliveries.removeValue(forKey: messageID)\n }\n \n // MARK: - Private Methods\n \n private func updateDeliveryStatus(_ messageID: String, status: DeliveryStatus) {\n SecureLogger.log(\"Updating delivery status for message \\(messageID): \\(status)\", category: SecureLogger.session, level: .debug)\n DispatchQueue.main.async { [weak self] in\n self?.deliveryStatusUpdated.send((messageID: messageID, status: status))\n }\n }\n \n private func scheduleTimeout(for messageID: String) {\n // Get delivery info with lock\n pendingLock.lock()\n guard let delivery = pendingDeliveries[messageID] else {\n pendingLock.unlock()\n return\n }\n let isFavorite = delivery.isFavorite\n pendingLock.unlock()\n \n let timeout = isFavorite ? favoriteTimeout : privateMessageTimeout\n \n let timer = Timer.scheduledTimer(withTimeInterval: timeout, repeats: false) { [weak self] _ in\n self?.handleTimeout(messageID: messageID)\n }\n \n pendingLock.lock()\n if var updatedDelivery = pendingDeliveries[messageID] {\n updatedDelivery.timeoutTimer = timer\n pendingDeliveries[messageID] = updatedDelivery\n }\n pendingLock.unlock()\n }\n \n private func handleTimeout(messageID: String) {\n pendingLock.lock()\n guard let delivery = pendingDeliveries[messageID] else {\n pendingLock.unlock()\n return\n }\n \n let shouldRetry = delivery.shouldRetry\n \n if shouldRetry {\n pendingLock.unlock()\n // Retry for favorites (outside of lock)\n retryDelivery(messageID: messageID)\n } else {\n // Mark as failed\n let reason = \"Message not delivered\"\n pendingDeliveries.removeValue(forKey: messageID)\n pendingLock.unlock()\n updateDeliveryStatus(messageID, status: .failed(reason: reason))\n }\n }\n \n private func retryDelivery(messageID: String) {\n pendingLock.lock()\n guard let delivery = pendingDeliveries[messageID] else {\n pendingLock.unlock()\n return\n }\n \n // Increment retry count\n let newDelivery = PendingDelivery(\n messageID: delivery.messageID,\n sentAt: delivery.sentAt,\n recipientID: delivery.recipientID,\n recipientNickname: delivery.recipientNickname,\n retryCount: delivery.retryCount + 1,\n isFavorite: delivery.isFavorite,\n timeoutTimer: nil\n )\n \n pendingDeliveries[messageID] = newDelivery\n let retryCount = delivery.retryCount\n pendingLock.unlock()\n \n // Exponential backoff for retry\n let delay = retryDelay * pow(2, Double(retryCount))\n \n DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in\n // Trigger resend through delegate or notification\n NotificationCenter.default.post(\n name: Notification.Name(\"bitchat.retryMessage\"),\n object: nil,\n userInfo: [\"messageID\": messageID]\n )\n \n // Schedule new timeout\n self?.scheduleTimeout(for: messageID)\n }\n }\n \n private func startCleanupTimer() {\n cleanupTimer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in\n self?.cleanupOldDeliveries()\n }\n }\n \n private func cleanupOldDeliveries() {\n pendingLock.lock()\n defer { pendingLock.unlock() }\n \n let now = Date()\n let maxAge: TimeInterval = 3600 // 1 hour\n \n // Clean up old pending deliveries\n pendingDeliveries = pendingDeliveries.filter { (_, delivery) in\n now.timeIntervalSince(delivery.sentAt) < maxAge\n }\n \n // Clean up old ACK IDs (keep last 1000)\n if receivedAckIDs.count > 1000 {\n receivedAckIDs.removeAll()\n }\n if sentAckIDs.count > 1000 {\n sentAckIDs.removeAll()\n }\n }\n}"], ["/bitchat/bitchat/Utils/BatteryOptimizer.swift", "//\n// BatteryOptimizer.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport Combine\n#if os(iOS)\nimport UIKit\n#elseif os(macOS)\nimport IOKit.ps\n#endif\n\nenum PowerMode {\n case performance // Max performance, battery drain OK\n case balanced // Default balanced mode\n case powerSaver // Aggressive power saving\n case ultraLowPower // Emergency mode\n \n var scanDuration: TimeInterval {\n switch self {\n case .performance: return 3.0\n case .balanced: return 2.0\n case .powerSaver: return 1.0\n case .ultraLowPower: return 0.5\n }\n }\n \n var scanPauseDuration: TimeInterval {\n switch self {\n case .performance: return 2.0\n case .balanced: return 3.0\n case .powerSaver: return 8.0\n case .ultraLowPower: return 20.0\n }\n }\n \n var maxConnections: Int {\n switch self {\n case .performance: return 20\n case .balanced: return 10\n case .powerSaver: return 5\n case .ultraLowPower: return 2\n }\n }\n \n var advertisingInterval: TimeInterval {\n // Note: iOS doesn't let us control this directly, but we can stop/start advertising\n switch self {\n case .performance: return 0.0 // Continuous\n case .balanced: return 5.0 // Advertise every 5 seconds\n case .powerSaver: return 15.0 // Advertise every 15 seconds\n case .ultraLowPower: return 30.0 // Advertise every 30 seconds\n }\n }\n \n var messageAggregationWindow: TimeInterval {\n switch self {\n case .performance: return 0.05 // 50ms\n case .balanced: return 0.1 // 100ms\n case .powerSaver: return 0.3 // 300ms\n case .ultraLowPower: return 0.5 // 500ms\n }\n }\n}\n\nclass BatteryOptimizer {\n static let shared = BatteryOptimizer()\n \n @Published var currentPowerMode: PowerMode = .balanced\n @Published var isInBackground: Bool = false\n @Published var batteryLevel: Float = 1.0\n @Published var isCharging: Bool = false\n \n private var observers: [NSObjectProtocol] = []\n \n private init() {\n setupObservers()\n updateBatteryStatus()\n }\n \n deinit {\n observers.forEach { NotificationCenter.default.removeObserver($0) }\n }\n \n private func setupObservers() {\n #if os(iOS)\n // Monitor app state\n observers.append(\n NotificationCenter.default.addObserver(\n forName: UIApplication.didEnterBackgroundNotification,\n object: nil,\n queue: .main\n ) { [weak self] _ in\n self?.isInBackground = true\n self?.updatePowerMode()\n }\n )\n \n observers.append(\n NotificationCenter.default.addObserver(\n forName: UIApplication.willEnterForegroundNotification,\n object: nil,\n queue: .main\n ) { [weak self] _ in\n self?.isInBackground = false\n self?.updatePowerMode()\n }\n )\n \n // Monitor battery\n UIDevice.current.isBatteryMonitoringEnabled = true\n \n observers.append(\n NotificationCenter.default.addObserver(\n forName: UIDevice.batteryLevelDidChangeNotification,\n object: nil,\n queue: .main\n ) { [weak self] _ in\n self?.updateBatteryStatus()\n }\n )\n \n observers.append(\n NotificationCenter.default.addObserver(\n forName: UIDevice.batteryStateDidChangeNotification,\n object: nil,\n queue: .main\n ) { [weak self] _ in\n self?.updateBatteryStatus()\n }\n )\n #endif\n }\n \n private func updateBatteryStatus() {\n #if os(iOS)\n batteryLevel = UIDevice.current.batteryLevel\n if batteryLevel < 0 {\n batteryLevel = 1.0 // Unknown battery level\n }\n \n isCharging = UIDevice.current.batteryState == .charging || \n UIDevice.current.batteryState == .full\n #elseif os(macOS)\n if let info = getMacOSBatteryInfo() {\n batteryLevel = info.level\n isCharging = info.isCharging\n }\n #endif\n \n updatePowerMode()\n }\n \n #if os(macOS)\n private func getMacOSBatteryInfo() -> (level: Float, isCharging: Bool)? {\n let snapshot = IOPSCopyPowerSourcesInfo().takeRetainedValue()\n let sources = IOPSCopyPowerSourcesList(snapshot).takeRetainedValue() as Array\n \n for source in sources {\n if let description = IOPSGetPowerSourceDescription(snapshot, source).takeUnretainedValue() as? [String: Any] {\n if let currentCapacity = description[kIOPSCurrentCapacityKey] as? Int,\n let maxCapacity = description[kIOPSMaxCapacityKey] as? Int {\n let level = Float(currentCapacity) / Float(maxCapacity)\n let isCharging = description[kIOPSPowerSourceStateKey] as? String == kIOPSACPowerValue\n return (level, isCharging)\n }\n }\n }\n return nil\n }\n #endif\n \n private func updatePowerMode() {\n // Determine optimal power mode based on:\n // 1. Battery level\n // 2. Charging status\n // 3. Background/foreground state\n \n if isCharging {\n // When charging, use performance mode unless battery is critical\n currentPowerMode = batteryLevel < 0.1 ? .balanced : .performance\n } else if isInBackground {\n // In background, always use power saving\n if batteryLevel < 0.2 {\n currentPowerMode = .ultraLowPower\n } else if batteryLevel < 0.5 {\n currentPowerMode = .powerSaver\n } else {\n currentPowerMode = .balanced\n }\n } else {\n // Foreground, not charging\n if batteryLevel < 0.1 {\n currentPowerMode = .ultraLowPower\n } else if batteryLevel < 0.3 {\n currentPowerMode = .powerSaver\n } else if batteryLevel < 0.6 {\n currentPowerMode = .balanced\n } else {\n currentPowerMode = .performance\n }\n }\n }\n \n // Manual power mode override\n func setPowerMode(_ mode: PowerMode) {\n currentPowerMode = mode\n }\n \n // Get current scan parameters\n var scanParameters: (duration: TimeInterval, pause: TimeInterval) {\n return (currentPowerMode.scanDuration, currentPowerMode.scanPauseDuration)\n }\n \n // Should we skip non-essential operations?\n var shouldSkipNonEssential: Bool {\n return currentPowerMode == .ultraLowPower || \n (currentPowerMode == .powerSaver && isInBackground)\n }\n \n // Should we reduce message frequency?\n var shouldThrottleMessages: Bool {\n return currentPowerMode == .powerSaver || currentPowerMode == .ultraLowPower\n }\n}"], ["/bitchat/bitchat/Noise/NoiseSecurityConsiderations.swift", "//\n// NoiseSecurityConsiderations.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport CryptoKit\n\n// MARK: - Security Constants\n\nenum NoiseSecurityConstants {\n // Maximum message size to prevent memory exhaustion\n static let maxMessageSize = 65535 // 64KB as per Noise spec\n \n // Maximum handshake message size\n static let maxHandshakeMessageSize = 2048 // 2KB to accommodate XX pattern\n \n // Session timeout - sessions older than this should be renegotiated\n static let sessionTimeout: TimeInterval = 86400 // 24 hours\n \n // Maximum number of messages before rekey (2^64 - 1 is the nonce limit)\n static let maxMessagesPerSession: UInt64 = 1_000_000_000 // 1 billion messages\n \n // Handshake timeout - abandon incomplete handshakes\n static let handshakeTimeout: TimeInterval = 60 // 1 minute\n \n // Maximum concurrent sessions per peer\n static let maxSessionsPerPeer = 3\n \n // Rate limiting\n static let maxHandshakesPerMinute = 10\n static let maxMessagesPerSecond = 100\n \n // Global rate limiting (across all peers)\n static let maxGlobalHandshakesPerMinute = 30\n static let maxGlobalMessagesPerSecond = 500\n}\n\n// MARK: - Security Validations\n\nstruct NoiseSecurityValidator {\n \n /// Validate message size\n static func validateMessageSize(_ data: Data) -> Bool {\n return data.count <= NoiseSecurityConstants.maxMessageSize\n }\n \n /// Validate handshake message size\n static func validateHandshakeMessageSize(_ data: Data) -> Bool {\n return data.count <= NoiseSecurityConstants.maxHandshakeMessageSize\n }\n \n /// Validate peer ID format\n static func validatePeerID(_ peerID: String) -> Bool {\n // Peer ID should be reasonable length and contain valid characters\n let validCharset = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: \"-_\"))\n return peerID.count > 0 && \n peerID.count <= 64 && \n peerID.rangeOfCharacter(from: validCharset.inverted) == nil\n }\n}\n\n// MARK: - Enhanced Noise Session with Security\n\nclass SecureNoiseSession: NoiseSession {\n private(set) var messageCount: UInt64 = 0\n private let sessionStartTime = Date()\n private(set) var lastActivityTime = Date()\n \n override func encrypt(_ plaintext: Data) throws -> Data {\n // Check session age\n if Date().timeIntervalSince(sessionStartTime) > NoiseSecurityConstants.sessionTimeout {\n throw NoiseSecurityError.sessionExpired\n }\n \n // Check message count\n if messageCount >= NoiseSecurityConstants.maxMessagesPerSession {\n throw NoiseSecurityError.sessionExhausted\n }\n \n // Validate message size\n guard NoiseSecurityValidator.validateMessageSize(plaintext) else {\n throw NoiseSecurityError.messageTooLarge\n }\n \n let encrypted = try super.encrypt(plaintext)\n messageCount += 1\n lastActivityTime = Date()\n \n return encrypted\n }\n \n override func decrypt(_ ciphertext: Data) throws -> Data {\n // Check session age\n if Date().timeIntervalSince(sessionStartTime) > NoiseSecurityConstants.sessionTimeout {\n throw NoiseSecurityError.sessionExpired\n }\n \n // Validate message size\n guard NoiseSecurityValidator.validateMessageSize(ciphertext) else {\n throw NoiseSecurityError.messageTooLarge\n }\n \n let decrypted = try super.decrypt(ciphertext)\n lastActivityTime = Date()\n \n return decrypted\n }\n \n func needsRenegotiation() -> Bool {\n // Check if we've used more than 90% of message limit\n let messageThreshold = UInt64(Double(NoiseSecurityConstants.maxMessagesPerSession) * 0.9)\n if messageCount >= messageThreshold {\n return true\n }\n \n // Check if last activity was more than 30 minutes ago\n if Date().timeIntervalSince(lastActivityTime) > NoiseSecurityConstants.sessionTimeout {\n return true\n }\n \n return false\n }\n \n // MARK: - Testing Support\n #if DEBUG\n func setLastActivityTimeForTesting(_ date: Date) {\n lastActivityTime = date\n }\n \n func setMessageCountForTesting(_ count: UInt64) {\n messageCount = count\n }\n #endif\n}\n\n// MARK: - Rate Limiter\n\nclass NoiseRateLimiter {\n private var handshakeTimestamps: [String: [Date]] = [:] // peerID -> timestamps\n private var messageTimestamps: [String: [Date]] = [:] // peerID -> timestamps\n \n // Global rate limiting\n private var globalHandshakeTimestamps: [Date] = []\n private var globalMessageTimestamps: [Date] = []\n \n private let queue = DispatchQueue(label: \"chat.bitchat.noise.ratelimit\", attributes: .concurrent)\n \n func allowHandshake(from peerID: String) -> Bool {\n return queue.sync(flags: .barrier) {\n let now = Date()\n let oneMinuteAgo = now.addingTimeInterval(-60)\n \n // Check global rate limit first\n globalHandshakeTimestamps = globalHandshakeTimestamps.filter { $0 > oneMinuteAgo }\n if globalHandshakeTimestamps.count >= NoiseSecurityConstants.maxGlobalHandshakesPerMinute {\n SecureLogger.log(\"Global handshake rate limit exceeded: \\(globalHandshakeTimestamps.count)/\\(NoiseSecurityConstants.maxGlobalHandshakesPerMinute) per minute\", category: SecureLogger.security, level: .warning)\n return false\n }\n \n // Check per-peer rate limit\n var timestamps = handshakeTimestamps[peerID] ?? []\n timestamps = timestamps.filter { $0 > oneMinuteAgo }\n \n if timestamps.count >= NoiseSecurityConstants.maxHandshakesPerMinute {\n SecureLogger.log(\"Per-peer handshake rate limit exceeded for \\(peerID): \\(timestamps.count)/\\(NoiseSecurityConstants.maxHandshakesPerMinute) per minute\", category: SecureLogger.security, level: .warning)\n return false\n }\n \n // Record new handshake\n timestamps.append(now)\n handshakeTimestamps[peerID] = timestamps\n globalHandshakeTimestamps.append(now)\n return true\n }\n }\n \n func allowMessage(from peerID: String) -> Bool {\n return queue.sync(flags: .barrier) {\n let now = Date()\n let oneSecondAgo = now.addingTimeInterval(-1)\n \n // Check global rate limit first\n globalMessageTimestamps = globalMessageTimestamps.filter { $0 > oneSecondAgo }\n if globalMessageTimestamps.count >= NoiseSecurityConstants.maxGlobalMessagesPerSecond {\n SecureLogger.log(\"Global message rate limit exceeded: \\(globalMessageTimestamps.count)/\\(NoiseSecurityConstants.maxGlobalMessagesPerSecond) per second\", category: SecureLogger.security, level: .warning)\n return false\n }\n \n // Check per-peer rate limit\n var timestamps = messageTimestamps[peerID] ?? []\n timestamps = timestamps.filter { $0 > oneSecondAgo }\n \n if timestamps.count >= NoiseSecurityConstants.maxMessagesPerSecond {\n SecureLogger.log(\"Per-peer message rate limit exceeded for \\(peerID): \\(timestamps.count)/\\(NoiseSecurityConstants.maxMessagesPerSecond) per second\", category: SecureLogger.security, level: .warning)\n return false\n }\n \n // Record new message\n timestamps.append(now)\n messageTimestamps[peerID] = timestamps\n globalMessageTimestamps.append(now)\n return true\n }\n }\n \n func reset(for peerID: String) {\n queue.async(flags: .barrier) {\n self.handshakeTimestamps.removeValue(forKey: peerID)\n self.messageTimestamps.removeValue(forKey: peerID)\n }\n }\n}\n\n// MARK: - Security Errors\n\nenum NoiseSecurityError: Error {\n case sessionExpired\n case sessionExhausted\n case messageTooLarge\n case invalidPeerID\n case rateLimitExceeded\n case handshakeTimeout\n}\n"], ["/bitchat/bitchat/Protocols/BinaryEncodingUtils.swift", "//\n// BinaryEncodingUtils.swift\n// bitchat\n//\n// Binary encoding utilities for efficient protocol messages\n//\n\nimport Foundation\n\n// MARK: - Hex Encoding/Decoding\n\nextension Data {\n func hexEncodedString() -> String {\n if self.isEmpty {\n return \"\"\n }\n return self.map { String(format: \"%02x\", $0) }.joined()\n }\n \n init?(hexString: String) {\n let len = hexString.count / 2\n var data = Data(capacity: len)\n var index = hexString.startIndex\n \n for _ in 0..> 8) & 0xFF))\n self.append(UInt8(value & 0xFF))\n }\n \n mutating func appendUInt32(_ value: UInt32) {\n self.append(UInt8((value >> 24) & 0xFF))\n self.append(UInt8((value >> 16) & 0xFF))\n self.append(UInt8((value >> 8) & 0xFF))\n self.append(UInt8(value & 0xFF))\n }\n \n mutating func appendUInt64(_ value: UInt64) {\n for i in (0..<8).reversed() {\n self.append(UInt8((value >> (i * 8)) & 0xFF))\n }\n }\n \n mutating func appendString(_ string: String, maxLength: Int = 255) {\n guard let data = string.data(using: .utf8) else { return }\n let length = Swift.min(data.count, maxLength)\n \n if maxLength <= 255 {\n self.append(UInt8(length))\n } else {\n self.appendUInt16(UInt16(length))\n }\n \n self.append(data.prefix(length))\n }\n \n mutating func appendData(_ data: Data, maxLength: Int = 65535) {\n let length = Swift.min(data.count, maxLength)\n \n if maxLength <= 255 {\n self.append(UInt8(length))\n } else {\n self.appendUInt16(UInt16(length))\n }\n \n self.append(data.prefix(length))\n }\n \n mutating func appendDate(_ date: Date) {\n let timestamp = UInt64(date.timeIntervalSince1970 * 1000) // milliseconds\n self.appendUInt64(timestamp)\n }\n \n mutating func appendUUID(_ uuid: String) {\n // Convert UUID string to 16 bytes\n var uuidData = Data(count: 16)\n \n let cleanUUID = uuid.replacingOccurrences(of: \"-\", with: \"\")\n var index = cleanUUID.startIndex\n \n for i in 0..<16 {\n guard index < cleanUUID.endIndex else { break }\n let nextIndex = cleanUUID.index(index, offsetBy: 2)\n if let byte = UInt8(String(cleanUUID[index.. UInt8? {\n guard offset >= 0 && offset < self.count else { return nil }\n let value = self[offset]\n offset += 1\n return value\n }\n \n func readUInt16(at offset: inout Int) -> UInt16? {\n guard offset + 2 <= self.count else { return nil }\n let value = UInt16(self[offset]) << 8 | UInt16(self[offset + 1])\n offset += 2\n return value\n }\n \n func readUInt32(at offset: inout Int) -> UInt32? {\n guard offset + 4 <= self.count else { return nil }\n let value = UInt32(self[offset]) << 24 |\n UInt32(self[offset + 1]) << 16 |\n UInt32(self[offset + 2]) << 8 |\n UInt32(self[offset + 3])\n offset += 4\n return value\n }\n \n func readUInt64(at offset: inout Int) -> UInt64? {\n guard offset + 8 <= self.count else { return nil }\n var value: UInt64 = 0\n for i in 0..<8 {\n value = (value << 8) | UInt64(self[offset + i])\n }\n offset += 8\n return value\n }\n \n func readString(at offset: inout Int, maxLength: Int = 255) -> String? {\n let length: Int\n \n if maxLength <= 255 {\n guard let len = readUInt8(at: &offset) else { return nil }\n length = Int(len)\n } else {\n guard let len = readUInt16(at: &offset) else { return nil }\n length = Int(len)\n }\n \n guard offset + length <= self.count else { return nil }\n \n let stringData = self[offset.. Data? {\n let length: Int\n \n if maxLength <= 255 {\n guard let len = readUInt8(at: &offset) else { return nil }\n length = Int(len)\n } else {\n guard let len = readUInt16(at: &offset) else { return nil }\n length = Int(len)\n }\n \n guard offset + length <= self.count else { return nil }\n \n let data = self[offset.. Date? {\n guard let timestamp = readUInt64(at: &offset) else { return nil }\n return Date(timeIntervalSince1970: Double(timestamp) / 1000.0)\n }\n \n func readUUID(at offset: inout Int) -> String? {\n guard offset + 16 <= self.count else { return nil }\n \n let uuidData = self[offset.. Data? {\n guard offset + count <= self.count else { return nil }\n \n let data = self[offset.. Data\n static func fromBinaryData(_ data: Data) -> Self?\n}\n\n// MARK: - Message Type Registry\n\nenum BinaryMessageType: UInt8 {\n case deliveryAck = 0x01\n case readReceipt = 0x02\n case versionHello = 0x07\n case versionAck = 0x08\n case noiseIdentityAnnouncement = 0x09\n case noiseMessage = 0x0A\n}"], ["/bitchat/bitchat/Utils/OptimizedBloomFilter.swift", "//\n// OptimizedBloomFilter.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport CryptoKit\n\n/// Optimized Bloom filter using bit-packed storage and better hash functions\nstruct OptimizedBloomFilter {\n private var bitArray: [UInt64]\n private let bitCount: Int\n private let hashCount: Int\n \n // Statistics\n private(set) var insertCount: Int = 0\n \n init(expectedItems: Int = 1000, falsePositiveRate: Double = 0.01) {\n // Calculate optimal bit count and hash count\n let m = Double(expectedItems) * abs(log(falsePositiveRate)) / (log(2) * log(2))\n self.bitCount = Int(max(64, m.rounded()))\n \n let k = Double(bitCount) / Double(expectedItems) * log(2)\n self.hashCount = Int(max(1, min(10, k.rounded())))\n \n // Initialize bit array (64 bits per UInt64)\n let arraySize = (bitCount + 63) / 64\n self.bitArray = Array(repeating: 0, count: arraySize)\n }\n \n mutating func insert(_ item: String) {\n let hashes = generateHashes(item)\n \n for i in 0.. Bool {\n let hashes = generateHashes(item)\n \n for i in 0.. [Int] {\n guard let data = item.data(using: .utf8) else {\n return Array(repeating: 0, count: hashCount)\n }\n \n // Use SHA256 for high-quality hash values\n let hash = SHA256.hash(data: data)\n let hashBytes = Array(hash)\n \n var hashes = [Int]()\n \n // Extract multiple hash values from the SHA256 output\n for i in 0.. 0 else { return 0 }\n \n // Count set bits\n var setBits = 0\n for value in bitArray {\n setBits += value.nonzeroBitCount\n }\n \n // Calculate probability: (1 - e^(-kn/m))^k\n let ratio = Double(hashCount * insertCount) / Double(bitCount)\n return pow(1 - exp(-ratio), Double(hashCount))\n }\n \n // Get memory usage in bytes\n var memorySizeBytes: Int {\n return bitArray.count * 8\n }\n}\n\n// Extension for adaptive Bloom filter that adjusts based on network size\nextension OptimizedBloomFilter {\n static func adaptive(for networkSize: Int) -> OptimizedBloomFilter {\n // Adjust parameters based on network size\n let expectedItems: Int\n let falsePositiveRate: Double\n \n switch networkSize {\n case 0..<50:\n expectedItems = 500\n falsePositiveRate = 0.01\n case 50..<200:\n expectedItems = 2000\n falsePositiveRate = 0.02\n case 200..<500:\n expectedItems = 5000\n falsePositiveRate = 0.03\n default:\n expectedItems = 10000\n falsePositiveRate = 0.05\n }\n \n return OptimizedBloomFilter(expectedItems: expectedItems, falsePositiveRate: falsePositiveRate)\n }\n}"], ["/bitchat/bitchat/Utils/LRUCache.swift", "//\n// LRUCache.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\n\n/// Thread-safe LRU (Least Recently Used) cache implementation\nfinal class LRUCache {\n private class Node {\n var key: Key\n var value: Value\n var prev: Node?\n var next: Node?\n \n init(key: Key, value: Value) {\n self.key = key\n self.value = value\n }\n }\n \n private let maxSize: Int\n private var cache: [Key: Node] = [:]\n private var head: Node?\n private var tail: Node?\n private let queue = DispatchQueue(label: \"bitchat.lrucache\", attributes: .concurrent)\n \n init(maxSize: Int) {\n self.maxSize = maxSize\n }\n \n func set(_ key: Key, value: Value) {\n queue.sync(flags: .barrier) {\n if let node = cache[key] {\n // Update existing value and move to front\n node.value = value\n moveToFront(node)\n } else {\n // Add new node\n let newNode = Node(key: key, value: value)\n cache[key] = newNode\n addToFront(newNode)\n \n // Remove oldest if over capacity\n if cache.count > maxSize {\n if let tailNode = tail {\n removeNode(tailNode)\n cache.removeValue(forKey: tailNode.key)\n }\n }\n }\n }\n }\n \n func get(_ key: Key) -> Value? {\n return queue.sync(flags: .barrier) {\n guard let node = cache[key] else { return nil }\n moveToFront(node)\n return node.value\n }\n }\n \n func contains(_ key: Key) -> Bool {\n return queue.sync {\n return cache[key] != nil\n }\n }\n \n func remove(_ key: Key) {\n queue.sync(flags: .barrier) {\n if let node = cache[key] {\n removeNode(node)\n cache.removeValue(forKey: key)\n }\n }\n }\n \n func removeAll() {\n queue.sync(flags: .barrier) {\n cache.removeAll()\n head = nil\n tail = nil\n }\n }\n \n var count: Int {\n return queue.sync {\n return cache.count\n }\n }\n \n var keys: [Key] {\n return queue.sync {\n return Array(cache.keys)\n }\n }\n \n // MARK: - Private Helpers\n \n private func addToFront(_ node: Node) {\n node.next = head\n node.prev = nil\n \n if let head = head {\n head.prev = node\n }\n \n head = node\n \n if tail == nil {\n tail = node\n }\n }\n \n private func removeNode(_ node: Node) {\n if let prev = node.prev {\n prev.next = node.next\n } else {\n head = node.next\n }\n \n if let next = node.next {\n next.prev = node.prev\n } else {\n tail = node.prev\n }\n \n node.prev = nil\n node.next = nil\n }\n \n private func moveToFront(_ node: Node) {\n guard node !== head else { return }\n removeNode(node)\n addToFront(node)\n }\n}\n\n// MARK: - Bounded Set\n\n/// Thread-safe set with maximum size using LRU eviction\nfinal class BoundedSet {\n private let cache: LRUCache\n \n init(maxSize: Int) {\n self.cache = LRUCache(maxSize: maxSize)\n }\n \n func insert(_ element: Element) {\n cache.set(element, value: true)\n }\n \n func contains(_ element: Element) -> Bool {\n return cache.get(element) != nil\n }\n \n func remove(_ element: Element) {\n cache.remove(element)\n }\n \n func removeAll() {\n cache.removeAll()\n }\n \n var count: Int {\n return cache.count\n }\n}"], ["/bitchat/bitchat/Services/NotificationService.swift", "//\n// NotificationService.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport UserNotifications\n#if os(iOS)\nimport UIKit\n#elseif os(macOS)\nimport AppKit\n#endif\n\nclass NotificationService {\n static let shared = NotificationService()\n \n private init() {}\n \n func requestAuthorization() {\n UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in\n if granted {\n // Permission granted\n } else {\n // Permission denied\n }\n }\n }\n \n func sendLocalNotification(title: String, body: String, identifier: String, userInfo: [String: Any]? = nil) {\n // For now, skip app state check entirely to avoid thread issues\n // The NotificationDelegate will handle foreground presentation\n DispatchQueue.main.async {\n let content = UNMutableNotificationContent()\n content.title = title\n content.body = body\n content.sound = .default\n if let userInfo = userInfo {\n content.userInfo = userInfo\n }\n \n let request = UNNotificationRequest(\n identifier: identifier,\n content: content,\n trigger: nil // Deliver immediately\n )\n \n UNUserNotificationCenter.current().add(request) { _ in\n // Notification added\n }\n }\n }\n \n func sendMentionNotification(from sender: String, message: String) {\n let title = \"@🫵 you were mentioned by \\(sender)\"\n let body = message\n let identifier = \"mention-\\(UUID().uuidString)\"\n \n sendLocalNotification(title: title, body: body, identifier: identifier)\n }\n \n func sendPrivateMessageNotification(from sender: String, message: String, peerID: String) {\n let title = \"🔒 private message from \\(sender)\"\n let body = message\n let identifier = \"private-\\(UUID().uuidString)\"\n let userInfo = [\"peerID\": peerID, \"senderName\": sender]\n \n sendLocalNotification(title: title, body: body, identifier: identifier, userInfo: userInfo)\n }\n \n func sendFavoriteOnlineNotification(nickname: String) {\n // Send directly without checking app state for favorites\n DispatchQueue.main.async {\n let content = UNMutableNotificationContent()\n content.title = \"⭐ \\(nickname) is online!\"\n content.body = \"wanna get in there?\"\n content.sound = .default\n \n let request = UNNotificationRequest(\n identifier: \"favorite-online-\\(UUID().uuidString)\",\n content: content,\n trigger: nil\n )\n \n UNUserNotificationCenter.current().add(request) { _ in\n // Notification added\n }\n }\n }\n \n func sendNetworkAvailableNotification(peerCount: Int) {\n let title = \"👥 bitchatters nearby!\"\n let body = peerCount == 1 ? \"1 person around\" : \"\\(peerCount) people around\"\n let identifier = \"network-available-\\(Date().timeIntervalSince1970)\"\n \n // For network notifications, we want to show them even in foreground\n // No app state check - let the notification delegate handle presentation\n DispatchQueue.main.async {\n let content = UNMutableNotificationContent()\n content.title = title\n content.body = body\n content.sound = .default\n content.interruptionLevel = .timeSensitive // Make it more prominent\n \n let request = UNNotificationRequest(\n identifier: identifier,\n content: content,\n trigger: nil // Deliver immediately\n )\n \n UNUserNotificationCenter.current().add(request) { _ in\n // Notification added\n }\n }\n }\n}\n"], ["/bitchat/bitchat/Utils/CompressionUtil.swift", "//\n// CompressionUtil.swift\n// bitchat\n//\n// This is free and unencumbered software released into the public domain.\n// For more information, see \n//\n\nimport Foundation\nimport Compression\n\nstruct CompressionUtil {\n // Compression threshold - don't compress if data is smaller than this\n static let compressionThreshold = 100 // bytes\n \n // Compress data using LZ4 algorithm (fast compression/decompression)\n static func compress(_ data: Data) -> Data? {\n // Skip compression for small data\n guard data.count >= compressionThreshold else { return nil }\n \n let maxCompressedSize = data.count + (data.count / 255) + 16\n let destinationBuffer = UnsafeMutablePointer.allocate(capacity: maxCompressedSize)\n defer { destinationBuffer.deallocate() }\n \n let compressedSize = data.withUnsafeBytes { sourceBuffer in\n guard let sourcePtr = sourceBuffer.bindMemory(to: UInt8.self).baseAddress else { return 0 }\n return compression_encode_buffer(\n destinationBuffer, data.count,\n sourcePtr, data.count,\n nil, COMPRESSION_LZ4\n )\n }\n \n guard compressedSize > 0 && compressedSize < data.count else { return nil }\n \n return Data(bytes: destinationBuffer, count: compressedSize)\n }\n \n // Decompress LZ4 compressed data\n static func decompress(_ compressedData: Data, originalSize: Int) -> Data? {\n let destinationBuffer = UnsafeMutablePointer.allocate(capacity: originalSize)\n defer { destinationBuffer.deallocate() }\n \n let decompressedSize = compressedData.withUnsafeBytes { sourceBuffer in\n guard let sourcePtr = sourceBuffer.bindMemory(to: UInt8.self).baseAddress else { return 0 }\n return compression_decode_buffer(\n destinationBuffer, originalSize,\n sourcePtr, compressedData.count,\n nil, COMPRESSION_LZ4\n )\n }\n \n guard decompressedSize > 0 else { return nil }\n \n return Data(bytes: destinationBuffer, count: decompressedSize)\n }\n \n // Helper to check if compression is worth it\n static func shouldCompress(_ data: Data) -> Bool {\n // Don't compress if:\n // 1. Data is too small\n // 2. Data appears to be already compressed (high entropy)\n guard data.count >= compressionThreshold else { return false }\n \n // Simple entropy check - count unique bytes\n var byteFrequency = [UInt8: Int]()\n for byte in data {\n byteFrequency[byte, default: 0] += 1\n }\n \n // If we have very high byte diversity, data is likely already compressed\n let uniqueByteRatio = Double(byteFrequency.count) / Double(min(data.count, 256))\n return uniqueByteRatio < 0.9 // Compress if less than 90% unique bytes\n }\n}"]], "task_instance_info": {"created_time": "2025-08-21 03:19:36", "created_task_model": "DeepSeek-R1", "function_skeleton": "private func formatFingerprint ( _ fingerprint: String ) -> String { }", "code_description": "This code segment functions to: Transform an input string into a formatted representation by inserting spacing elements at regular intervals and organizing the output into grouped blocks for improved readability."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\nprivate func formatFingerprint(_ fingerprint: String) -> String {\n return stride(from: 0, to: fingerprint.count, by: 4).map { index -> String in\n let start = fingerprint.index(fingerprint.startIndex, offsetBy: index)\n let end = fingerprint.index(start, offsetBy: 4, limitedBy: fingerprint.endIndex) ?? fingerprint.endIndex\n return String(fingerprint[start.. String {\n let uppercased = fingerprint.uppercased()\n var formatted = \"\"\n for (index, char) in uppercased.enumerated() {\n if index > 0 && index % 4 == 0 {\n if index % 16 == 0 {\n formatted += \"\\n\"\n } else {\n formatted += \" \"\n }\n }\n formatted += String(char)\n }\n return formatted\n }", "predict_code_clean": "private func formatFingerprint(_ fingerprint: String) -> String {\n return stride(from: 0, to: fingerprint.count, by: 4).map { index -> String in\n let start = fingerprint.index(fingerprint.startIndex, offsetBy: index)\n let end = fingerprint.index(start, offsetBy: 4, limitedBy: fingerprint.endIndex) ?? fingerprint.endIndex\n return String(fingerprint[start..