diff --git a/bitchat/App/AppRuntime.swift b/bitchat/App/AppRuntime.swift index bf96a8ef..09508594 100644 --- a/bitchat/App/AppRuntime.swift +++ b/bitchat/App/AppRuntime.swift @@ -278,6 +278,9 @@ final class AppRuntime: ObservableObject { chatViewModel.pruneAllExpiredPrivateMessages() chatViewModel.handleDidBecomeActive() + chatViewModel.messageRouter.retryUnconfirmedNostrMessages() + chatViewModel.groupCoordinator.flushPendingNostrDeliveries() + chatViewModel.privateConversationCoordinator.flushPendingGeohashDMs() checkForSharedContent() case .inactive: @@ -345,8 +348,10 @@ private extension AppRuntime { .sink { [weak self] allowed in guard allowed, let self, self.chatViewModel.networkActivationAllowed else { return } GeoRelayDirectory.shared.prefetchIfNeeded() - // Recover any active location channel whose subscribe() was - // dropped while offline or during the teleport activation race. + // Recover any active location channel or DM inbox subscription + // whose subscribe() was dropped while offline or before default + // relays were permitted. + self.chatViewModel.ensureNostrMessageHandlingSubscribed() self.chatViewModel.ensureCurrentGeohashSubscribed() } .store(in: &cancellables) @@ -446,6 +451,8 @@ private extension AppRuntime { if !chatViewModel.nostrHandlersSetup { chatViewModel.setupNostrMessageHandling() chatViewModel.nostrHandlersSetup = true + } else { + chatViewModel.ensureNostrMessageHandlingSubscribed() } if isInitialConnection { diff --git a/bitchat/App/PeerListModel.swift b/bitchat/App/PeerListModel.swift index 56253d9d..040049a9 100644 --- a/bitchat/App/PeerListModel.swift +++ b/bitchat/App/PeerListModel.swift @@ -229,10 +229,6 @@ final class PeerListModel: ObservableObject { chatViewModel.startPrivateChat(with: peerID) } - func toggleFavorite(peerID: PeerID) { - chatViewModel.toggleFavorite(peerID: peerID) - } - func openGeohashDirectMessage(with pubkeyHex: String) { chatViewModel.startGeohashDM(withPubkeyHex: pubkeyHex) } @@ -275,7 +271,8 @@ final class PeerListModel: ObservableObject { ) } - // 2. Mutual Nostr favorites with pinned signing keys (e.g. added via Friend Invite) + // 2. Contacts with verified Nostr routes (friend invites, legacy favorites, + // and mutual 1:1 DM exchanges) that have pinned signing keys. for (noiseKey, rel) in FavoritesPersistenceService.shared.favorites { guard rel.isMutual && rel.hasValidNostrPublicKey else { continue } let peerID = PeerID(hexData: noiseKey) @@ -303,6 +300,32 @@ final class PeerListModel: ObservableObject { } } + for (noiseKey, route) in chatViewModel.nostrPeerRouteStore.routes { + let peerID = PeerID(hexData: noiseKey) + guard !chatViewModel.isPeerBlocked(peerID), + let identity = chatViewModel.cryptoIdentity(for: peerID), + identity.fingerprint != myFingerprint, + !excludingFingerprints.contains(identity.fingerprint) else { continue } + let meshConnected = chatViewModel.connectedPeerID(forFingerprint: identity.fingerprint) != nil + if let existing = byFingerprint[identity.fingerprint] { + byFingerprint[identity.fingerprint] = GroupInviteCandidate( + peerID: existing.peerID, + fingerprint: identity.fingerprint, + displayName: existing.displayName, + isMeshConnected: existing.isMeshConnected || meshConnected, + isNostrReachable: true + ) + } else { + byFingerprint[identity.fingerprint] = GroupInviteCandidate( + peerID: peerID, + fingerprint: identity.fingerprint, + displayName: route.peerNickname, + isMeshConnected: meshConnected, + isNostrReachable: true + ) + } + } + return byFingerprint.values.sorted { if $0.isMeshConnected != $1.isMeshConnected { return $0.isMeshConnected } return $0.displayName.localizedCaseInsensitiveCompare($1.displayName) == .orderedAscending @@ -507,6 +530,13 @@ final class PeerListModel: ObservableObject { } .store(in: &cancellables) + chatViewModel.nostrPeerRouteStore.$routes + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + self?.setNeedsRefresh() + } + .store(in: &cancellables) + chatViewModel.participantTracker.$visiblePeople .receive(on: DispatchQueue.main) .sink { [weak self] _ in @@ -578,7 +608,8 @@ final class PeerListModel: ObservableObject { isFavorite: peer.favoriteStatus?.isFavorite ?? false, isConnected: peer.isConnected, isReachable: peer.isReachable, - isNostrAvailable: peer.connectionState == .nostrAvailable, + isNostrAvailable: peer.connectionState == .nostrAvailable + || (!isMe && chatViewModel.hasDirectNostrRoute(for: peer.peerID)), encryptionStatus: chatViewModel.getEncryptionStatus(for: peer.peerID), showsVerifiedBadgeWhenOffline: verifiedBadge, showsVouchedBadge: vouchedBadge @@ -728,6 +759,49 @@ final class PeerListModel: ObservableObject { rowsByKey[fingerprint] = row } + // 2b. Contacts learned from mutual 1:1 DM Nostr route exchanges + for (noiseKey, route) in chatViewModel.nostrPeerRouteStore.routes { + let peerID = PeerID(hexData: noiseKey) + guard !chatViewModel.isPeerBlocked(peerID) else { continue } + let fingerprint = noiseKey.sha256Fingerprint() + if rowsByKey[fingerprint] != nil { continue } + let meshRow = meshByFingerprint[fingerprint] + let targetPeerID = meshRow?.peerID ?? peerID + let lastMsg = latestDirectMessage(for: targetPeerID, fingerprint: fingerprint) + let reachability: InboxChatRow.Reachability = { + if meshRow?.isConnected == true { return .meshConnected } + if meshRow?.isReachable == true { return .meshReachable } + return .nostr + }() + let fallbackSubtitle: String = { + switch reachability { + case .meshConnected: + return String(localized: "inbox.status.nearby_ble", defaultValue: "Nearby over Bluetooth", comment: "Subtitle for a friend reachable over Bluetooth") + case .meshReachable: + return String(localized: "inbox.status.mesh_relayed", defaultValue: "Reachable on mesh", comment: "Subtitle for a friend reachable via multi-hop mesh") + case .nostr: + return String(localized: "inbox.status.nostr_ready", defaultValue: "Encrypted over Nostr · tap to chat", comment: "Subtitle for a friend ready over Nostr") + case .offline, .group: + return String(localized: "inbox.status.offline", defaultValue: "Offline · messages queue automatically", comment: "Subtitle for an offline friend") + } + }() + rowsByKey[fingerprint] = InboxChatRow( + peerID: targetPeerID, + pinKey: fingerprint, + displayName: meshRow?.displayName ?? route.peerNickname, + subtitle: lastMsg.map { MessageInteractionCodec.formattedPreview(for: $0.content) } ?? fallbackSubtitle, + lastActivity: lastMsg?.timestamp ?? route.updatedAt, + hasUnread: chatViewModel.hasUnreadMessages(for: targetPeerID), + isPinned: pinnedKeys.contains(fingerprint), + isMuted: mutedKeys.contains(fingerprint), + isGroup: false, + memberCount: 0, + isFavorite: false, + reachability: reachability, + disappearingTimer: chatViewModel.disappearingTimer(for: targetPeerID) + ) + } + // 3. Any other direct conversations that have messages (e.g. mesh passerby or GeoDM) for (id, conversation) in conversations.conversationsByID { guard case .direct(let handle) = id else { continue } @@ -749,7 +823,7 @@ final class PeerListModel: ObservableObject { let reachability: InboxChatRow.Reachability = { if meshRow?.isConnected == true { return .meshConnected } if meshRow?.isReachable == true { return .meshReachable } - if peerID.isGeoDM { return .nostr } + if peerID.isGeoDM || chatViewModel.hasDirectNostrRoute(for: peerID) { return .nostr } return .offline }() rowsByKey[key] = InboxChatRow( diff --git a/bitchat/App/PrivateConversationModels.swift b/bitchat/App/PrivateConversationModels.swift index 276124f8..7a79b1a1 100644 --- a/bitchat/App/PrivateConversationModels.swift +++ b/bitchat/App/PrivateConversationModels.swift @@ -96,6 +96,7 @@ enum PrivateConversationAvailability: Equatable { case bluetoothConnected case meshReachable case nostrAvailable + case nostrQueued case offline } @@ -104,16 +105,12 @@ struct PrivateConversationHeaderState: Equatable { let headerPeerID: PeerID let displayName: String let availability: PrivateConversationAvailability - let isFavorite: Bool let encryptionStatus: EncryptionStatus? var groupMeshReachableCount: Int = 0 var groupNostrReachableCount: Int = 0 + var groupNostrQueuedCount: Int = 0 var groupOtherMemberCount: Int = 0 - var supportsFavoriteToggle: Bool { - !conversationPeerID.isGeoDM && !conversationPeerID.isGroup - } - /// Group chats have no single peer identity behind the header: no /// fingerprint screen, no per-peer encryption badge. var isGroupConversation: Bool { @@ -167,16 +164,6 @@ final class PrivateConversationModel: ObservableObject { refreshSelectedConversation() } - func toggleFavorite(peerID: PeerID) { - chatViewModel.toggleFavorite(peerID: peerID) - refreshSelectedConversation() - } - - func toggleFavoriteForSelectedConversation() { - guard let headerPeerID = selectedHeaderState?.headerPeerID else { return } - toggleFavorite(peerID: headerPeerID) - } - func markMessagesAsRead(from peerID: PeerID) { chatViewModel.markPrivateMessagesAsRead(from: peerID) } @@ -323,6 +310,13 @@ final class PrivateConversationModel: ObservableObject { } .store(in: &cancellables) + chatViewModel.nostrPeerRouteStore.$routes + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + self?.refreshSelectedConversation() + } + .store(in: &cancellables) + NotificationCenter.default.publisher(for: Notification.Name("peerStatusUpdated")) .receive(on: DispatchQueue.main) .sink { [weak self] _ in @@ -336,6 +330,22 @@ final class PrivateConversationModel: ObservableObject { self?.refreshSelectedConversation() } .store(in: &cancellables) + + NostrRelayManager.shared.$isDMRelayConnected + .removeDuplicates() + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + self?.refreshSelectedConversation() + } + .store(in: &cancellables) + + NetworkActivationService.shared.$activationAllowed + .removeDuplicates() + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + self?.refreshSelectedConversation() + } + .store(in: &cancellables) } private func refreshSelectedConversation() { @@ -359,18 +369,24 @@ final class PrivateConversationModel: ObservableObject { let displayName: String var meshCount = 0 var nostrCount = 0 + var nostrQueuedCount = 0 var otherCount = 0 + let nostrRelaysUp = chatViewModel.isNostrDMRelayConnected() if let group = chatViewModel.groupStore.group(for: conversationPeerID) { displayName = "#\(group.name) (\(group.members.count))" let myFP = chatViewModel.myNoiseFingerprint() for member in group.members where member.fingerprint != myFP { otherCount += 1 let onMesh = chatViewModel.connectedPeerID(forFingerprint: member.fingerprint) != nil - let onNostr = chatViewModel.nostrReachablePeerID(forFingerprint: member.fingerprint) != nil + let hasNostrRoute = chatViewModel.resolvedNostrPubkeyHex(for: member) != nil if onMesh { meshCount += 1 - } else if onNostr { - nostrCount += 1 + } else if hasNostrRoute { + if nostrRelaysUp { + nostrCount += 1 + } else { + nostrQueuedCount += 1 + } } } } else { @@ -379,6 +395,7 @@ final class PrivateConversationModel: ObservableObject { let groupAvailability: PrivateConversationAvailability = { if meshCount > 0 { return .bluetoothConnected } if nostrCount > 0 { return .nostrAvailable } + if nostrQueuedCount > 0 { return .nostrQueued } return .offline }() return PrivateConversationHeaderState( @@ -386,10 +403,10 @@ final class PrivateConversationModel: ObservableObject { headerPeerID: conversationPeerID, displayName: displayName, availability: groupAvailability, - isFavorite: false, encryptionStatus: nil, groupMeshReachableCount: meshCount, groupNostrReachableCount: nostrCount, + groupNostrQueuedCount: nostrQueuedCount, groupOtherMemberCount: otherCount ) } @@ -398,11 +415,10 @@ final class PrivateConversationModel: ObservableObject { let peer = chatViewModel.getPeer(byID: headerPeerID) let displayName = resolveDisplayName(for: conversationPeerID, headerPeerID: headerPeerID, peer: peer) // Geo DMs are always routed through BitChat private envelopes over - // Nostr; their nostr_ keys never resolve to a reachable mesh peer, so - // resolveAvailability would report .offline. Report .nostrAvailable - // so the header shows the globe instead of a misleading "offline" tag. - let availability = conversationPeerID.isGeoDM - ? .nostrAvailable + // Nostr; reflect live relay state honestly so offline GeoDMs read as + // queued rather than live. + let availability: PrivateConversationAvailability = conversationPeerID.isGeoDM + ? (chatViewModel.isNostrDMRelayConnected() ? .nostrAvailable : .nostrQueued) : resolveAvailability(for: headerPeerID, peer: peer) let encryptionStatus: EncryptionStatus? = conversationPeerID.isGeoDM ? nil @@ -413,7 +429,6 @@ final class PrivateConversationModel: ObservableObject { headerPeerID: headerPeerID, displayName: displayName, availability: availability, - isFavorite: chatViewModel.isFavorite(peerID: headerPeerID), encryptionStatus: encryptionStatus ) } @@ -472,6 +487,7 @@ final class PrivateConversationModel: ObservableObject { } private func resolveAvailability(for headerPeerID: PeerID, peer: BitchatPeer?) -> PrivateConversationAvailability { + let nostrRelaysUp = chatViewModel.isNostrDMRelayConnected() if let connectionState = peer?.connectionState { switch connectionState { case .bluetoothConnected: @@ -479,27 +495,24 @@ final class PrivateConversationModel: ObservableObject { case .meshReachable: return .meshReachable case .nostrAvailable: - return .nostrAvailable + return nostrRelaysUp ? .nostrAvailable : .nostrQueued case .offline: - return .offline + break } } + if chatViewModel.meshService.isPeerConnected(headerPeerID) || chatViewModel.connectedPeers.contains(headerPeerID) { + return .bluetoothConnected + } if chatViewModel.meshService.isPeerReachable(headerPeerID) { return .meshReachable } let favoriteStatus = headerPeerID.noiseKey.flatMap { FavoritesPersistenceService.shared.getFavoriteStatus(for: $0) } ?? FavoritesPersistenceService.shared.getFavoriteStatus(forPeerID: headerPeerID) - if let favoriteStatus, - favoriteStatus.isMutual, - // No stored recipient key means no Nostr delivery — and the - // "end-to-end encrypted" caption keys off .nostrAvailable. - favoriteStatus.hasValidNostrPublicKey { - return .nostrAvailable - } - if chatViewModel.meshService.isPeerConnected(headerPeerID) || chatViewModel.connectedPeers.contains(headerPeerID) { - return .bluetoothConnected + let hasFavoriteNostr = (favoriteStatus?.isMutual == true && favoriteStatus?.hasValidNostrPublicKey == true) + if hasFavoriteNostr || chatViewModel.hasDirectNostrRoute(for: headerPeerID) { + return nostrRelaysUp ? .nostrAvailable : .nostrQueued } return .offline diff --git a/bitchat/Localizable.xcstrings b/bitchat/Localizable.xcstrings index 39d63c0e..775904fc 100644 --- a/bitchat/Localizable.xcstrings +++ b/bitchat/Localizable.xcstrings @@ -33737,181 +33737,181 @@ "ar" : { "stringUnit" : { "state" : "translated", - "value" : "الأوامر:\n/msg @name [message] — بدء محادثة خاصة\n/who — عرض من هنا\n/clear — مسح هذه المحادثة\n/hug @name — إرسال عناق\n/slap @name — صفعة بسمكة تراوت ضخمة\n/block @name · /unblock @name\n/fav @name · /unfav @name — المفضلة (mesh فقط)\n/group create — إنشاء مجموعة مشفّرة\n/group invite @name · /group remove @name — إدارة الأعضاء (المنشئ)\n/group leave · /group list — مغادرة مجموعاتك أو عرضها\n/ping @name — قياس زمن الذهاب والإياب (mesh فقط)\n/trace @name — مسار mesh المقدّر (mesh فقط)\n/pay — إرسال رمز cashu (ecash) في هذه المحادثة\n/drop — تثبيت ملاحظة في هذا المكان لمدة 24 ساعة (يحتاج إلى الموقع)\n/help — هذه القائمة" + "value" : "الأوامر:\n/msg @name [message] — بدء محادثة خاصة\n/who — عرض من هنا\n/clear — مسح هذه المحادثة\n/hug @name — إرسال عناق\n/slap @name — صفعة بسمكة تراوت ضخمة\n/block @name · /unblock @name\n/group create — إنشاء مجموعة مشفّرة\n/group invite @name · /group remove @name — إدارة الأعضاء (المنشئ)\n/group leave · /group list — مغادرة مجموعاتك أو عرضها\n/ping @name — قياس زمن الذهاب والإياب (mesh فقط)\n/trace @name — مسار mesh المقدّر (mesh فقط)\n/pay — إرسال رمز cashu (ecash) في هذه المحادثة\n/drop — تثبيت ملاحظة في هذا المكان لمدة 24 ساعة (يحتاج إلى الموقع)\n/help — هذه القائمة" } }, "bn" : { "stringUnit" : { "state" : "translated", - "value" : "কমান্ড:\n/msg @name [message] — প্রাইভেট চ্যাট শুরু করো\n/who — কে কে আছে দেখো\n/clear — এই চ্যাট মুছে ফেলো\n/hug @name — একটা আলিঙ্গন পাঠাও\n/slap @name — বিশাল এক ট্রাউট মাছ দিয়ে চড় মারো\n/block @name · /unblock @name\n/fav @name · /unfav @name — প্রিয় তালিকা (শুধু mesh)\n/group create — এনক্রিপ্ট করা গ্রুপ শুরু করো\n/group invite @name · /group remove @name — সদস্য ব্যবস্থাপনা (নির্মাতা)\n/group leave · /group list — গ্রুপ ছাড়ো বা তালিকা দেখো\n/ping @name — রাউন্ড-ট্রিপ সময় মাপো (শুধু mesh)\n/trace @name — আনুমানিক mesh পথ (শুধু mesh)\n/pay — এই চ্যাটে একটি cashu ecash টোকেন পাঠাও\n/drop — এই জায়গায় ২৪ ঘণ্টার জন্য একটা নোট আটকে দাও (লোকেশন লাগবে)\n/help — এই তালিকা" + "value" : "কমান্ড:\n/msg @name [message] — প্রাইভেট চ্যাট শুরু করো\n/who — কে কে আছে দেখো\n/clear — এই চ্যাট মুছে ফেলো\n/hug @name — একটা আলিঙ্গন পাঠাও\n/slap @name — বিশাল এক ট্রাউট মাছ দিয়ে চড় মারো\n/block @name · /unblock @name\n/group create — এনক্রিপ্ট করা গ্রুপ শুরু করো\n/group invite @name · /group remove @name — সদস্য ব্যবস্থাপনা (নির্মাতা)\n/group leave · /group list — গ্রুপ ছাড়ো বা তালিকা দেখো\n/ping @name — রাউন্ড-ট্রিপ সময় মাপো (শুধু mesh)\n/trace @name — আনুমানিক mesh পথ (শুধু mesh)\n/pay — এই চ্যাটে একটি cashu ecash টোকেন পাঠাও\n/drop — এই জায়গায় ২৪ ঘণ্টার জন্য একটা নোট আটকে দাও (লোকেশন লাগবে)\n/help — এই তালিকা" } }, "de" : { "stringUnit" : { "state" : "translated", - "value" : "befehle:\n/msg @name [message] — privaten chat starten\n/who — zeigen, wer hier ist\n/clear — diesen chat leeren\n/hug @name — eine umarmung senden\n/slap @name — mit einer großen forelle ohrfeigen\n/block @name · /unblock @name\n/fav @name · /unfav @name — favoriten (nur mesh)\n/group create — eine verschlüsselte gruppe starten\n/group invite @name · /group remove @name — mitglieder verwalten (ersteller)\n/group leave · /group list — gruppen verlassen oder auflisten\n/ping @name — round-trip-zeit messen (nur mesh)\n/trace @name — geschätzter mesh-pfad (nur mesh)\n/pay — einen cashu-ecash-token in diesem chat senden\n/drop — eine notiz für 24h an diesem ort anpinnen (braucht standort)\n/help — diese liste" + "value" : "befehle:\n/msg @name [message] — privaten chat starten\n/who — zeigen, wer hier ist\n/clear — diesen chat leeren\n/hug @name — eine umarmung senden\n/slap @name — mit einer großen forelle ohrfeigen\n/block @name · /unblock @name\n/group create — eine verschlüsselte gruppe starten\n/group invite @name · /group remove @name — mitglieder verwalten (ersteller)\n/group leave · /group list — gruppen verlassen oder auflisten\n/ping @name — round-trip-zeit messen (nur mesh)\n/trace @name — geschätzter mesh-pfad (nur mesh)\n/pay — einen cashu-ecash-token in diesem chat senden\n/drop — eine notiz für 24h an diesem ort anpinnen (braucht standort)\n/help — diese liste" } }, "en" : { "stringUnit" : { "state" : "translated", - "value" : "commands:\n/msg @name [message] — start a private chat\n/who — list who's here\n/clear — clear this chat\n/hug @name — send a hug\n/slap @name — slap with a large trout\n/block @name · /unblock @name\n/fav @name · /unfav @name — favorites (mesh only)\n/group create — start an encrypted group\n/group invite @name · /group remove @name — manage members (creator)\n/group leave · /group list — leave or list your groups\n/ping @name — measure round-trip time (mesh only)\n/trace @name — estimated mesh path (mesh only)\n/pay — send a cashu ecash token in this chat\n/drop — pin a note to this place for 24h (needs location)\n/help — this list" + "value" : "commands:\n/msg @name [message] — start a private chat\n/who — list who's here\n/clear — clear this chat\n/hug @name — send a hug\n/slap @name — slap with a large trout\n/block @name · /unblock @name\n/group create — start an encrypted group\n/group invite @name · /group remove @name — manage members (creator)\n/group leave · /group list — leave or list your groups\n/ping @name — measure round-trip time (mesh only)\n/trace @name — estimated mesh path (mesh only)\n/pay — send a cashu ecash token in this chat\n/drop — pin a note to this place for 24h (needs location)\n/help — this list" } }, "es" : { "stringUnit" : { "state" : "translated", - "value" : "comandos:\n/msg @name [message] — iniciar un chat privado\n/who — listar quién está aquí\n/clear — limpiar este chat\n/hug @name — enviar un abrazo\n/slap @name — dar un golpe con una trucha enorme\n/block @name · /unblock @name\n/fav @name · /unfav @name — favoritos (solo mesh)\n/group create — iniciar un grupo cifrado\n/group invite @name · /group remove @name — gestionar miembros (creador)\n/group leave · /group list — salir o listar tus grupos\n/ping @name — medir el tiempo de ida y vuelta (solo mesh)\n/trace @name — ruta estimada por la mesh (solo mesh)\n/pay — enviar un token ecash de cashu en este chat\n/drop — fijar una nota en este lugar por 24h (necesita ubicación)\n/help — esta lista" + "value" : "comandos:\n/msg @name [message] — iniciar un chat privado\n/who — listar quién está aquí\n/clear — limpiar este chat\n/hug @name — enviar un abrazo\n/slap @name — dar un golpe con una trucha enorme\n/block @name · /unblock @name\n/group create — iniciar un grupo cifrado\n/group invite @name · /group remove @name — gestionar miembros (creador)\n/group leave · /group list — salir o listar tus grupos\n/ping @name — medir el tiempo de ida y vuelta (solo mesh)\n/trace @name — ruta estimada por la mesh (solo mesh)\n/pay — enviar un token ecash de cashu en este chat\n/drop — fijar una nota en este lugar por 24h (necesita ubicación)\n/help — esta lista" } }, "fa" : { "stringUnit" : { "state" : "translated", - "value" : "دستورها:\n/msg @name [message] — شروع چت خصوصی\n/who — فهرست کسانی که اینجا هستند\n/clear — پاک کردن این چت\n/hug @name — فرستادن یک بغل\n/slap @name — سیلی با یک قزل‌آلای گنده\n/block @name · /unblock @name\n/fav @name · /unfav @name — موردعلاقه‌ها (فقط mesh)\n/group create — شروع یک گروه رمزگذاری‌شده\n/group invite @name · /group remove @name — مدیریت اعضا (سازنده)\n/group leave · /group list — ترک گروه‌هایت یا فهرست‌شان\n/ping @name — اندازه‌گیری زمان رفت‌وبرگشت (فقط mesh)\n/trace @name — مسیر تخمینی mesh (فقط mesh)\n/pay — ارسال توکن ecash از cashu در این چت\n/drop — سنجاق کردن یادداشت به این مکان برای ۲۴ ساعت (به موقعیت نیاز دارد)\n/help — همین فهرست" + "value" : "دستورها:\n/msg @name [message] — شروع چت خصوصی\n/who — فهرست کسانی که اینجا هستند\n/clear — پاک کردن این چت\n/hug @name — فرستادن یک بغل\n/slap @name — سیلی با یک قزل‌آلای گنده\n/block @name · /unblock @name\n/group create — شروع یک گروه رمزگذاری‌شده\n/group invite @name · /group remove @name — مدیریت اعضا (سازنده)\n/group leave · /group list — ترک گروه‌هایت یا فهرست‌شان\n/ping @name — اندازه‌گیری زمان رفت‌وبرگشت (فقط mesh)\n/trace @name — مسیر تخمینی mesh (فقط mesh)\n/pay — ارسال توکن ecash از cashu در این چت\n/drop — سنجاق کردن یادداشت به این مکان برای ۲۴ ساعت (به موقعیت نیاز دارد)\n/help — همین فهرست" } }, "fil" : { "stringUnit" : { "state" : "translated", - "value" : "mga command:\n/msg @name [message] — magsimula ng pribadong chat\n/who — ilista kung sino ang narito\n/clear — i-clear ang chat na ito\n/hug @name — magpadala ng yakap\n/slap @name — sampalin gamit ang malaking trout\n/block @name · /unblock @name\n/fav @name · /unfav @name — mga favorite (mesh lang)\n/group create — magsimula ng encrypted na group\n/group invite @name · /group remove @name — pamahalaan ang mga miyembro (creator)\n/group leave · /group list — umalis o ilista ang mga group mo\n/ping @name — sukatin ang round-trip time (mesh lang)\n/trace @name — tinatayang mesh path (mesh lang)\n/pay — magpadala ng cashu ecash token sa chat na ito\n/drop — mag-pin ng note sa lugar na ito nang 24h (kailangan ng location)\n/help — ang listahang ito" + "value" : "mga command:\n/msg @name [message] — magsimula ng pribadong chat\n/who — ilista kung sino ang narito\n/clear — i-clear ang chat na ito\n/hug @name — magpadala ng yakap\n/slap @name — sampalin gamit ang malaking trout\n/block @name · /unblock @name\n/group create — magsimula ng encrypted na group\n/group invite @name · /group remove @name — pamahalaan ang mga miyembro (creator)\n/group leave · /group list — umalis o ilista ang mga group mo\n/ping @name — sukatin ang round-trip time (mesh lang)\n/trace @name — tinatayang mesh path (mesh lang)\n/pay — magpadala ng cashu ecash token sa chat na ito\n/drop — mag-pin ng note sa lugar na ito nang 24h (kailangan ng location)\n/help — ang listahang ito" } }, "fr" : { "stringUnit" : { "state" : "translated", - "value" : "commandes :\n/msg @name [message] — démarrer un chat privé\n/who — lister qui est là\n/clear — effacer ce chat\n/hug @name — envoyer un câlin\n/slap @name — mettre une claque avec une grosse truite\n/block @name · /unblock @name\n/fav @name · /unfav @name — favoris (mesh uniquement)\n/group create — démarrer un groupe chiffré\n/group invite @name · /group remove @name — gérer les membres (créateur)\n/group leave · /group list — quitter ou lister tes groupes\n/ping @name — mesurer le temps aller-retour (mesh uniquement)\n/trace @name — chemin mesh estimé (mesh uniquement)\n/pay — envoyer un token ecash cashu dans ce chat\n/drop — épingler une note à cet endroit pour 24h (nécessite la localisation)\n/help — cette liste" + "value" : "commandes :\n/msg @name [message] — démarrer un chat privé\n/who — lister qui est là\n/clear — effacer ce chat\n/hug @name — envoyer un câlin\n/slap @name — mettre une claque avec une grosse truite\n/block @name · /unblock @name\n/group create — démarrer un groupe chiffré\n/group invite @name · /group remove @name — gérer les membres (créateur)\n/group leave · /group list — quitter ou lister tes groupes\n/ping @name — mesurer le temps aller-retour (mesh uniquement)\n/trace @name — chemin mesh estimé (mesh uniquement)\n/pay — envoyer un token ecash cashu dans ce chat\n/drop — épingler une note à cet endroit pour 24h (nécessite la localisation)\n/help — cette liste" } }, "he" : { "stringUnit" : { "state" : "translated", - "value" : "פקודות:\n/msg @name [message] — פתיחת צ'אט פרטי\n/who — מי נמצא כאן\n/clear — ניקוי הצ'אט הזה\n/hug @name — שליחת חיבוק\n/slap @name — סטירה עם פורל ענק\n/block @name · /unblock @name\n/fav @name · /unfav @name — מועדפים (mesh בלבד)\n/group create — פתיחת קבוצה מוצפנת\n/group invite @name · /group remove @name — ניהול חברים (יוצר הקבוצה)\n/group leave · /group list — עזיבה או הצגת הקבוצות שלכם\n/ping @name — מדידת זמן הלוך-חזור (mesh בלבד)\n/trace @name — נתיב mesh משוער (mesh בלבד)\n/pay — שליחת טוקן ecash של cashu בצ'אט הזה\n/drop — הצמדת הערה למקום הזה ל-24 שעות (דורש מיקום)\n/help — הרשימה הזאת" + "value" : "פקודות:\n/msg @name [message] — פתיחת צ'אט פרטי\n/who — מי נמצא כאן\n/clear — ניקוי הצ'אט הזה\n/hug @name — שליחת חיבוק\n/slap @name — סטירה עם פורל ענק\n/block @name · /unblock @name\n/group create — פתיחת קבוצה מוצפנת\n/group invite @name · /group remove @name — ניהול חברים (יוצר הקבוצה)\n/group leave · /group list — עזיבה או הצגת הקבוצות שלכם\n/ping @name — מדידת זמן הלוך-חזור (mesh בלבד)\n/trace @name — נתיב mesh משוער (mesh בלבד)\n/pay — שליחת טוקן ecash של cashu בצ'אט הזה\n/drop — הצמדת הערה למקום הזה ל-24 שעות (דורש מיקום)\n/help — הרשימה הזאת" } }, "hi" : { "stringUnit" : { "state" : "translated", - "value" : "कमांड:\n/msg @name [message] — निजी चैट शुरू करो\n/who — देखो यहाँ कौन-कौन है\n/clear — यह चैट साफ़ करो\n/hug @name — झप्पी भेजो\n/slap @name — एक बड़ी ट्राउट मछली से थप्पड़ मारो\n/block @name · /unblock @name\n/fav @name · /unfav @name — पसंदीदा (सिर्फ mesh)\n/group create — एक एन्क्रिप्टेड ग्रुप शुरू करो\n/group invite @name · /group remove @name — सदस्य प्रबंधन (निर्माता)\n/group leave · /group list — ग्रुप छोड़ो या अपने ग्रुप की सूची देखो\n/ping @name — राउंड-ट्रिप समय मापो (सिर्फ mesh)\n/trace @name — अनुमानित mesh रास्ता (सिर्फ mesh)\n/pay — इस चैट में cashu ecash टोकन भेजो\n/drop — इस जगह 24 घंटे के लिए नोट पिन करो (लोकेशन चाहिए)\n/help — यही सूची" + "value" : "कमांड:\n/msg @name [message] — निजी चैट शुरू करो\n/who — देखो यहाँ कौन-कौन है\n/clear — यह चैट साफ़ करो\n/hug @name — झप्पी भेजो\n/slap @name — एक बड़ी ट्राउट मछली से थप्पड़ मारो\n/block @name · /unblock @name\n/group create — एक एन्क्रिप्टेड ग्रुप शुरू करो\n/group invite @name · /group remove @name — सदस्य प्रबंधन (निर्माता)\n/group leave · /group list — ग्रुप छोड़ो या अपने ग्रुप की सूची देखो\n/ping @name — राउंड-ट्रिप समय मापो (सिर्फ mesh)\n/trace @name — अनुमानित mesh रास्ता (सिर्फ mesh)\n/pay — इस चैट में cashu ecash टोकन भेजो\n/drop — इस जगह 24 घंटे के लिए नोट पिन करो (लोकेशन चाहिए)\n/help — यही सूची" } }, "id" : { "stringUnit" : { "state" : "translated", - "value" : "perintah:\n/msg @name [message] — mulai chat pribadi\n/who — daftar siapa saja yang ada di sini\n/clear — bersihkan chat ini\n/hug @name — kirim pelukan\n/slap @name — tampar dengan ikan trout besar\n/block @name · /unblock @name\n/fav @name · /unfav @name — favorit (khusus mesh)\n/group create — mulai grup terenkripsi\n/group invite @name · /group remove @name — kelola anggota (pembuat)\n/group leave · /group list — keluar dari grup atau lihat daftar grupmu\n/ping @name — ukur waktu bolak-balik (khusus mesh)\n/trace @name — perkiraan jalur mesh (khusus mesh)\n/pay — kirim token ecash cashu di chat ini\n/drop — sematkan catatan di tempat ini selama 24 jam (butuh lokasi)\n/help — daftar ini" + "value" : "perintah:\n/msg @name [message] — mulai chat pribadi\n/who — daftar siapa saja yang ada di sini\n/clear — bersihkan chat ini\n/hug @name — kirim pelukan\n/slap @name — tampar dengan ikan trout besar\n/block @name · /unblock @name\n/group create — mulai grup terenkripsi\n/group invite @name · /group remove @name — kelola anggota (pembuat)\n/group leave · /group list — keluar dari grup atau lihat daftar grupmu\n/ping @name — ukur waktu bolak-balik (khusus mesh)\n/trace @name — perkiraan jalur mesh (khusus mesh)\n/pay — kirim token ecash cashu di chat ini\n/drop — sematkan catatan di tempat ini selama 24 jam (butuh lokasi)\n/help — daftar ini" } }, "it" : { "stringUnit" : { "state" : "translated", - "value" : "comandi:\n/msg @name [messaggio] — avvia una chat privata\n/who — elenca chi c'è\n/clear — pulisci questa chat\n/hug @name — manda un abbraccio\n/slap @name — schiaffeggia con una grossa trota\n/block @name · /unblock @name\n/fav @name · /unfav @name — preferiti (solo mesh)\n/group create — avvia un gruppo cifrato\n/group invite @name · /group remove @name — gestisci i membri (creatore)\n/group leave · /group list — esci dai tuoi gruppi o elencali\n/ping @name — misura il tempo di andata e ritorno (solo mesh)\n/trace @name — percorso mesh stimato (solo mesh)\n/pay — invia un token ecash cashu in questa chat\n/drop — appunta una nota in questo posto per 24h (serve la posizione)\n/help — questa lista" + "value" : "comandi:\n/msg @name [messaggio] — avvia una chat privata\n/who — elenca chi c'è\n/clear — pulisci questa chat\n/hug @name — manda un abbraccio\n/slap @name — schiaffeggia con una grossa trota\n/block @name · /unblock @name\n/group create — avvia un gruppo cifrato\n/group invite @name · /group remove @name — gestisci i membri (creatore)\n/group leave · /group list — esci dai tuoi gruppi o elencali\n/ping @name — misura il tempo di andata e ritorno (solo mesh)\n/trace @name — percorso mesh stimato (solo mesh)\n/pay — invia un token ecash cashu in questa chat\n/drop — appunta una nota in questo posto per 24h (serve la posizione)\n/help — questa lista" } }, "ja" : { "stringUnit" : { "state" : "translated", - "value" : "コマンド:\n/msg @name [メッセージ] — プライベートチャットを開始\n/who — 誰がいるか一覧表示\n/clear — このチャットをクリア\n/hug @name — ハグを送る\n/slap @name — 大きなマスでひっぱたく\n/block @name · /unblock @name\n/fav @name · /unfav @name — お気に入り (メッシュのみ)\n/group create <名前> — 暗号化グループを開始\n/group invite @name · /group remove @name — メンバー管理 (作成者)\n/group leave · /group list — グループから抜ける・一覧表示\n/ping @name — 往復時間を測定 (メッシュのみ)\n/trace @name — 推定メッシュ経路 (メッシュのみ)\n/pay <トークン> — このチャットで cashu ecash トークンを送る\n/drop <メッセージ> — この場所に24時間ノートをピン留め (位置情報が必要)\n/help — この一覧" + "value" : "コマンド:\n/msg @name [メッセージ] — プライベートチャットを開始\n/who — 誰がいるか一覧表示\n/clear — このチャットをクリア\n/hug @name — ハグを送る\n/slap @name — 大きなマスでひっぱたく\n/block @name · /unblock @name\n/group create <名前> — 暗号化グループを開始\n/group invite @name · /group remove @name — メンバー管理 (作成者)\n/group leave · /group list — グループから抜ける・一覧表示\n/ping @name — 往復時間を測定 (メッシュのみ)\n/trace @name — 推定メッシュ経路 (メッシュのみ)\n/pay <トークン> — このチャットで cashu ecash トークンを送る\n/drop <メッセージ> — この場所に24時間ノートをピン留め (位置情報が必要)\n/help — この一覧" } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "명령어:\n/msg @name [메시지] — 개인 채팅 시작\n/who — 여기 누가 있는지 보기\n/clear — 이 채팅 지우기\n/hug @name — 포옹 보내기\n/slap @name — 큰 송어로 찰싹 때리기\n/block @name · /unblock @name\n/fav @name · /unfav @name — 즐겨찾기 (메시 전용)\n/group create <이름> — 암호화 그룹 만들기\n/group invite @name · /group remove @name — 멤버 관리 (만든 사람)\n/group leave · /group list — 그룹 나가기 또는 목록 보기\n/ping @name — 왕복 시간 측정 (메시 전용)\n/trace @name — 예상 메시 경로 (메시 전용)\n/pay <토큰> — 이 채팅에서 cashu ecash 토큰 보내기\n/drop <메시지> — 이 장소에 24시간 노트 고정 (위치 정보 필요)\n/help — 이 목록" + "value" : "명령어:\n/msg @name [메시지] — 개인 채팅 시작\n/who — 여기 누가 있는지 보기\n/clear — 이 채팅 지우기\n/hug @name — 포옹 보내기\n/slap @name — 큰 송어로 찰싹 때리기\n/block @name · /unblock @name\n/group create <이름> — 암호화 그룹 만들기\n/group invite @name · /group remove @name — 멤버 관리 (만든 사람)\n/group leave · /group list — 그룹 나가기 또는 목록 보기\n/ping @name — 왕복 시간 측정 (메시 전용)\n/trace @name — 예상 메시 경로 (메시 전용)\n/pay <토큰> — 이 채팅에서 cashu ecash 토큰 보내기\n/drop <메시지> — 이 장소에 24시간 노트 고정 (위치 정보 필요)\n/help — 이 목록" } }, "ms" : { "stringUnit" : { "state" : "translated", - "value" : "arahan:\n/msg @name [mesej] — mulakan sembang peribadi\n/who — senaraikan siapa yang ada di sini\n/clear — kosongkan sembang ini\n/hug @name — hantar pelukan\n/slap @name — tampar dengan ikan trout besar\n/block @name · /unblock @name\n/fav @name · /unfav @name — kegemaran (mesh sahaja)\n/group create — mulakan kumpulan tersulit\n/group invite @name · /group remove @name — urus ahli (pencipta)\n/group leave · /group list — keluar atau senaraikan kumpulan anda\n/ping @name — ukur masa pergi balik (mesh sahaja)\n/trace @name — laluan mesh anggaran (mesh sahaja)\n/pay — hantar token ecash cashu dalam sembang ini\n/drop — sematkan nota di tempat ini selama 24 jam (perlukan lokasi)\n/help — senarai ini" + "value" : "arahan:\n/msg @name [mesej] — mulakan sembang peribadi\n/who — senaraikan siapa yang ada di sini\n/clear — kosongkan sembang ini\n/hug @name — hantar pelukan\n/slap @name — tampar dengan ikan trout besar\n/block @name · /unblock @name\n/group create — mulakan kumpulan tersulit\n/group invite @name · /group remove @name — urus ahli (pencipta)\n/group leave · /group list — keluar atau senaraikan kumpulan anda\n/ping @name — ukur masa pergi balik (mesh sahaja)\n/trace @name — laluan mesh anggaran (mesh sahaja)\n/pay — hantar token ecash cashu dalam sembang ini\n/drop — sematkan nota di tempat ini selama 24 jam (perlukan lokasi)\n/help — senarai ini" } }, "ne" : { "stringUnit" : { "state" : "translated", - "value" : "कमाण्डहरू:\n/msg @name [सन्देश] — निजी च्याट सुरु गर्नुहोस्\n/who — यहाँ को छ भनेर हेर्नुहोस्\n/clear — यो च्याट खाली गर्नुहोस्\n/hug @name — अँगालो पठाउनुहोस्\n/slap @name — ठूलो ट्राउट माछाले हिर्काउनुहोस्\n/block @name · /unblock @name\n/fav @name · /unfav @name — मनपर्नेहरू (मेस मात्र)\n/group create <नाम> — इन्क्रिप्टेड समूह सुरु गर्नुहोस्\n/group invite @name · /group remove @name — सदस्य व्यवस्थापन (सर्जक)\n/group leave · /group list — समूह छोड्नुहोस् वा सूची हेर्नुहोस्\n/ping @name — राउन्ड-ट्रिप समय नाप्नुहोस् (मेस मात्र)\n/trace @name — अनुमानित मेस बाटो (मेस मात्र)\n/pay <टोकन> — यो च्याटमा cashu ecash टोकन पठाउनुहोस्\n/drop <सन्देश> — यो ठाउँमा 24 घण्टाका लागि नोट राख्नुहोस् (स्थान चाहिन्छ)\n/help — यो सूची" + "value" : "कमाण्डहरू:\n/msg @name [सन्देश] — निजी च्याट सुरु गर्नुहोस्\n/who — यहाँ को छ भनेर हेर्नुहोस्\n/clear — यो च्याट खाली गर्नुहोस्\n/hug @name — अँगालो पठाउनुहोस्\n/slap @name — ठूलो ट्राउट माछाले हिर्काउनुहोस्\n/block @name · /unblock @name\n/group create <नाम> — इन्क्रिप्टेड समूह सुरु गर्नुहोस्\n/group invite @name · /group remove @name — सदस्य व्यवस्थापन (सर्जक)\n/group leave · /group list — समूह छोड्नुहोस् वा सूची हेर्नुहोस्\n/ping @name — राउन्ड-ट्रिप समय नाप्नुहोस् (मेस मात्र)\n/trace @name — अनुमानित मेस बाटो (मेस मात्र)\n/pay <टोकन> — यो च्याटमा cashu ecash टोकन पठाउनुहोस्\n/drop <सन्देश> — यो ठाउँमा 24 घण्टाका लागि नोट राख्नुहोस् (स्थान चाहिन्छ)\n/help — यो सूची" } }, "nl" : { "stringUnit" : { "state" : "translated", - "value" : "commando's:\n/msg @name [bericht] — start een privéchat\n/who — toon wie er is\n/clear — wis deze chat\n/hug @name — stuur een knuffel\n/slap @name — sla met een grote forel\n/block @name · /unblock @name\n/fav @name · /unfav @name — favorieten (alleen mesh)\n/group create — start een versleutelde groep\n/group invite @name · /group remove @name — beheer leden (maker)\n/group leave · /group list — verlaat of toon je groepen\n/ping @name — meet de rondreistijd (alleen mesh)\n/trace @name — geschat mesh-pad (alleen mesh)\n/pay — stuur een cashu-ecash-token in deze chat\n/drop — pin 24 uur lang een notitie op deze plek (vereist locatie)\n/help — deze lijst" + "value" : "commando's:\n/msg @name [bericht] — start een privéchat\n/who — toon wie er is\n/clear — wis deze chat\n/hug @name — stuur een knuffel\n/slap @name — sla met een grote forel\n/block @name · /unblock @name\n/group create — start een versleutelde groep\n/group invite @name · /group remove @name — beheer leden (maker)\n/group leave · /group list — verlaat of toon je groepen\n/ping @name — meet de rondreistijd (alleen mesh)\n/trace @name — geschat mesh-pad (alleen mesh)\n/pay — stuur een cashu-ecash-token in deze chat\n/drop — pin 24 uur lang een notitie op deze plek (vereist locatie)\n/help — deze lijst" } }, "pl" : { "stringUnit" : { "state" : "translated", - "value" : "polecenia:\n/msg @name [wiadomość] — rozpocznij prywatny czat\n/who — pokaż, kto tu jest\n/clear — wyczyść ten czat\n/hug @name — wyślij przytulasa\n/slap @name — trzaśnij wielkim pstrągiem\n/block @name · /unblock @name\n/fav @name · /unfav @name — ulubione (tylko mesh)\n/group create — załóż szyfrowaną grupę\n/group invite @name · /group remove @name — zarządzaj członkami (założyciel)\n/group leave · /group list — opuść grupę lub pokaż swoje grupy\n/ping @name — zmierz czas podróży w obie strony (tylko mesh)\n/trace @name — szacowana ścieżka mesh (tylko mesh)\n/pay — wyślij token ecash cashu na tym czacie\n/drop — przypnij notkę w tym miejscu na 24 h (wymaga lokalizacji)\n/help — ta lista" + "value" : "polecenia:\n/msg @name [wiadomość] — rozpocznij prywatny czat\n/who — pokaż, kto tu jest\n/clear — wyczyść ten czat\n/hug @name — wyślij przytulasa\n/slap @name — trzaśnij wielkim pstrągiem\n/block @name · /unblock @name\n/group create — załóż szyfrowaną grupę\n/group invite @name · /group remove @name — zarządzaj członkami (założyciel)\n/group leave · /group list — opuść grupę lub pokaż swoje grupy\n/ping @name — zmierz czas podróży w obie strony (tylko mesh)\n/trace @name — szacowana ścieżka mesh (tylko mesh)\n/pay — wyślij token ecash cashu na tym czacie\n/drop — przypnij notkę w tym miejscu na 24 h (wymaga lokalizacji)\n/help — ta lista" } }, "pt" : { "stringUnit" : { "state" : "translated", - "value" : "comandos:\n/msg @name [mensagem] — inicia uma conversa privada\n/who — lista quem está aqui\n/clear — limpa esta conversa\n/hug @name — envia um abraço\n/slap @name — dá uma chapada com uma truta enorme\n/block @name · /unblock @name\n/fav @name · /unfav @name — favoritos (só mesh)\n/group create — cria um grupo encriptado\n/group invite @name · /group remove @name — gere os membros (criador)\n/group leave · /group list — sai dos teus grupos ou lista-os\n/ping @name — mede o tempo de ida e volta (só mesh)\n/trace @name — caminho mesh estimado (só mesh)\n/pay — envia um token ecash cashu nesta conversa\n/drop — fixa uma nota neste sítio por 24h (precisa de localização)\n/help — esta lista" + "value" : "comandos:\n/msg @name [mensagem] — inicia uma conversa privada\n/who — lista quem está aqui\n/clear — limpa esta conversa\n/hug @name — envia um abraço\n/slap @name — dá uma chapada com uma truta enorme\n/block @name · /unblock @name\n/group create — cria um grupo encriptado\n/group invite @name · /group remove @name — gere os membros (criador)\n/group leave · /group list — sai dos teus grupos ou lista-os\n/ping @name — mede o tempo de ida e volta (só mesh)\n/trace @name — caminho mesh estimado (só mesh)\n/pay — envia um token ecash cashu nesta conversa\n/drop — fixa uma nota neste sítio por 24h (precisa de localização)\n/help — esta lista" } }, "pt-BR" : { "stringUnit" : { "state" : "translated", - "value" : "comandos:\n/msg @name [mensagem] — comece um chat privado\n/who — veja quem está aqui\n/clear — limpe este chat\n/hug @name — mande um abraço\n/slap @name — dê um tapa com uma truta gigante\n/block @name · /unblock @name\n/fav @name · /unfav @name — favoritos (só mesh)\n/group create — crie um grupo criptografado\n/group invite @name · /group remove @name — gerencie os membros (criador)\n/group leave · /group list — saia dos seus grupos ou liste-os\n/ping @name — meça o tempo de ida e volta (só mesh)\n/trace @name — caminho mesh estimado (só mesh)\n/pay — envie um token ecash cashu neste chat\n/drop — fixe uma nota neste lugar por 24h (precisa de localização)\n/help — esta lista" + "value" : "comandos:\n/msg @name [mensagem] — comece um chat privado\n/who — veja quem está aqui\n/clear — limpe este chat\n/hug @name — mande um abraço\n/slap @name — dê um tapa com uma truta gigante\n/block @name · /unblock @name\n/group create — crie um grupo criptografado\n/group invite @name · /group remove @name — gerencie os membros (criador)\n/group leave · /group list — saia dos seus grupos ou liste-os\n/ping @name — meça o tempo de ida e volta (só mesh)\n/trace @name — caminho mesh estimado (só mesh)\n/pay — envie um token ecash cashu neste chat\n/drop — fixe uma nota neste lugar por 24h (precisa de localização)\n/help — esta lista" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "команды:\n/msg @name [сообщение] — начать личный чат\n/who — показать, кто здесь\n/clear — очистить этот чат\n/hug @name — отправить обнимашку\n/slap @name — шлёпнуть большой форелью\n/block @name · /unblock @name\n/fav @name · /unfav @name — избранное (только mesh)\n/group create <название> — создать зашифрованную группу\n/group invite @name · /group remove @name — управление участниками (создатель)\n/group leave · /group list — выйти из групп или показать их список\n/ping @name — измерить время туда-обратно (только mesh)\n/trace @name — примерный путь по mesh (только mesh)\n/pay <токен> — отправить cashu-токен (ecash) в этот чат\n/drop <сообщение> — закрепить заметку в этом месте на 24 ч (нужна геолокация)\n/help — этот список" + "value" : "команды:\n/msg @name [сообщение] — начать личный чат\n/who — показать, кто здесь\n/clear — очистить этот чат\n/hug @name — отправить обнимашку\n/slap @name — шлёпнуть большой форелью\n/block @name · /unblock @name\n/group create <название> — создать зашифрованную группу\n/group invite @name · /group remove @name — управление участниками (создатель)\n/group leave · /group list — выйти из групп или показать их список\n/ping @name — измерить время туда-обратно (только mesh)\n/trace @name — примерный путь по mesh (только mesh)\n/pay <токен> — отправить cashu-токен (ecash) в этот чат\n/drop <сообщение> — закрепить заметку в этом месте на 24 ч (нужна геолокация)\n/help — этот список" } }, "sv" : { "stringUnit" : { "state" : "translated", - "value" : "kommandon:\n/msg @name [message] — starta en privat chatt\n/who — lista vilka som är här\n/clear — rensa den här chatten\n/hug @name — skicka en kram\n/slap @name — daska till med en stor forell\n/block @name · /unblock @name\n/fav @name · /unfav @name — favoriter (endast mesh)\n/group create — starta en krypterad grupp\n/group invite @name · /group remove @name — hantera medlemmar (skapare)\n/group leave · /group list — lämna eller lista dina grupper\n/ping @name — mät tur- och returtid (endast mesh)\n/trace @name — uppskattad mesh-väg (endast mesh)\n/pay — skicka en cashu ecash-token i den här chatten\n/drop — fäst en anteckning på den här platsen i 24h (kräver plats)\n/help — den här listan" + "value" : "kommandon:\n/msg @name [message] — starta en privat chatt\n/who — lista vilka som är här\n/clear — rensa den här chatten\n/hug @name — skicka en kram\n/slap @name — daska till med en stor forell\n/block @name · /unblock @name\n/group create — starta en krypterad grupp\n/group invite @name · /group remove @name — hantera medlemmar (skapare)\n/group leave · /group list — lämna eller lista dina grupper\n/ping @name — mät tur- och returtid (endast mesh)\n/trace @name — uppskattad mesh-väg (endast mesh)\n/pay — skicka en cashu ecash-token i den här chatten\n/drop — fäst en anteckning på den här platsen i 24h (kräver plats)\n/help — den här listan" } }, "ta" : { "stringUnit" : { "state" : "translated", - "value" : "கட்டளைகள்:\n/msg @name [message] — தனி அரட்டையைத் தொடங்கு\n/who — இங்கு யார் இருக்கிறார்கள் என்று பட்டியலிடு\n/clear — இந்த அரட்டையை அழி\n/hug @name — ஒரு அணைப்பை அனுப்பு\n/slap @name — ஒரு பெரிய ட்ரவுட் மீனால் அறை\n/block @name · /unblock @name\n/fav @name · /unfav @name — பிடித்தவை (mesh மட்டும்)\n/group create — மறைகுறியாக்கப்பட்ட குழுவைத் தொடங்கு\n/group invite @name · /group remove @name — உறுப்பினர்களை நிர்வகி (உருவாக்கியவர்)\n/group leave · /group list — உங்கள் குழுக்களிலிருந்து வெளியேறு அல்லது பட்டியலிடு\n/ping @name — சுற்றுப்பயண நேரத்தை அளவிடு (mesh மட்டும்)\n/trace @name — மதிப்பிடப்பட்ட mesh பாதை (mesh மட்டும்)\n/pay — இந்த அரட்டையில் cashu ecash டோக்கனை அனுப்பு\n/drop — இந்த இடத்தில் 24 மணி நேரத்திற்கு ஒரு குறிப்பை பொருத்து (இருப்பிடம் தேவை)\n/help — இந்த பட்டியல்" + "value" : "கட்டளைகள்:\n/msg @name [message] — தனி அரட்டையைத் தொடங்கு\n/who — இங்கு யார் இருக்கிறார்கள் என்று பட்டியலிடு\n/clear — இந்த அரட்டையை அழி\n/hug @name — ஒரு அணைப்பை அனுப்பு\n/slap @name — ஒரு பெரிய ட்ரவுட் மீனால் அறை\n/block @name · /unblock @name\n/group create — மறைகுறியாக்கப்பட்ட குழுவைத் தொடங்கு\n/group invite @name · /group remove @name — உறுப்பினர்களை நிர்வகி (உருவாக்கியவர்)\n/group leave · /group list — உங்கள் குழுக்களிலிருந்து வெளியேறு அல்லது பட்டியலிடு\n/ping @name — சுற்றுப்பயண நேரத்தை அளவிடு (mesh மட்டும்)\n/trace @name — மதிப்பிடப்பட்ட mesh பாதை (mesh மட்டும்)\n/pay — இந்த அரட்டையில் cashu ecash டோக்கனை அனுப்பு\n/drop — இந்த இடத்தில் 24 மணி நேரத்திற்கு ஒரு குறிப்பை பொருத்து (இருப்பிடம் தேவை)\n/help — இந்த பட்டியல்" } }, "th" : { "stringUnit" : { "state" : "translated", - "value" : "คำสั่ง:\n/msg @name [message] — เริ่มแชทส่วนตัว\n/who — ดูว่าใครอยู่ที่นี่บ้าง\n/clear — ล้างแชทนี้\n/hug @name — ส่งอ้อมกอด\n/slap @name — ตบด้วยปลาเทราต์ตัวใหญ่\n/block @name · /unblock @name\n/fav @name · /unfav @name — รายการโปรด (เฉพาะ mesh)\n/group create — เริ่มกลุ่มที่เข้ารหัส\n/group invite @name · /group remove @name — จัดการสมาชิก (ผู้สร้าง)\n/group leave · /group list — ออกจากกลุ่มหรือดูรายชื่อกลุ่มของคุณ\n/ping @name — วัดเวลาไปกลับ (เฉพาะ mesh)\n/trace @name — เส้นทาง mesh โดยประมาณ (เฉพาะ mesh)\n/pay — ส่งโทเคน ecash ของ cashu ในแชทนี้\n/drop — ปักโน้ตไว้ที่นี่นาน 24 ชม. (ต้องใช้ตำแหน่งที่ตั้ง)\n/help — รายการนี้" + "value" : "คำสั่ง:\n/msg @name [message] — เริ่มแชทส่วนตัว\n/who — ดูว่าใครอยู่ที่นี่บ้าง\n/clear — ล้างแชทนี้\n/hug @name — ส่งอ้อมกอด\n/slap @name — ตบด้วยปลาเทราต์ตัวใหญ่\n/block @name · /unblock @name\n/group create — เริ่มกลุ่มที่เข้ารหัส\n/group invite @name · /group remove @name — จัดการสมาชิก (ผู้สร้าง)\n/group leave · /group list — ออกจากกลุ่มหรือดูรายชื่อกลุ่มของคุณ\n/ping @name — วัดเวลาไปกลับ (เฉพาะ mesh)\n/trace @name — เส้นทาง mesh โดยประมาณ (เฉพาะ mesh)\n/pay — ส่งโทเคน ecash ของ cashu ในแชทนี้\n/drop — ปักโน้ตไว้ที่นี่นาน 24 ชม. (ต้องใช้ตำแหน่งที่ตั้ง)\n/help — รายการนี้" } }, "tr" : { "stringUnit" : { "state" : "translated", - "value" : "komutlar:\n/msg @name [message] — özel sohbet başlat\n/who — burada kimler var, listele\n/clear — bu sohbeti temizle\n/hug @name — sarılma gönder\n/slap @name — koca bir alabalıkla tokat at\n/block @name · /unblock @name\n/fav @name · /unfav @name — favoriler (sadece mesh)\n/group create — şifreli bir grup başlat\n/group invite @name · /group remove @name — üyeleri yönet (kurucu)\n/group leave · /group list — gruplarından ayrıl veya listele\n/ping @name — gidiş-dönüş süresini ölç (sadece mesh)\n/trace @name — tahmini mesh yolu (sadece mesh)\n/pay — bu sohbette cashu ecash token'ı gönder\n/drop — buraya 24 saatliğine not sabitle (konum gerekli)\n/help — bu liste" + "value" : "komutlar:\n/msg @name [message] — özel sohbet başlat\n/who — burada kimler var, listele\n/clear — bu sohbeti temizle\n/hug @name — sarılma gönder\n/slap @name — koca bir alabalıkla tokat at\n/block @name · /unblock @name\n/group create — şifreli bir grup başlat\n/group invite @name · /group remove @name — üyeleri yönet (kurucu)\n/group leave · /group list — gruplarından ayrıl veya listele\n/ping @name — gidiş-dönüş süresini ölç (sadece mesh)\n/trace @name — tahmini mesh yolu (sadece mesh)\n/pay — bu sohbette cashu ecash token'ı gönder\n/drop — buraya 24 saatliğine not sabitle (konum gerekli)\n/help — bu liste" } }, "uk" : { "stringUnit" : { "state" : "translated", - "value" : "команди:\n/msg @name [message] — почати приватний чат\n/who — показати, хто тут є\n/clear — очистити цей чат\n/hug @name — надіслати обійми\n/slap @name — ляснути великою фореллю\n/block @name · /unblock @name\n/fav @name · /unfav @name — обране (лише mesh)\n/group create — створити зашифровану групу\n/group invite @name · /group remove @name — керувати учасниками (творець)\n/group leave · /group list — вийти з груп або показати список\n/ping @name — виміряти час проходження туди й назад (лише mesh)\n/trace @name — орієнтовний шлях у mesh (лише mesh)\n/pay — надіслати cashu ecash-токен у цей чат\n/drop — закріпити нотатку в цьому місці на 24 год (потрібна геолокація)\n/help — цей список" + "value" : "команди:\n/msg @name [message] — почати приватний чат\n/who — показати, хто тут є\n/clear — очистити цей чат\n/hug @name — надіслати обійми\n/slap @name — ляснути великою фореллю\n/block @name · /unblock @name\n/group create — створити зашифровану групу\n/group invite @name · /group remove @name — керувати учасниками (творець)\n/group leave · /group list — вийти з груп або показати список\n/ping @name — виміряти час проходження туди й назад (лише mesh)\n/trace @name — орієнтовний шлях у mesh (лише mesh)\n/pay — надіслати cashu ecash-токен у цей чат\n/drop — закріпити нотатку в цьому місці на 24 год (потрібна геолокація)\n/help — цей список" } }, "ur" : { "stringUnit" : { "state" : "translated", - "value" : "کمانڈز:\n/msg @name [message] — نجی چیٹ شروع کریں\n/who — دیکھیں یہاں کون کون ہے\n/clear — یہ چیٹ صاف کریں\n/hug @name — جھپی بھیجیں\n/slap @name — ایک بڑی ٹراؤٹ مچھلی سے تھپڑ ماریں\n/block @name · /unblock @name\n/fav @name · /unfav @name — پسندیدہ (صرف mesh)\n/group create — ایک انکرپٹڈ گروپ بنائیں\n/group invite @name · /group remove @name — اراکین کا انتظام کریں (بنانے والا)\n/group leave · /group list — اپنے گروپ چھوڑیں یا فہرست دیکھیں\n/ping @name — راؤنڈ ٹرپ وقت ناپیں (صرف mesh)\n/trace @name — تخمینی mesh راستہ (صرف mesh)\n/pay — اس چیٹ میں cashu ای کیش ٹوکن بھیجیں\n/drop — اس جگہ 24 گھنٹے کے لیے نوٹ لگائیں (مقام درکار)\n/help — یہ فہرست" + "value" : "کمانڈز:\n/msg @name [message] — نجی چیٹ شروع کریں\n/who — دیکھیں یہاں کون کون ہے\n/clear — یہ چیٹ صاف کریں\n/hug @name — جھپی بھیجیں\n/slap @name — ایک بڑی ٹراؤٹ مچھلی سے تھپڑ ماریں\n/block @name · /unblock @name\n/group create — ایک انکرپٹڈ گروپ بنائیں\n/group invite @name · /group remove @name — اراکین کا انتظام کریں (بنانے والا)\n/group leave · /group list — اپنے گروپ چھوڑیں یا فہرست دیکھیں\n/ping @name — راؤنڈ ٹرپ وقت ناپیں (صرف mesh)\n/trace @name — تخمینی mesh راستہ (صرف mesh)\n/pay — اس چیٹ میں cashu ای کیش ٹوکن بھیجیں\n/drop — اس جگہ 24 گھنٹے کے لیے نوٹ لگائیں (مقام درکار)\n/help — یہ فہرست" } }, "vi" : { "stringUnit" : { "state" : "translated", - "value" : "các lệnh:\n/msg @name [message] — bắt đầu trò chuyện riêng\n/who — xem ai đang ở đây\n/clear — xóa cuộc trò chuyện này\n/hug @name — gửi một cái ôm\n/slap @name — tát bằng một con cá hồi vân to\n/block @name · /unblock @name\n/fav @name · /unfav @name — mục yêu thích (chỉ mesh)\n/group create — tạo nhóm mã hóa\n/group invite @name · /group remove @name — quản lý thành viên (người tạo)\n/group leave · /group list — rời hoặc xem danh sách nhóm của bạn\n/ping @name — đo thời gian khứ hồi (chỉ mesh)\n/trace @name — đường đi mesh ước tính (chỉ mesh)\n/pay — gửi token ecash cashu trong cuộc trò chuyện này\n/drop — ghim ghi chú tại nơi này trong 24 giờ (cần vị trí)\n/help — danh sách này" + "value" : "các lệnh:\n/msg @name [message] — bắt đầu trò chuyện riêng\n/who — xem ai đang ở đây\n/clear — xóa cuộc trò chuyện này\n/hug @name — gửi một cái ôm\n/slap @name — tát bằng một con cá hồi vân to\n/block @name · /unblock @name\n/group create — tạo nhóm mã hóa\n/group invite @name · /group remove @name — quản lý thành viên (người tạo)\n/group leave · /group list — rời hoặc xem danh sách nhóm của bạn\n/ping @name — đo thời gian khứ hồi (chỉ mesh)\n/trace @name — đường đi mesh ước tính (chỉ mesh)\n/pay — gửi token ecash cashu trong cuộc trò chuyện này\n/drop — ghim ghi chú tại nơi này trong 24 giờ (cần vị trí)\n/help — danh sách này" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "命令:\n/msg @name [message] — 开始私聊\n/who — 列出谁在这里\n/clear — 清空当前聊天\n/hug @name — 送出一个拥抱\n/slap @name — 用一条大鳟鱼拍过去\n/block @name · /unblock @name\n/fav @name · /unfav @name — 收藏(仅 mesh)\n/group create — 创建加密群组\n/group invite @name · /group remove @name — 管理成员(创建者)\n/group leave · /group list — 退出或列出你的群组\n/ping @name — 测量往返时间(仅 mesh)\n/trace @name — 估计的 mesh 路径(仅 mesh)\n/pay — 在当前聊天发送 cashu ecash 代币\n/drop — 在这个地方钉一条便签,保留 24 小时(需要位置)\n/help — 本列表" + "value" : "命令:\n/msg @name [message] — 开始私聊\n/who — 列出谁在这里\n/clear — 清空当前聊天\n/hug @name — 送出一个拥抱\n/slap @name — 用一条大鳟鱼拍过去\n/block @name · /unblock @name\n/group create — 创建加密群组\n/group invite @name · /group remove @name — 管理成员(创建者)\n/group leave · /group list — 退出或列出你的群组\n/ping @name — 测量往返时间(仅 mesh)\n/trace @name — 估计的 mesh 路径(仅 mesh)\n/pay — 在当前聊天发送 cashu ecash 代币\n/drop — 在这个地方钉一条便签,保留 24 小时(需要位置)\n/help — 本列表" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "指令:\n/msg @name [message] — 開始私人聊天\n/who — 列出誰在這裡\n/clear — 清除這個聊天\n/hug @name — 送出一個擁抱\n/slap @name — 用一條大鱒魚巴下去\n/block @name · /unblock @name\n/fav @name · /unfav @name — 最愛(僅限 mesh)\n/group create — 建立加密群組\n/group invite @name · /group remove @name — 管理成員(建立者)\n/group leave · /group list — 離開或列出你的群組\n/ping @name — 測量來回時間(僅限 mesh)\n/trace @name — 估計的 mesh 路徑(僅限 mesh)\n/pay — 在這個聊天中傳送 cashu ecash 代幣\n/drop — 在這個地方釘一張便箋 24 小時(需要位置)\n/help — 這份清單" + "value" : "指令:\n/msg @name [message] — 開始私人聊天\n/who — 列出誰在這裡\n/clear — 清除這個聊天\n/hug @name — 送出一個擁抱\n/slap @name — 用一條大鱒魚巴下去\n/block @name · /unblock @name\n/group create — 建立加密群組\n/group invite @name · /group remove @name — 管理成員(建立者)\n/group leave · /group list — 離開或列出你的群組\n/ping @name — 測量來回時間(僅限 mesh)\n/trace @name — 估計的 mesh 路徑(僅限 mesh)\n/pay — 在這個聊天中傳送 cashu ecash 代幣\n/drop — 在這個地方釘一張便箋 24 小時(需要位置)\n/help — 這份清單" } } } @@ -147387,181 +147387,181 @@ "ar" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld من أصدقاء الشبكة المفضلين بمفاتيح Nostr" + "value" : "+ %lld جهات اتصال بمفاتيح Nostr" } }, "bn" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld জন Nostr কী সহ পছন্দের মেশ বন্ধু" + "value" : "+ Nostr কী সহ %lld জন কন্টাক্ট" } }, "de" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld favorisierte Mesh-Kontakte mit Nostr-Schlüsseln" + "value" : "+ %lld Kontakte mit Nostr-Schlüsseln" } }, "en" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld favorited mesh peers with Nostr keys" + "value" : "+ %lld contacts with Nostr keys" } }, "es" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld favoritos de malla con claves Nostr" + "value" : "+ %lld contactos con claves Nostr" } }, "fa" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld دوست منتخب مش با کلید Nostr" + "value" : "+ %lld مخاطب با کلید Nostr" } }, "fil" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld paboritong mesh peer na may Nostr key" + "value" : "+ %lld contact na may Nostr key" } }, "fr" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld favoris mesh avec clés Nostr" + "value" : "+ %lld contacts avec clés Nostr" } }, "he" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld מועדפי רשת עם מפתחות Nostr" + "value" : "+ %lld אנשי קשר עם מפתחות Nostr" } }, "hi" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld Nostr कुंजी वाले पसंदीदा मेश साथी" + "value" : "+ Nostr कुंजी वाले %lld संपर्क" } }, "id" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld favorit mesh dengan kunci Nostr" + "value" : "+ %lld kontak dengan kunci Nostr" } }, "it" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld preferiti mesh con chiavi Nostr" + "value" : "+ %lld contatti con chiavi Nostr" } }, "ja" : { "stringUnit" : { "state" : "translated", - "value" : "+ Nostr鍵を持つお気に入りメッシュ %lld 人" + "value" : "+ Nostrキーを持つ連絡先 %lld件" } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "+ Nostr 키가 있는 즐겨찾기 메시 %lld명" + "value" : "+ Nostr 키가 있는 연락처 %lld명" } }, "ms" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld rakan mesh kegemaran dengan kunci Nostr" + "value" : "+ %lld kenalan dengan kunci Nostr" } }, "ne" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld Nostr कुञ्जी भएका मनपर्ने मेश साथी" + "value" : "+ Nostr कुञ्जी भएका %lld सम्पर्क" } }, "nl" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld favoriete mesh-contacten met Nostr-sleutels" + "value" : "+ %lld contacten met Nostr-sleutels" } }, "pl" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld ulubionych z sieci mesh z kluczami Nostr" + "value" : "+ %lld kontaktów z kluczami Nostr" } }, "pt" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld favoritos mesh com chaves Nostr" + "value" : "+ %lld contactos com chaves Nostr" } }, "pt-BR" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld favoritos mesh com chaves Nostr" + "value" : "+ %lld contatos com chaves Nostr" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld избранных из mesh с ключами Nostr" + "value" : "+ %lld контактов с ключами Nostr" } }, "sv" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld favoritmarkerade mesh-kontakter med Nostr-nycklar" + "value" : "+ %lld kontakter med Nostr-nycklar" } }, "ta" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld Nostr விசையுள்ள பிடித்த மெஷ் நண்பர்கள்" + "value" : "+ Nostr விசைகளுடன் %lld தொடர்புகள்" } }, "th" : { "stringUnit" : { "state" : "translated", - "value" : "+ เพื่อนเมชคนโปรดที่มีคีย์ Nostr อีก %lld คน" + "value" : "+ รายชื่อติดต่อที่มีคีย์ Nostr %lld ราย" } }, "tr" : { "stringUnit" : { "state" : "translated", - "value" : "+ Nostr anahtarlı %lld favori mesh kişi" + "value" : "+ Nostr anahtarlı %lld kişi" } }, "uk" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld улюблених з mesh із ключами Nostr" + "value" : "+ %lld контактів із ключами Nostr" } }, "ur" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld Nostr کلید والے پسندیدہ میش دوست" + "value" : "+ Nostr کلیدوں والے %lld رابطے" } }, "vi" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld bạn mesh yêu thích có khóa Nostr" + "value" : "+ %lld liên hệ có khóa Nostr" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld 位已交换 Nostr 密钥的 Mesh 好友" + "value" : "+ %lld 位带有 Nostr 密钥的联系人" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "+ %lld 位已交換 Nostr 金鑰的 Mesh 好友" + "value" : "+ %lld 位擁有 Nostr 金鑰的聯絡人" } } } @@ -147942,181 +147942,181 @@ "ar" : { "stringUnit" : { "state" : "translated", - "value" : "تُحفظ فقط في سلسلة مفاتيح جهازك ولا تُنشر أبدًا كقائمة متابعة عامة. تُدرج المفضلات المتبادلة ذات مفاتيح Nostr تلقائيًا." + "value" : "تُخزَّن فقط في سلسلة مفاتيح جهازك ولا تُنشر أبدًا كقائمة متابعة عامة. تُضمَّن جهات الاتصال التي لديها مفاتيح Nostr تلقائيًا." } }, "bn" : { "stringUnit" : { "state" : "translated", - "value" : "শুধুমাত্র আপনার ডিভাইসের কীচেইনে সংরক্ষিত, কখনোই প্রকাশ্যে প্রকাশিত হয় না। Nostr কী সহ পছন্দের মেশ বন্ধুরা স্বয়ংক্রিয়ভাবে যুক্ত হয়।" + "value" : "শুধু তোমার ডিভাইসের Keychain-এ সংরক্ষিত থাকে এবং কখনো পাবলিক ফলো তালিকা হিসেবে প্রকাশিত হয় না। Nostr কী থাকা কন্টাক্টগুলো স্বয়ংক্রিয়ভাবে যুক্ত হয়।" } }, "de" : { "stringUnit" : { "state" : "translated", - "value" : "Wird nur im Geräte-Schlüsselbund gespeichert und nie öffentlich geteilt. Mesh-Favoriten mit Nostr-Schlüsseln werden automatisch einbezogen." + "value" : "Wird nur im Schlüsselbund deines Geräts gespeichert und niemals als öffentliche Follower-Liste veröffentlicht. Kontakte mit Nostr-Schlüsseln werden automatisch einbezogen." } }, "en" : { "stringUnit" : { "state" : "translated", - "value" : "Stored only in your device Keychain and never published as a public follow list. Mutual mesh favorites with Nostr keys are included automatically." + "value" : "Stored only in your device Keychain and never published as a public follow list. Contacts with Nostr keys are included automatically." } }, "es" : { "stringUnit" : { "state" : "translated", - "value" : "Guardado solo en el llavero de tu dispositivo y nunca publicado. Los favoritos de malla con claves Nostr se incluyen automáticamente." + "value" : "Se guarda solo en el llavero de tu dispositivo y nunca se publica como lista pública. Los contactos con claves Nostr se incluyen automáticamente." } }, "fa" : { "stringUnit" : { "state" : "translated", - "value" : "فقط در Keychain دستگاه ذخیره می‌شود و هرگز عمومی منتشر نمی‌شود. دوستان منتخب مش با کلید Nostr خودکار اضافه می‌شوند." + "value" : "فقط در Keychain دستگاه شما ذخیره می‌شود و هرگز به‌عنوان فهرست دنبال‌شوندگان عمومی منتشر نمی‌شود. مخاطبان دارای کلید Nostr به‌طور خودکار اضافه می‌شوند." } }, "fil" : { "stringUnit" : { "state" : "translated", - "value" : "Naka-save lang sa Keychain ng iyong device at hindi kailanman inilalathala. Awtomatikong kasama ang mga mesh favorite na may Nostr key." + "value" : "Naka-store lang sa Keychain ng device mo at hindi kailanman inilalathala bilang pampublikong listahan. Awtomatikong kasama ang mga contact na may Nostr key." } }, "fr" : { "stringUnit" : { "state" : "translated", - "value" : "Stocké uniquement dans le trousseau de votre appareil et jamais publié. Les favoris mesh dotés de clés Nostr sont inclus automatiquement." + "value" : "Stockée uniquement dans le trousseau de votre appareil et jamais publiée comme liste publique. Les contacts disposant d’une clé Nostr sont inclus automatiquement." } }, "he" : { "stringUnit" : { "state" : "translated", - "value" : "נשמר רק ב-Keychain של המכשיר ולא מפורסם לעולם. מועדפי רשת עם מפתחות Nostr נכללים אוטומטית." + "value" : "נשמר רק במחזיק המפתחות של המכשיר ולא מתפרסם לעולם כרשימת מעקב ציבורית. אנשי קשר עם מפתחות Nostr נכללים אוטומטית." } }, "hi" : { "stringUnit" : { "state" : "translated", - "value" : "केवल आपके डिवाइस के कीचेन में सहेजा जाता है और कभी सार्वजनिक नहीं किया जाता। Nostr कुंजी वाले पसंदीदा मेश मित्र स्वतः जुड़ जाते हैं।" + "value" : "केवल आपके डिवाइस के Keychain में संग्रहीत होता है और कभी सार्वजनिक फॉलो सूची के रूप में प्रकाशित नहीं होता। Nostr कुंजी वाले संपर्क अपने आप शामिल हो जाते हैं।" } }, "id" : { "stringUnit" : { "state" : "translated", - "value" : "Hanya disimpan di Keychain perangkat dan tidak pernah dipublikasikan. Favorit mesh dengan kunci Nostr otomatis disertakan." + "value" : "Hanya disimpan di Keychain perangkat Anda dan tidak pernah dipublikasikan sebagai daftar ikuti publik. Kontak dengan kunci Nostr otomatis disertakan." } }, "it" : { "stringUnit" : { "state" : "translated", - "value" : "Salvato solo nel portachiavi del dispositivo e mai pubblicato. I preferiti mesh con chiavi Nostr sono inclusi automaticamente." + "value" : "Salvata solo nel portachiavi del dispositivo e mai pubblicata come elenco pubblico. I contatti con chiavi Nostr vengono inclusi automaticamente." } }, "ja" : { "stringUnit" : { "state" : "translated", - "value" : "端末のキーチェーンのみに保存され、公開されることはありません。Nostr鍵を持つメッシュのお気に入りは自動で含まれます。" + "value" : "デバイスのキーチェーンにのみ保存され、公開フォローリストとして公開されることはありません。Nostrキーを持つ連絡先は自動的に含まれます。" } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "기기 키체인에만 저장되며 공개되지 않습니다. Nostr 키가 있는 메시 즐겨찾기는 자동으로 포함됩니다." + "value" : "기기 키체인에만 저장되며 공개 팔로우 목록으로 게시되지 않습니다. Nostr 키가 있는 연락처는 자동으로 포함됩니다." } }, "ms" : { "stringUnit" : { "state" : "translated", - "value" : "Disimpan hanya dalam Keychain peranti dan tidak pernah diterbitkan. Kegemaran mesh dengan kunci Nostr disertakan secara automatik." + "value" : "Disimpan hanya dalam Keychain peranti anda dan tidak pernah diterbitkan sebagai senarai ikutan awam. Kenalan dengan kunci Nostr disertakan secara automatik." } }, "ne" : { "stringUnit" : { "state" : "translated", - "value" : "केवल तपाईंको उपकरणको कीचेनमा सुरक्षित रहन्छ र कहिल्यै सार्वजनिक गरिँदैन। Nostr कुञ्जी भएका मनपर्ने मेश साथीहरू स्वतः समावेश हुन्छन्।" + "value" : "तपाईंको डिभाइसको Keychain मा मात्र भण्डारण हुन्छ र सार्वजनिक फलो सूचीको रूपमा कहिल्यै प्रकाशित हुँदैन। Nostr कुञ्जी भएका सम्पर्कहरू स्वतः समावेश हुन्छन्।" } }, "nl" : { "stringUnit" : { "state" : "translated", - "value" : "Alleen opgeslagen in je sleutelhanger en nooit openbaar gepubliceerd. Mesh-favorieten met Nostr-sleutels worden automatisch opgenomen." + "value" : "Alleen opgeslagen in de sleutelhanger van je apparaat en nooit gepubliceerd als openbare volglijst. Contacten met Nostr-sleutels worden automatisch opgenomen." } }, "pl" : { "stringUnit" : { "state" : "translated", - "value" : "Przechowywane wyłącznie w pęku kluczy urządzenia i nigdy nie publikowane. Ulubieni z sieci mesh z kluczami Nostr są dodawani automatycznie." + "value" : "Przechowywana wyłącznie w pęku kluczy urządzenia i nigdy nie publikowana jako publiczna lista obserwowanych. Kontakty z kluczami Nostr są dodawane automatycznie." } }, "pt" : { "stringUnit" : { "state" : "translated", - "value" : "Guardado apenas no Porta-chaves do dispositivo e nunca publicado. Favoritos mesh com chaves Nostr são incluídos automaticamente." + "value" : "Guardada apenas no Porta-chaves do dispositivo e nunca publicada como lista pública. Contactos com chaves Nostr são incluídos automaticamente." } }, "pt-BR" : { "stringUnit" : { "state" : "translated", - "value" : "Salvo apenas no Keychain do aparelho e nunca publicado. Favoritos mesh com chaves Nostr são incluídos automaticamente." + "value" : "Armazenada apenas nas Chaves do dispositivo e nunca publicada como lista pública. Contatos com chaves Nostr são incluídos automaticamente." } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Хранится только в Keychain устройства и никогда не публикуется. Избранные контакты mesh с ключами Nostr добавляются автоматически." + "value" : "Хранится только в связке ключей вашего устройства и никогда не публикуется как публичный список подписок. Контакты с ключами Nostr включаются автоматически." } }, "sv" : { "stringUnit" : { "state" : "translated", - "value" : "Lagras endast i enhetens nyckelring och publiceras aldrig. Mesh-favoriter med Nostr-nycklar inkluderas automatiskt." + "value" : "Lagras endast i enhetens nyckelring och publiceras aldrig som en offentlig följlista. Kontakter med Nostr-nycklar inkluderas automatiskt." } }, "ta" : { "stringUnit" : { "state" : "translated", - "value" : "உங்கள் சாதன கீசெயினில் மட்டுமே சேமிக்கப்படும்; ஒருபோதும் பொதுவில் வெளியிடப்படாது. Nostr விசையுள்ள பிடித்தவர்கள் தானாக சேர்க்கப்படுவர்." + "value" : "உங்கள் சாதன Keychain-இல் மட்டுமே சேமிக்கப்படும்; பொது பின்தொடர்பு பட்டியலாக ஒருபோதும் வெளியிடப்படாது. Nostr விசைகள் கொண்ட தொடர்புகள் தானாகவே சேர்க்கப்படும்." } }, "th" : { "stringUnit" : { "state" : "translated", - "value" : "เก็บไว้ใน Keychain ของอุปกรณ์เท่านั้นและไม่เคยเผยแพร่สาธารณะ เพื่อนโปรดในเมชที่มีคีย์ Nostr จะถูกรวมให้อัตโนมัติ" + "value" : "จัดเก็บไว้ในพวงกุญแจของอุปกรณ์เท่านั้นและจะไม่เผยแพร่เป็นรายการติดตามสาธารณะ รายชื่อติดต่อที่มีคีย์ Nostr จะถูกรวมไว้โดยอัตโนมัติ" } }, "tr" : { "stringUnit" : { "state" : "translated", - "value" : "Yalnızca cihaz Anahtar Zincirinde saklanır ve asla herkese açık yayınlanmaz. Nostr anahtarlı mesh favorileri otomatik eklenir." + "value" : "Yalnızca cihazınızın Anahtar Zinciri’nde saklanır ve hiçbir zaman herkese açık takip listesi olarak yayınlanmaz. Nostr anahtarına sahip kişiler otomatik olarak eklenir." } }, "uk" : { "stringUnit" : { "state" : "translated", - "value" : "Зберігається лише в Keychain пристрою й ніколи не публікується. Улюблені mesh-контакти з ключами Nostr додаються автоматично." + "value" : "Зберігається лише у в’язці ключів вашого пристрою й ніколи не публікується як публічний список підписок. Контакти з ключами Nostr додаються автоматично." } }, "ur" : { "stringUnit" : { "state" : "translated", - "value" : "صرف آپ کے آلے کے کی چین میں محفوظ رہتا ہے اور کبھی عوامی نہیں ہوتا۔ Nostr کلید والے پسندیدہ میش دوست خودکار شامل ہو جاتے ہیں۔" + "value" : "صرف آپ کے آلے کے Keychain میں محفوظ ہوتی ہے اور کبھی عوامی فالو فہرست کے طور پر شائع نہیں ہوتی۔ Nostr کلیدوں والے رابطے خودکار طور پر شامل ہو جاتے ہیں۔" } }, "vi" : { "stringUnit" : { "state" : "translated", - "value" : "Chỉ lưu trong Keychain trên thiết bị và không bao giờ công khai. Bạn bè mesh yêu thích có khóa Nostr được tự động thêm vào." + "value" : "Chỉ lưu trong Keychain của thiết bị và không bao giờ được công khai như danh sách theo dõi. Các liên hệ có khóa Nostr sẽ tự động được thêm vào." } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "仅保存在本机钥匙串中,绝不公开广播。已交换 Nostr 密钥的 Mesh 好友会自动包含在内。" + "value" : "仅保存在设备的钥匙串中,绝不会作为公开关注列表发布。带有 Nostr 密钥的联系人会自动包含在内。" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "僅儲存在本機鑰匙圈中,絕不公開廣播。已交換 Nostr 金鑰的 Mesh 好友會自動包含在內。" + "value" : "僅儲存在裝置的鑰匙圈中,絕不會作為公開追蹤名單發布。擁有 Nostr 金鑰的聯絡人會自動包含在內。" } } } @@ -149970,6 +149970,191 @@ } } } + }, + "content.private.transport.group_nostr_queued" : { + "comment" : "Group transport caption when members have Nostr keys and messages will flush once a Nostr relay connects", + "localizations" : { + "ar" : { + "stringUnit" : { + "state" : "translated", + "value" : "مشفر · في انتظار مرحّل Nostr" + } + }, + "bn" : { + "stringUnit" : { + "state" : "translated", + "value" : "এনক্রিপ্টেড · Nostr রিলের জন্য অপেক্ষমাণ" + } + }, + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Verschlüsselt · Wartet auf Nostr-Relay" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Encrypted · Queued for Nostr relay" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cifrado · En cola para relay de Nostr" + } + }, + "fa" : { + "stringUnit" : { + "state" : "translated", + "value" : "رمزگذاری‌شده · در صف رله Nostr" + } + }, + "fil" : { + "stringUnit" : { + "state" : "translated", + "value" : "Naka-encrypt · Nakapila para sa Nostr relay" + } + }, + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chiffré · En attente d'un relais Nostr" + } + }, + "he" : { + "stringUnit" : { + "state" : "translated", + "value" : "מוצפן · בתור לממסר Nostr" + } + }, + "hi" : { + "stringUnit" : { + "state" : "translated", + "value" : "एन्क्रिप्टेड · Nostr रिले के लिए कतारबद्ध" + } + }, + "id" : { + "stringUnit" : { + "state" : "translated", + "value" : "Terenkripsi · Diantrekan untuk relay Nostr" + } + }, + "it" : { + "stringUnit" : { + "state" : "translated", + "value" : "Crittografato · In coda per il relay Nostr" + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "暗号化済み · Nostrリレーへの送信待機中" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "암호화됨 · Nostr 릴레이 전송 대기 중" + } + }, + "ms" : { + "stringUnit" : { + "state" : "translated", + "value" : "Disulitkan · Beratur untuk geganti Nostr" + } + }, + "ne" : { + "stringUnit" : { + "state" : "translated", + "value" : "इन्क्रिप्ट · Nostr रिलेका लागि लामबद्ध" + } + }, + "nl" : { + "stringUnit" : { + "state" : "translated", + "value" : "Versleuteld · In wachtrij voor Nostr-relay" + } + }, + "pl" : { + "stringUnit" : { + "state" : "translated", + "value" : "Szyfrowane · W kolejce do przekaźnika Nostr" + } + }, + "pt" : { + "stringUnit" : { + "state" : "translated", + "value" : "Encriptado · Em fila para o relay Nostr" + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "translated", + "value" : "Criptografado · Na fila para relay Nostr" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Зашифровано · В очереди на реле Nostr" + } + }, + "sv" : { + "stringUnit" : { + "state" : "translated", + "value" : "Krypterat · I kö för Nostr-relä" + } + }, + "ta" : { + "stringUnit" : { + "state" : "translated", + "value" : "குறியாக்கப்பட்டது · Nostr ரிலேக்காக வரிசையில்" + } + }, + "th" : { + "stringUnit" : { + "state" : "translated", + "value" : "เข้ารหัส · รอส่งผ่านรีเลย์ Nostr" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Şifreli · Nostr rölesi için sırada" + } + }, + "uk" : { + "stringUnit" : { + "state" : "translated", + "value" : "Зашифровано · У черзі для реле Nostr" + } + }, + "ur" : { + "stringUnit" : { + "state" : "translated", + "value" : "انکرپٹڈ · Nostr ریلے کے لیے قطار میں" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Đã mã hóa · Đang chờ relay Nostr" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "已加密 · 等待 Nostr 中继发送" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "已加密 · 等待 Nostr 中繼傳送" + } + } + } } } } diff --git a/bitchat/Models/BitchatPeer.swift b/bitchat/Models/BitchatPeer.swift index 4ece9c72..6b1b2b55 100644 --- a/bitchat/Models/BitchatPeer.swift +++ b/bitchat/Models/BitchatPeer.swift @@ -14,6 +14,9 @@ struct BitchatPeer: Equatable { // Nostr identity (if known) var nostrPublicKey: String? + /// True when this peer has a verified 1:1 Nostr route (learned from a + /// mutual BLE DM exchange, friend invite, or shared encrypted group). + var hasDirectNostrRoute: Bool = false /// Device-local alias (petname). Never sent over the wire; when set it /// outranks the peer-claimed `nickname` for display only. @@ -23,7 +26,7 @@ struct BitchatPeer: Equatable { enum ConnectionState { case bluetoothConnected case meshReachable // Seen via mesh recently, not directly connected - case nostrAvailable // Mutual favorite, reachable via Nostr + case nostrAvailable // Contact reachable via Nostr case offline // Not connected via any transport } @@ -32,12 +35,9 @@ struct BitchatPeer: Equatable { return .bluetoothConnected } else if isReachable { return .meshReachable - } else if favoriteStatus?.isMutual == true, reachableNostrPublicKey != nil { - // Mutual favorites can communicate via Nostr when offline — but - // only with a stored recipient key. NostrTransport applies the - // same rule when computing reachable peers; without a key, - // "available" would be a lie, and the DM header's - // "end-to-end encrypted" caption keys off this state. + } else if (favoriteStatus?.isMutual == true || hasDirectNostrRoute), reachableNostrPublicKey != nil { + // Contacts with a verified Nostr key can communicate over Nostr + // when out of BLE range. return .nostrAvailable } else { return .offline diff --git a/bitchat/Models/CommandInfo.swift b/bitchat/Models/CommandInfo.swift index 2b077759..b06615b3 100644 --- a/bitchat/Models/CommandInfo.swift +++ b/bitchat/Models/CommandInfo.swift @@ -24,8 +24,6 @@ enum CommandInfo: String, Identifiable { case pay case unblock case who - case favorite = "fav" - case unfavorite = "unfav" case ping case trace case drop @@ -36,7 +34,7 @@ enum CommandInfo: String, Identifiable { var placeholder: String? { switch self { - case .block, .hug, .message, .slap, .unblock, .favorite, .unfavorite, .ping, .trace: + case .block, .hug, .message, .slap, .unblock, .ping, .trace: return "<" + String(localized: "content.input.nickname_placeholder") + ">" case .group: return "<" + String(localized: "content.input.group_placeholder") + ">" @@ -61,8 +59,6 @@ enum CommandInfo: String, Identifiable { case .slap: String(localized: "content.commands.slap") case .unblock: String(localized: "content.commands.unblock") case .who: String(localized: "content.commands.who") - case .favorite: String(localized: "content.commands.favorite") - case .unfavorite: String(localized: "content.commands.unfavorite") case .ping: String(localized: "content.commands.ping") case .trace: String(localized: "content.commands.trace") case .drop: String(localized: "content.commands.drop") @@ -78,11 +74,11 @@ enum CommandInfo: String, Identifiable { if !isGeoPublic { commands.append(.pay) } - // The processor rejects favorites, groups, and mesh diagnostics in - // geohash contexts, so only suggest them where they work: mesh. + // The processor rejects groups and mesh diagnostics in geohash + // contexts, so only suggest them where they work: mesh. if isGeoPublic || isGeoDM { return commands } - return commands + [.favorite, .unfavorite, .ping, .trace, .group] + return commands + [.ping, .trace, .group] } } diff --git a/bitchat/Nostr/NostrRelayConnection.swift b/bitchat/Nostr/NostrRelayConnection.swift index a1f2870e..6e03cd8b 100644 --- a/bitchat/Nostr/NostrRelayConnection.swift +++ b/bitchat/Nostr/NostrRelayConnection.swift @@ -86,6 +86,11 @@ struct NostrRelayManagerDependencies { /// for someone who denied location and has no mutual favorites. var isInLocationChannel: () -> Bool = { false } var selectedChannelPublisher: AnyPublisher = Empty().eraseToAnyPublisher() + /// Whether the user belongs to any multi-member hybrid group. Allows + /// default DM relays to connect and carry sealed group envelopes even when + /// the user has no 1:1 mutual favorites and no location permission. + var hasNostrGroups: () -> Bool = { false } + var hasNostrGroupsPublisher: AnyPublisher = Empty().eraseToAnyPublisher() } extension NostrRelayManagerDependencies { @@ -119,7 +124,9 @@ extension NostrRelayManagerDependencies { if case .location = LocationChannelManager.shared.selectedChannel { return true } return false }, - selectedChannelPublisher: LocationChannelManager.shared.$selectedChannel.eraseToAnyPublisher() + selectedChannelPublisher: LocationChannelManager.shared.$selectedChannel.eraseToAnyPublisher(), + hasNostrGroups: { NetworkActivationService.shared.hasNostrGroups }, + hasNostrGroupsPublisher: NetworkActivationService.shared.$hasNostrGroups.eraseToAnyPublisher() ) } } diff --git a/bitchat/Nostr/NostrRelayManager.swift b/bitchat/Nostr/NostrRelayManager.swift index e760d2b4..a5308f31 100644 --- a/bitchat/Nostr/NostrRelayManager.swift +++ b/bitchat/Nostr/NostrRelayManager.swift @@ -76,6 +76,7 @@ final class NostrRelayManager: ObservableObject { private var allowDefaultRelays: Bool = false private var hasMutualFavorites: Bool = false private var hasLocationPermission: Bool = false + private var hasNostrGroups: Bool = false private var connections: [String: NostrRelayConnectionProtocol] = [:] private var subscriptions: [String: Set] = [:] // relay URL -> active subscription IDs // Not-yet-flushed REQs per relay, bounded by a per-relay cap (oldest by @@ -224,6 +225,7 @@ final class NostrRelayManager: ObservableObject { self.dependencies = dependencies hasMutualFavorites = dependencies.hasMutualFavorites() hasLocationPermission = dependencies.hasLocationPermission() + hasNostrGroups = dependencies.hasNostrGroups() reloadDefaultRelays() applyDefaultRelayPolicy(force: true) // Deterministic JSON shape for outbound requests @@ -252,6 +254,15 @@ final class NostrRelayManager: ObservableObject { self?.applyDefaultRelayPolicy() } .store(in: &cancellables) + dependencies.hasNostrGroupsPublisher + .receive(on: DispatchQueue.main) + .sink { [weak self] hasGroups in + guard let self = self else { return } + if hasGroups == self.hasNostrGroups { return } + self.hasNostrGroups = hasGroups + self.applyDefaultRelayPolicy() + } + .store(in: &cancellables) // Adding or removing a relay by hand changes the target set, so // reconcile connections now rather than at the next send. dependencies.notificationCenter @@ -786,7 +797,7 @@ final class NostrRelayManager: ObservableObject { } private func applyDefaultRelayPolicy(force: Bool = false) { - let shouldAllow = hasMutualFavorites || hasLocationPermission || dependencies.isInLocationChannel() + let shouldAllow = hasMutualFavorites || hasLocationPermission || dependencies.isInLocationChannel() || hasNostrGroups if !force && shouldAllow == allowDefaultRelays { return } allowDefaultRelays = shouldAllow if shouldAllow { diff --git a/bitchat/Protocols/BitchatProtocol.swift b/bitchat/Protocols/BitchatProtocol.swift index 958fe6bc..a124d68a 100644 --- a/bitchat/Protocols/BitchatProtocol.swift +++ b/bitchat/Protocols/BitchatProtocol.swift @@ -91,6 +91,10 @@ enum NoisePayloadType: UInt8 { // capabilities are discovery hints, while this payload proves possession // of the advertised Noise static key before downgrade state is pinned. case authenticatedPeerState = 0x21 + // Signed Nostr routing key exchange sent automatically over an established + // Noise session once both sides have exchanged a 1:1 DM (mutual consent), + // enabling seamless mesh ↔ Nostr 1:1 DM handoff without manual starring. + case nostrRouteExchange = 0x22 // Verification (QR-based OOB binding) case verifyChallenge = 0x10 // Verification challenge case verifyResponse = 0x11 // Verification response @@ -121,6 +125,7 @@ enum NoisePayloadType: UInt8 { case .voiceFrame: return "voiceFrame" case .privateFile: return "privateFile" case .authenticatedPeerState: return "authenticatedPeerState" + case .nostrRouteExchange: return "nostrRouteExchange" case .verifyChallenge: return "verifyChallenge" case .verifyResponse: return "verifyResponse" case .vouch: return "vouch" diff --git a/bitchat/Services/BLE/BLEService.swift b/bitchat/Services/BLE/BLEService.swift index da6ca090..0b42b748 100644 --- a/bitchat/Services/BLE/BLEService.swift +++ b/bitchat/Services/BLE/BLEService.swift @@ -3032,6 +3032,12 @@ final class BLEService: NSObject { sendNoisePayload(NoisePayload(type: .groupKeyUpdate, data: statePayload).encode(), to: peerID) } + /// Sends a signed Nostr route binding payload over the Noise session once + /// mutual 1:1 DM consent exists, enabling seamless Nostr fallback. + func sendNostrRouteExchange(_ payload: Data, to peerID: PeerID) { + sendNoisePayload(NoisePayload(type: .nostrRouteExchange, data: payload).encode(), to: peerID) + } + /// Broadcasts a sealed group message (MessageType 0x25) like a public /// message: fire-and-flood with gossip-sync backfill. The outer packet is /// intentionally unsigned — receivers authenticate the sender's Ed25519 diff --git a/bitchat/Services/CommandProcessor.swift b/bitchat/Services/CommandProcessor.swift index a76d1214..e23cb984 100644 --- a/bitchat/Services/CommandProcessor.swift +++ b/bitchat/Services/CommandProcessor.swift @@ -73,12 +73,6 @@ protocol CommandContextProvider: AnyObject { /// conversation captured when the command was issued. func addCommandOutput(_ content: String, to destination: CommandOutputDestination) - // MARK: - Favorites - /// Toggles the favorite via the unified peer flow, which persists by the - /// real noise key and notifies the peer over mesh or Nostr. - @discardableResult - func toggleFavorite(peerID: PeerID) -> FavoriteToggleOutcome - // MARK: - Groups // Group logic lives in `ChatGroupCoordinator`; these forward the parsed // /group subcommands. @@ -139,12 +133,6 @@ final class CommandProcessor { case "/group": if inGeoPublic || inGeoDM { return .error(message: String(localized: "command.error.groups_mesh_only", defaultValue: "groups are only for mesh peers in #mesh", comment: "Error when a group command is used outside the mesh channel")) } return handleGroup(args) - case "/fav": - if inGeoPublic || inGeoDM { return .error(message: String(localized: "command.error.favorites_mesh_only", defaultValue: "favorites are only for mesh peers in #mesh", comment: "Error when a favorites command is used outside the mesh channel")) } - return handleFavorite(args, add: true) - case "/unfav": - if inGeoPublic || inGeoDM { return .error(message: String(localized: "command.error.favorites_mesh_only", defaultValue: "favorites are only for mesh peers in #mesh", comment: "Error when a favorites command is used outside the mesh channel")) } - return handleFavorite(args, add: false) case "/ping": if inGeoPublic || inGeoDM { return .error(message: String(localized: "command.error.ping_mesh_only", defaultValue: "ping only works for mesh peers in #mesh", comment: "Error when /ping is used outside the mesh channel")) } return handlePing(args) @@ -166,7 +154,7 @@ final class CommandProcessor { /// suggestion panel hides once arguments are typed, and typos used to /// dead-end in a bare "unknown command" — this is the way out. static var helpText: String { - String(localized: "command.help.text", defaultValue: "commands:\n/msg @name [message] — start a private chat\n/who — list who's here\n/clear — clear this chat\n/hug @name — send a hug\n/slap @name — slap with a large trout\n/block @name · /unblock @name\n/fav @name · /unfav @name — favorites (mesh only)\n/group create — start an encrypted group\n/group invite @name · /group remove @name — manage members (creator)\n/group leave · /group list — leave or list your groups\n/ping @name — measure round-trip time (mesh only)\n/trace @name — estimated mesh path (mesh only)\n/pay — send a cashu ecash token in this chat\n/drop — pin a note to this place for 24h (needs location)\n/help — this list", comment: "The /help reference list; command syntax stays verbatim, only the descriptions after each dash are translated") + String(localized: "command.help.text", defaultValue: "commands:\n/msg @name [message] — start a private chat\n/who — list who's here\n/clear — clear this chat\n/hug @name — send a hug\n/slap @name — slap with a large trout\n/block @name · /unblock @name\n/group create — start an encrypted group\n/group invite @name · /group remove @name — manage members (creator)\n/group leave · /group list — leave or list your groups\n/ping @name — measure round-trip time (mesh only)\n/trace @name — estimated mesh path (mesh only)\n/pay — send a cashu ecash token in this chat\n/drop — pin a note to this place for 24h (needs location)\n/help — this list", comment: "The /help reference list; command syntax stays verbatim, only the descriptions after each dash are translated") } /// /drop — a dead drop: pins a note to the current building-level @@ -563,46 +551,4 @@ final class CommandProcessor { contextProvider?.sendPublicMessage(token) return .success(message: String(format: String(localized: "command.pay.sent_public", defaultValue: "sent %@ to the public channel — anyone here can redeem it", comment: "Confirmation after sending a cashu token to a public channel; placeholder is the amount summary"), locale: .current, summary)) } - - private func handleFavorite(_ args: String, add: Bool) -> CommandResult { - let targetName = args.trimmed - guard !targetName.isEmpty else { - return .error(message: String(format: String(localized: "command.action.usage", defaultValue: "usage: /%@ ", comment: "Usage hint for a command that takes a nickname; placeholder is the command name"), locale: .current, (add ? "fav" : "unfav"))) - } - - let nickname = targetName.hasPrefix("@") ? String(targetName.dropFirst()) : targetName - - guard let peerID = contextProvider?.getPeerIDForNickname(nickname) else { - return .error(message: String(format: String(localized: "command.fav.not_found", defaultValue: "can't find peer: %@", comment: "Error when /fav or /unfav can't resolve the nickname"), locale: .current, nickname)) - } - - // Resolve current state by the peer's real noise key. The resolved - // peerID is either the short 16-hex mesh ID or the full 64-hex - // noise-key ID (offline favorite row) — never the noise key itself. - let isCurrentlyFavorite: Bool - if let noiseKey = peerID.noiseKey { - isCurrentlyFavorite = FavoritesPersistenceService.shared.isFavorite(noiseKey) - } else { - isCurrentlyFavorite = FavoritesPersistenceService.shared.getFavoriteStatus(forPeerID: peerID)?.isFavorite ?? false - } - - guard add != isCurrentlyFavorite else { - return .success(message: add - ? String(format: String(localized: "command.fav.already", defaultValue: "%@ is already a favorite", comment: "Reply when /fav targets an existing favorite"), locale: .current, nickname) - : String(format: String(localized: "command.fav.not_favorite", defaultValue: "%@ is not a favorite", comment: "Reply when /unfav targets someone who isn't a favorite"), locale: .current, nickname)) - } - - // toggleFavorite persists by the real noise key and notifies the peer. - switch contextProvider?.toggleFavorite(peerID: peerID) { - case .toggled: - return .success(message: add - ? String(format: String(localized: "command.fav.added", defaultValue: "added %@ to favorites", comment: "Confirmation after /fav"), locale: .current, nickname) - : String(format: String(localized: "command.fav.removed", defaultValue: "removed %@ from favorites", comment: "Confirmation after /unfav"), locale: .current, nickname)) - case .ambiguous: - return .error(message: String(format: String(localized: "command.fav.ambiguous", defaultValue: "ambiguous peer %@ — open the chat or tap the peer row directly", comment: "Error when /fav or /unfav matches multiple offline peer identities"), locale: .current, nickname)) - case .notFound, .none: - return .error(message: String(format: String(localized: "command.fav.not_found", defaultValue: "can't find peer: %@", comment: "Error when /fav or /unfav can't resolve the nickname"), locale: .current, nickname)) - } - } - } diff --git a/bitchat/Services/Groups/GroupOutboxStore.swift b/bitchat/Services/Groups/GroupOutboxStore.swift new file mode 100644 index 00000000..d0a654e4 --- /dev/null +++ b/bitchat/Services/Groups/GroupOutboxStore.swift @@ -0,0 +1,313 @@ +// +// GroupOutboxStore.swift +// bitchat +// +// Encrypted disk persistence for pending hybrid Nostr group message deliveries, +// so group messages sent while offline or while relays are reconnecting survive +// app restarts and flush automatically once a DM relay confirms NIP-01 OK. +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import BitFoundation +import BitLogger +import CryptoKit +import Foundation +import Security + +@MainActor +final class GroupOutboxStore { + struct Entry: Codable, Equatable { + let groupID: Data + let messageID: String + /// Already ChaCha20-Poly1305 sealed group message envelope (`MessageType.groupMessage`). + let payload: Data + /// Fingerprints of roster members still awaiting a confirmed Nostr relay `OK`. + var pendingMemberFingerprints: Set + /// True when at least one group member was connected on BLE mesh at send time. + let hadMeshDeliveryAtSend: Bool + /// True once at least one Nostr relay confirmed `OK` for any member. + var hadAnyNostrConfirmation: Bool + let createdAt: Date + /// Delivery attempts made while a DM relay was connected. + var sendAttempts: Int + + init( + groupID: Data, + messageID: String, + payload: Data, + pendingMemberFingerprints: Set, + hadMeshDeliveryAtSend: Bool, + hadAnyNostrConfirmation: Bool = false, + createdAt: Date, + sendAttempts: Int = 0 + ) { + self.groupID = groupID + self.messageID = messageID + self.payload = payload + self.pendingMemberFingerprints = pendingMemberFingerprints + self.hadMeshDeliveryAtSend = hadMeshDeliveryAtSend + self.hadAnyNostrConfirmation = hadAnyNostrConfirmation + self.createdAt = createdAt + self.sendAttempts = sendAttempts + } + } + + static let maxMessagesPerGroup = 100 + static let maxTotalMessages = 400 + static let messageTTLSeconds: TimeInterval = 24 * 60 * 60 + static let maxSendAttempts = 8 + + private static let encryptionKeychainKey = "groupOutboxEncryptionKey" + + private let keychain: KeychainManagerProtocol + private let fileStore: AppSupportFileStore + private var cachedKey: SymmetricKey? + private var loadUnavailable = false + private(set) var entries: [Entry] = [] + + init( + keychain: KeychainManagerProtocol, + persistsToDisk: Bool = true, + fileURL: URL? = nil + ) { + self.keychain = keychain + self.fileStore = AppSupportFileStore( + persistsToDisk: persistsToDisk, + fileURL: fileURL, + subdirectory: "groups", + fileName: "group_outbox.sealed", + protection: .untilFirstUserAuthentication + ) + if persistsToDisk { + loadFromDisk() + } + } + + @discardableResult + func enqueue(_ entry: Entry) -> [Entry] { + guard !entry.pendingMemberFingerprints.isEmpty else { return [] } + if loadUnavailable { + loadFromDisk() + } + entries.removeAll { $0.groupID == entry.groupID && $0.messageID == entry.messageID } + entries.append(entry) + + var evicted: [Entry] = [] + // Enforce per-group FIFO cap. + let groupIndices = entries.indices.filter { entries[$0].groupID == entry.groupID } + if groupIndices.count > Self.maxMessagesPerGroup { + let overflowCount = groupIndices.count - Self.maxMessagesPerGroup + let indicesToDrop = Set(groupIndices.prefix(overflowCount)) + for idx in indicesToDrop.sorted() { + evicted.append(entries[idx]) + } + entries = entries.enumerated().compactMap { indicesToDrop.contains($0.offset) ? nil : $0.element } + } + // Enforce global FIFO cap. + if entries.count > Self.maxTotalMessages { + let overflow = entries.count - Self.maxTotalMessages + evicted.append(contentsOf: entries.prefix(overflow)) + entries.removeFirst(overflow) + } + persist() + return evicted + } + + /// Marks `memberFingerprint` as confirmed for `messageID`. Returns the + /// updated entry (or nil if the entry is now complete and removed) along + /// with whether this was the first confirmation for the message. + @discardableResult + func markDelivered( + messageID: String, + groupID: Data, + memberFingerprint: String + ) -> (remainingEntry: Entry?, shouldMarkSent: Bool) { + guard let idx = entries.firstIndex(where: { $0.groupID == groupID && $0.messageID == messageID }) else { + return (nil, false) + } + var entry = entries[idx] + guard entry.pendingMemberFingerprints.remove(memberFingerprint) != nil else { + return (entry, false) + } + let wasFirstNostrConfirm = !entry.hadAnyNostrConfirmation + entry.hadAnyNostrConfirmation = true + let remaining: Entry? + if entry.pendingMemberFingerprints.isEmpty { + entries.remove(at: idx) + remaining = nil + } else { + entries[idx] = entry + remaining = entry + } + persist() + return (remaining, wasFirstNostrConfirm) + } + + /// Increments `sendAttempts` for a confirmed-relay attempt. Drops and + /// returns the entry if it reached `maxSendAttempts`. + @discardableResult + func recordRelayAttemptFailure(messageID: String, groupID: Data) -> Entry? { + guard let idx = entries.firstIndex(where: { $0.groupID == groupID && $0.messageID == messageID }) else { + return nil + } + entries[idx].sendAttempts += 1 + if entries[idx].sendAttempts >= Self.maxSendAttempts { + let dropped = entries.remove(at: idx) + persist() + return dropped + } + persist() + return nil + } + + /// Prunes entries for removed groups, removed members, or expired TTLs. + /// Returns dropped entries that had neither mesh delivery nor any Nostr confirmation. + @discardableResult + func prune(now: Date, validMembersByGroupID: [Data: Set]) -> [Entry] { + var failedEntries: [Entry] = [] + var changed = false + var kept: [Entry] = [] + kept.reserveCapacity(entries.count) + + for var entry in entries { + guard let validMembers = validMembersByGroupID[entry.groupID] else { + changed = true + continue + } + if now.timeIntervalSince(entry.createdAt) > Self.messageTTLSeconds { + changed = true + if !entry.hadMeshDeliveryAtSend && !entry.hadAnyNostrConfirmation { + failedEntries.append(entry) + } + continue + } + let filteredMembers = entry.pendingMemberFingerprints.intersection(validMembers) + if filteredMembers.count != entry.pendingMemberFingerprints.count { + changed = true + entry.pendingMemberFingerprints = filteredMembers + } + if entry.pendingMemberFingerprints.isEmpty { + changed = true + continue + } + kept.append(entry) + } + + if changed { + entries = kept + persist() + } + return failedEntries + } + + func removeGroup(withID groupID: Data) { + let countBefore = entries.count + entries.removeAll { $0.groupID == groupID } + if entries.count != countBefore { + persist() + } + } + + func wipe() { + loadUnavailable = false + entries.removeAll() + cachedKey = nil + _ = keychain.deleteIdentityKey(forKey: Self.encryptionKeychainKey) + fileStore.removeIgnoringErrors() + } + + // MARK: - Encrypted Persistence + + private func loadOrCreateEncryptionKey() -> SymmetricKey? { + if let cachedKey { + return cachedKey + } + switch keychain.getIdentityKeyWithResult(forKey: Self.encryptionKeychainKey) { + case .success(let keyData) where keyData.count == 32: + let key = SymmetricKey(data: keyData) + cachedKey = key + return key + case .itemNotFound, .success: + var bytes = Data(count: 32) + let status = bytes.withUnsafeMutableBytes { buf -> OSStatus in + guard let base = buf.baseAddress else { return errSecParam } + return SecRandomCopyBytes(kSecRandomDefault, 32, base) + } + guard status == errSecSuccess, + keychain.saveIdentityKey(bytes, forKey: Self.encryptionKeychainKey) else { + return nil + } + let key = SymmetricKey(data: bytes) + cachedKey = key + return key + case .deviceLocked, .authenticationFailed, .accessDenied, .otherError: + loadUnavailable = true + return nil + } + } + + private func loadFromDisk() { + AppSupportFileStore.drainPendingWrites() + guard let fileURL = fileStore.fileURL, + FileManager.default.fileExists(atPath: fileURL.path) else { + loadUnavailable = false + return + } + let sealedData: Data + do { + sealedData = try Data(contentsOf: fileURL) + } catch { + loadUnavailable = true + SecureLogger.warning("⚠️ Group outbox disk read unavailable at launch; deferring writes", category: .security) + return + } + switch keychain.getIdentityKeyWithResult(forKey: Self.encryptionKeychainKey) { + case .success(let keyData) where keyData.count == 32: + let key = SymmetricKey(data: keyData) + cachedKey = key + do { + let box = try ChaChaPoly.SealedBox(combined: sealedData) + let plaintext = try ChaChaPoly.open(box, using: key) + let decoded = try JSONDecoder().decode([Entry].self, from: plaintext) + loadUnavailable = false + if entries.isEmpty { + entries = decoded + } else { + // Merge without dropping in-session enqueues. + let existingKeys = Set(entries.map { "\($0.groupID.hexEncodedString()):\($0.messageID)" }) + let merged = decoded.filter { !existingKeys.contains("\($0.groupID.hexEncodedString()):\($0.messageID)") } + entries + entries = Array(merged.suffix(Self.maxTotalMessages)) + } + } catch { + loadUnavailable = false + SecureLogger.warning("⚠️ Failed to open persisted group outbox; starting clean: \(error)", category: .security) + fileStore.removeIgnoringErrors() + } + case .itemNotFound, .success: + loadUnavailable = false + fileStore.removeIgnoringErrors() + case .deviceLocked, .authenticationFailed, .accessDenied, .otherError: + loadUnavailable = true + SecureLogger.warning("⚠️ Group outbox key unavailable at launch; deferring writes", category: .security) + } + } + + private func persist() { + guard fileStore.fileURL != nil else { return } + guard !loadUnavailable else { return } + if entries.isEmpty { + fileStore.removeIgnoringErrors() + return + } + guard let key = loadOrCreateEncryptionKey() else { return } + do { + let plaintext = try JSONEncoder().encode(entries) + let sealed = try ChaChaPoly.seal(plaintext, using: key).combined + try fileStore.writeRawOffMain(sealed) + } catch { + SecureLogger.error("Failed to persist group outbox: \(error)", category: .session) + } + } +} diff --git a/bitchat/Services/Groups/GroupProtocol.swift b/bitchat/Services/Groups/GroupProtocol.swift index b0f4dedf..143c3dca 100644 --- a/bitchat/Services/Groups/GroupProtocol.swift +++ b/bitchat/Services/Groups/GroupProtocol.swift @@ -486,6 +486,26 @@ struct GroupMessagePlaintext: Equatable { let senderNickname: String let timestampMs: UInt64 let content: String + /// Optional 64-char lowercase hex x-only Nostr public key attached by the + /// sender inside the encrypted group envelope so BLE-formed groups learn + /// each member's Nostr route automatically. + let senderNostrPubkeyHex: String? + + init( + messageID: String, + senderSigningKey: Data, + senderNickname: String, + timestampMs: UInt64, + content: String, + senderNostrPubkeyHex: String? = nil + ) { + self.messageID = messageID + self.senderSigningKey = senderSigningKey + self.senderNickname = senderNickname + self.timestampMs = timestampMs + self.content = content + self.senderNostrPubkeyHex = senderNostrPubkeyHex + } } // MARK: - Crypto @@ -508,6 +528,8 @@ enum GroupCrypto { case timestamp = 0x04 case content = 0x05 case signature = 0x06 + /// Optional 32-byte raw x-only Nostr public key (ignored by legacy clients). + case senderNostrPubkey = 0x07 } /// Bytes the sender signs: domain | groupID | epoch | messageID | timestamp | content. @@ -538,6 +560,7 @@ enum GroupCrypto { messageID: String, senderNickname: String, senderSigningKey: Data, + senderNostrPubkeyHex: String? = nil, timestampMs: UInt64, groupID: Data, epoch: UInt32, @@ -562,6 +585,12 @@ enum GroupCrypto { try GroupTLV.put(InnerField.timestamp.rawValue, GroupTLV.timestampData(timestampMs), into: &inner) try GroupTLV.put(InnerField.content.rawValue, Data(content.utf8), into: &inner) try GroupTLV.put(InnerField.signature.rawValue, signature, into: &inner) + if let hex = senderNostrPubkeyHex?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(), + hex.count == 64, + let nostrKeyBytes = Data(hexString: hex), + nostrKeyBytes.count == 32 { + try GroupTLV.put(InnerField.senderNostrPubkey.rawValue, nostrKeyBytes, into: &inner) + } do { let symmetricKey = SymmetricKey(data: key) @@ -609,6 +638,7 @@ enum GroupCrypto { var timestampMs: UInt64? var content: String? var signature: Data? + var senderNostrPubkeyHex: String? for (type, value) in fields { switch InnerField(rawValue: type) { case .messageID: @@ -623,6 +653,8 @@ enum GroupCrypto { content = String(data: value, encoding: .utf8) case .signature where value.count == 64: signature = value + case .senderNostrPubkey where value.count == 32: + senderNostrPubkeyHex = value.hexEncodedString().lowercased() default: break } @@ -650,7 +682,8 @@ enum GroupCrypto { senderSigningKey: senderSigningKey, senderNickname: senderNickname, timestampMs: timestampMs, - content: content + content: content, + senderNostrPubkeyHex: senderNostrPubkeyHex ) } } diff --git a/bitchat/Services/Groups/GroupStore.swift b/bitchat/Services/Groups/GroupStore.swift index 72a505d7..1814be5c 100644 --- a/bitchat/Services/Groups/GroupStore.swift +++ b/bitchat/Services/Groups/GroupStore.swift @@ -157,6 +157,50 @@ final class GroupStore: ObservableObject { return updated } + /// Records learned Nostr x-only public keys (64-hex) for roster members + /// without rotating the epoch. Existing keys are preserved unless + /// `overwriteExisting` is true (used when authoritative favorite records + /// supply a newer key). Returns true if any member changed. + @discardableResult + func updateMemberNostrPubkeys( + groupID: Data, + updates: [String: String], + overwriteExisting: Bool = false + ) -> Bool { + guard !updates.isEmpty, + let index = groups.firstIndex(where: { $0.groupID == groupID }) else { return false } + var updated = groups[index] + var changed = false + for memberIndex in updated.members.indices { + let fp = updated.members[memberIndex].fingerprint + guard let rawHex = updates[fp], + let normalized = Self.validatedNostrPubkeyHex(rawHex) else { continue } + if updated.members[memberIndex].nostrPubkeyHex == nil || overwriteExisting { + if updated.members[memberIndex].nostrPubkeyHex != normalized { + updated.members[memberIndex].nostrPubkeyHex = normalized + changed = true + } + } + } + guard changed else { return false } + groups[index] = updated + persist() + return true + } + + /// True when the user belongs to any multi-member group (so default Nostr + /// relays and the account gift-wrap subscription stay active for both + /// outbound and inbound hybrid group traffic). + var hasActiveMultiMemberGroup: Bool { + groups.contains { $0.members.count > 1 } + } + + private static func validatedNostrPubkeyHex(_ raw: String) -> String? { + let lower = raw.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard lower.count == 64, Data(hexString: lower)?.count == 32 else { return nil } + return lower + } + /// Rotates the group key (creator-side removal/rotation): new random key, /// epoch + 1, and the given roster. Returns the updated group and new key. func rotateKey(groupID: Data, members: [GroupMember]) -> (group: BitchatGroup, key: Data)? { diff --git a/bitchat/Services/LocalWebOfTrustService.swift b/bitchat/Services/LocalWebOfTrustService.swift index da3816e9..50c7d2a7 100644 --- a/bitchat/Services/LocalWebOfTrustService.swift +++ b/bitchat/Services/LocalWebOfTrustService.swift @@ -38,30 +38,45 @@ final class LocalWebOfTrustService { static let shared = LocalWebOfTrustService() private var identityManager: SecureIdentityStateManagerProtocol? - private let noiseKeyLookup: @MainActor (_ nostrPubkeyHex: String) -> Data? + private weak var nostrPeerRouteStore: NostrPeerRouteStore? + private let customNoiseKeyLookup: (@MainActor (_ nostrPubkeyHex: String) -> Data?)? private let isVerifiedFingerprintOverride: ((_ fingerprint: String) -> Bool)? private let validVoucherCountOverride: ((_ fingerprint: String) -> Int)? init( identityManager: SecureIdentityStateManagerProtocol? = nil, + nostrPeerRouteStore: NostrPeerRouteStore? = nil, noiseKeyLookup: (@MainActor (_ nostrPubkeyHex: String) -> Data?)? = nil, isVerifiedFingerprint: ((_ fingerprint: String) -> Bool)? = nil, validVoucherCount: ((_ fingerprint: String) -> Int)? = nil ) { self.identityManager = identityManager - self.noiseKeyLookup = noiseKeyLookup ?? { pubkey in - FavoritesPersistenceService.shared.noisePublicKey(forNostrPubkey: pubkey) - } + self.nostrPeerRouteStore = nostrPeerRouteStore + self.customNoiseKeyLookup = noiseKeyLookup self.isVerifiedFingerprintOverride = isVerifiedFingerprint self.validVoucherCountOverride = validVoucherCount } - func configure(identityManager: SecureIdentityStateManagerProtocol) { + func configure( + identityManager: SecureIdentityStateManagerProtocol, + nostrPeerRouteStore: NostrPeerRouteStore? = nil + ) { self.identityManager = identityManager + if let nostrPeerRouteStore { + self.nostrPeerRouteStore = nostrPeerRouteStore + } + } + + private func resolveNoiseKey(forNostrPubkey nostrPubkeyHex: String) -> Data? { + if let customNoiseKeyLookup { + return customNoiseKeyLookup(nostrPubkeyHex) + } + return FavoritesPersistenceService.shared.noisePublicKey(forNostrPubkey: nostrPubkeyHex) + ?? nostrPeerRouteStore?.noisePublicKey(forNostrPubkey: nostrPubkeyHex) } func trust(forNostrPubkey nostrPubkeyHex: String) -> FeedAuthorTrust { - guard let noiseKey = noiseKeyLookup(nostrPubkeyHex.lowercased()) else { + guard let noiseKey = resolveNoiseKey(forNostrPubkey: nostrPubkeyHex.lowercased()) else { return .none } let fingerprint = noiseKey.sha256Fingerprint() diff --git a/bitchat/Services/MeshTransportCapabilities.swift b/bitchat/Services/MeshTransportCapabilities.swift index 075b9237..69fc03f3 100644 --- a/bitchat/Services/MeshTransportCapabilities.swift +++ b/bitchat/Services/MeshTransportCapabilities.swift @@ -79,6 +79,11 @@ protocol MeshGroupMessaging: AnyObject { func sendGroupInvite(_ statePayload: Data, to peerID: PeerID) func sendGroupKeyUpdate(_ statePayload: Data, to peerID: PeerID) func broadcastGroupMessage(_ envelope: Data) + func sendNostrRouteExchange(_ payload: Data, to peerID: PeerID) +} + +extension MeshGroupMessaging { + func sendNostrRouteExchange(_ payload: Data, to peerID: PeerID) {} } /// Bulletin board: broadcast a pre-signed board payload (post or diff --git a/bitchat/Services/MessageRouter.swift b/bitchat/Services/MessageRouter.swift index 099b6416..243cc7a0 100644 --- a/bitchat/Services/MessageRouter.swift +++ b/bitchat/Services/MessageRouter.swift @@ -116,12 +116,24 @@ final class MessageRouter { // next relaunch instead of surfacing as failed. self?.cleanupExpiredMessages() self?.retryBridgeCourierDeposits() + self?.retryUnconfirmedNostrMessages() } } } private var bridgeSweepTask: Task? + private var nostrRetryTask: Task? private var bridgeDepositsInFlight = Set() + /// Retained outbox messages whose latest Nostr send did not receive a + /// NIP-01 `OK` from any relay (e.g. half-dead socket or transient relay + /// rejection while `isDMRelayConnected` remained true). Only these entries + /// (and unsent `sendAttempts == 0` entries) are retried on the Nostr retry + /// timer so already-accepted messages never spam relays. + private var unconfirmedNostrMessages = Set() + /// Latest desired `[FAVORITED]` / `[UNFAVORITED]` notification for a peer + /// that had no live BLE or Nostr route when toggled; flushed automatically + /// on BLE reconnect or DM relay reconnect. + private var pendingFavoriteNotifications: [PeerID: Bool] = [:] private var favoritesObserver: NSObjectProtocol? private var outbox: [PeerID: [QueuedMessage]] = [:] @@ -178,6 +190,7 @@ final class MessageRouter { deinit { bridgeSweepTask?.cancel() + nostrRetryTask?.cancel() if let favoritesObserver { NotificationCenter.default.removeObserver(favoritesObserver) } @@ -457,10 +470,13 @@ final class MessageRouter { } if let peerIDs { for peerID in peerIDs { - secureTransmissions.remove(PeerMessageKey(peerID: peerID, messageID: messageID)) + let key = PeerMessageKey(peerID: peerID, messageID: messageID) + secureTransmissions.remove(key) + unconfirmedNostrMessages.remove(key) } } else { secureTransmissions = secureTransmissions.filter { $0.messageID != messageID } + unconfirmedNostrMessages = unconfirmedNostrMessages.filter { $0.messageID != messageID } } // Preserve the ack when protected data hides the durable queue during // a cold launch, but skip rewriting disk when nothing changed. @@ -540,7 +556,9 @@ final class MessageRouter { } private func dropMessage(_ messageID: String, for peerID: PeerID) { - secureTransmissions.remove(PeerMessageKey(peerID: peerID, messageID: messageID)) + let key = PeerMessageKey(peerID: peerID, messageID: messageID) + secureTransmissions.remove(key) + unconfirmedNostrMessages.remove(key) onMessageDropped?(messageID, peerID) } @@ -571,8 +589,12 @@ final class MessageRouter { /// Panic wipe: forget queued mail on disk and in memory. func wipeOutbox() { + nostrRetryTask?.cancel() + nostrRetryTask = nil outbox.removeAll() secureTransmissions.removeAll() + unconfirmedNostrMessages.removeAll() + pendingFavoriteNotifications.removeAll() bridgeDepositsInFlight.removeAll() outboxStore?.wipe() } @@ -604,16 +626,127 @@ final class MessageRouter { } func sendFavoriteNotification(to peerID: PeerID, isFavorite: Bool) { + if deliverFavoriteNotificationIfLive(to: peerID, isFavorite: isFavorite) { + clearPendingFavoriteNotification(for: peerID) + return + } + // No live BLE or Nostr relay path right now: retain the latest toggle + // so mutual-favorite sync finishes automatically on reconnect instead + // of silently leaving the relationship stuck one-sided. + clearPendingFavoriteNotification(for: peerID) + pendingFavoriteNotifications[peerID] = isFavorite + SecureLogger.debug("Queued FAVORITE(\(isFavorite)) for \(peerID.id.prefix(8))… until reconnect", category: .session) + } + + private func deliverFavoriteNotificationIfLive(to peerID: PeerID, isFavorite: Bool) -> Bool { if let transport = connectedTransport(for: peerID) { transport.sendFavoriteNotification(to: peerID, isFavorite: isFavorite) - } else if let transport = transports.first(where: { $0.isPeerReachable(peerID) && $0.canDeliverPromptly(to: peerID) }) { + return true + } + if let transport = transports.first(where: { $0.isPeerReachable(peerID) && $0.canDeliverPromptly(to: peerID) }) { transport.sendFavoriteNotification(to: peerID, isFavorite: isFavorite) - } else if let transport = reachableTransport(for: peerID) { - transport.sendFavoriteNotification(to: peerID, isFavorite: isFavorite) - } else if let nostr = nostrTransport, nostr.canSendFavoriteNotification(to: peerID) { + return true + } + if let nostr = nostrTransport, + nostr.canSendFavoriteNotification(to: peerID), + nostr.hasConnectedDMRelay { // One-sided relationships aren't Nostr-reachable for normal DMs, // but still need [FAVORITED]/[UNFAVORITED] routed over Nostr. nostr.sendFavoriteNotification(to: peerID, isFavorite: isFavorite) + return true + } + return false + } + + private func clearPendingFavoriteNotification(for peerID: PeerID) { + let short = peerID.toShort() + for key in Array(pendingFavoriteNotifications.keys) where key == peerID || key.toShort() == short { + pendingFavoriteNotifications.removeValue(forKey: key) + } + } + + private func flushPendingFavoriteNotifications(for peerID: PeerID? = nil) { + guard !pendingFavoriteNotifications.isEmpty else { return } + let targetShort = peerID?.toShort() + let candidates = pendingFavoriteNotifications.filter { key, _ in + guard let peerID, let targetShort else { return true } + return key == peerID || key.toShort() == targetShort + } + for (storedPeerID, isFavorite) in candidates { + let deliveryPeerID = (peerID != nil && deliverFavoriteNotificationIfLive(to: peerID!, isFavorite: isFavorite)) + ? peerID! + : (deliverFavoriteNotificationIfLive(to: storedPeerID, isFavorite: isFavorite) ? storedPeerID : nil) + if deliveryPeerID != nil { + clearPendingFavoriteNotification(for: storedPeerID) + SecureLogger.debug("Flushed queued FAVORITE(\(isFavorite)) for \(storedPeerID.id.prefix(8))…", category: .session) + } + } + } + + /// Handles NIP-01 `OK` / failure settlement for a 1:1 Nostr DM send. + func handleNostrPrivateMessageSendResult(messageID: String, peerID: PeerID, accepted: Bool) { + let aliases = outboxAliases(for: peerID) + let matchedPeerID = aliases.first(where: { queuedMessage(messageID, for: $0) != nil }) ?? peerID + let key = PeerMessageKey(peerID: matchedPeerID, messageID: messageID) + + if accepted { + for alias in aliases { + unconfirmedNostrMessages.remove(PeerMessageKey(peerID: alias, messageID: messageID)) + } + unconfirmedNostrMessages.remove(key) + onMessageSent?(messageID, matchedPeerID) + return + } + + guard queuedMessage(messageID, for: matchedPeerID) != nil else { return } + unconfirmedNostrMessages.insert(key) + if nostrTransport?.hasConnectedDMRelay == true { + scheduleNostrRetryIfNeeded() + } + } + + /// Retries only outbox entries whose Nostr send never received a relay `OK` + /// (or was never sent yet), without re-sending messages a relay already + /// accepted. + func retryUnconfirmedNostrMessages() { + guard let nostr = nostrTransport, nostr.hasConnectedDMRelay else { return } + let currentDate = now() + var outboxChanged = false + for (peerID, queue) in outbox { + guard nostr.isPeerReachable(peerID) && nostr.canDeliverPromptly(to: peerID) else { continue } + for message in queue { + let key = PeerMessageKey(peerID: peerID, messageID: message.messageID) + guard unconfirmedNostrMessages.contains(key) || message.sendAttempts == 0 else { continue } + guard queuedMessage(message.messageID, for: peerID) != nil else { continue } + if dropIfExpiredOrAtAttemptCap(message, for: peerID, now: currentDate, enforceAttemptCap: true) { + outboxChanged = true + continue + } + SecureLogger.debug( + "Retry unconfirmed Nostr PM for \(peerID.id.prefix(8))… id=\(message.messageID.prefix(8))…", + category: .session + ) + nostr.sendPrivateMessage( + message.content, + to: peerID, + recipientNickname: message.nickname, + messageID: message.messageID + ) + outboxChanged = incrementSendAttemptsIfQueued(message.messageID, for: peerID) || outboxChanged + } + } + if outboxChanged { + persistOutbox() + } + } + + private func scheduleNostrRetryIfNeeded(delaySeconds: TimeInterval = 15) { + guard nostrRetryTask == nil, !unconfirmedNostrMessages.isEmpty else { return } + nostrRetryTask = Task { @MainActor [weak self] in + try? await Task.sleep(nanoseconds: UInt64(delaySeconds * 1_000_000_000)) + guard let self, !Task.isCancelled else { return } + self.nostrRetryTask = nil + self.retryUnconfirmedNostrMessages() } } @@ -766,6 +899,7 @@ final class MessageRouter { } func flushOutbox(for peerID: PeerID) { + flushPendingFavoriteNotifications(for: peerID) let aliases = outboxAliases(for: peerID) guard !aliases.isEmpty else { return } if aliases.count == 1, let single = aliases.first { @@ -877,11 +1011,17 @@ final class MessageRouter { if dropIfExpiredOrAtAttemptCap(message, for: peerID, now: now, enforceAttemptCap: true) { return true } + let nonNostrDelivered = promptTargets.contains { !($0.0 is NostrTransport) } for (transport, sendPeerID) in promptTargets { SecureLogger.debug("Outbox -> \(type(of: transport)) (reachable/prompt) for \(peerID.id.prefix(8))… id=\(message.messageID.prefix(8))…", category: .session) transport.sendPrivateMessage(message.content, to: sendPeerID, recipientNickname: message.nickname, messageID: message.messageID) } - onMessageSent?(message.messageID, peerID) + // Nostr-only sends advance `.sending` → `.sent` when NIP-01 `OK` arrives + // via `handleNostrPrivateMessageSendResult` (or immediately if no result + // callback is wired in lightweight tests). + if nonNostrDelivered || nostrTransport?.onPrivateMessageSendResult == nil { + onMessageSent?(message.messageID, peerID) + } return incrementSendAttemptsIfQueued(message.messageID, for: peerID) } @@ -943,6 +1083,7 @@ final class MessageRouter { continue } secureTransmissions.remove(PeerMessageKey(peerID: peerID, messageID: message.messageID)) + let nonNostrDelivered = targets.contains { !($0.0 is NostrTransport) } for (transport, sendPeerID) in targets { SecureLogger.debug( "Failover -> \(type(of: transport)) after disconnect for \(peerID.id.prefix(8))… id=\(message.messageID.prefix(8))…", @@ -955,7 +1096,9 @@ final class MessageRouter { messageID: message.messageID ) } - onMessageSent?(message.messageID, peerID) + if nonNostrDelivered || nostrTransport?.onPrivateMessageSendResult == nil { + onMessageSent?(message.messageID, peerID) + } outboxChanged = incrementSendAttemptsIfQueued(message.messageID, for: peerID) || outboxChanged } @@ -1061,6 +1204,7 @@ final class MessageRouter { } func flushAllOutbox() { + flushPendingFavoriteNotifications() var anyChanged = false for key in Array(outbox.keys) { if flushOutbox(for: key, persist: false) { diff --git a/bitchat/Services/NetworkActivationService.swift b/bitchat/Services/NetworkActivationService.swift index 4f983a9e..e862302e 100644 --- a/bitchat/Services/NetworkActivationService.swift +++ b/bitchat/Services/NetworkActivationService.swift @@ -53,6 +53,10 @@ final class NetworkActivationService: ObservableObject { /// Coarse, debounced network reachability. `false` only when the OS reports /// no usable interface at all. Surfaced for UI ("offline" vs "connecting"). @Published private(set) var isNetworkReachable: Bool = true + /// True while the user belongs to at least one multi-member encrypted group + /// or has verified direct Nostr routes so default Nostr relays stay active + /// even without 1:1 mutual favorites or location permission. + @Published private(set) var hasNostrGroups: Bool = false private var cancellables = Set() private var started = false @@ -65,9 +69,11 @@ final class NetworkActivationService: ObservableObject { private let locationPermissionPublisher: AnyPublisher private let mutualFavoritesPublisher: AnyPublisher, Never> private let selectedChannelPublisher: AnyPublisher + private let hasNostrGroupsPublisher: AnyPublisher private let permissionProvider: () -> LocationChannelManager.PermissionState private let mutualFavoritesProvider: () -> Set private let locationChannelSelectedProvider: () -> Bool + private let externalHasNostrGroupsProvider: () -> Bool private let reachabilityMonitor: NetworkReachabilityMonitoring private let torController: NetworkActivationTorControlling // Resolved lazily: NostrRelayManager.init() reads NetworkActivationService.shared @@ -83,12 +89,14 @@ final class NetworkActivationService: ObservableObject { locationPermissionPublisher = LocationChannelManager.shared.$permissionState.eraseToAnyPublisher() mutualFavoritesPublisher = FavoritesPersistenceService.shared.$mutualFavorites.eraseToAnyPublisher() selectedChannelPublisher = LocationChannelManager.shared.$selectedChannel.eraseToAnyPublisher() + hasNostrGroupsPublisher = Empty().eraseToAnyPublisher() permissionProvider = { LocationChannelManager.shared.permissionState } mutualFavoritesProvider = { FavoritesPersistenceService.shared.mutualFavorites } locationChannelSelectedProvider = { if case .location = LocationChannelManager.shared.selectedChannel { return true } return false } + externalHasNostrGroupsProvider = { false } reachabilityMonitor = NWPathReachabilityMonitor() torController = TorManager.shared relayControllerProvider = { NostrRelayManager.shared } @@ -104,6 +112,8 @@ final class NetworkActivationService: ObservableObject { mutualFavoritesProvider: @escaping () -> Set, selectedChannelPublisher: AnyPublisher = Empty().eraseToAnyPublisher(), locationChannelSelectedProvider: @escaping () -> Bool = { false }, + hasNostrGroupsPublisher: AnyPublisher = Empty().eraseToAnyPublisher(), + hasNostrGroupsProvider: @escaping () -> Bool = { false }, reachabilityMonitor: NetworkReachabilityMonitoring, torController: NetworkActivationTorControlling, relayController: NetworkActivationRelayControlling, @@ -117,6 +127,9 @@ final class NetworkActivationService: ObservableObject { self.mutualFavoritesProvider = mutualFavoritesProvider self.selectedChannelPublisher = selectedChannelPublisher self.locationChannelSelectedProvider = locationChannelSelectedProvider + self.hasNostrGroupsPublisher = hasNostrGroupsPublisher + self.externalHasNostrGroupsProvider = hasNostrGroupsProvider + self.hasNostrGroups = hasNostrGroupsProvider() self.reachabilityMonitor = reachabilityMonitor self.torController = torController self.relayControllerProvider = { relayController } @@ -196,6 +209,14 @@ final class NetworkActivationService: ObservableObject { } .store(in: &cancellables) + // React to multi-member hybrid group / contact Nostr route changes. + hasNostrGroupsPublisher + .receive(on: DispatchQueue.main) + .sink { [weak self] hasGroups in + self?.setHasNostrGroups(hasGroups) + } + .store(in: &cancellables) + // React to network reachability changes (debounced, unsatisfied-only). reachabilityMonitor.reachabilityPublisher .receive(on: DispatchQueue.main) @@ -223,6 +244,12 @@ final class NetworkActivationService: ObservableObject { .store(in: &cancellables) } + func setHasNostrGroups(_ hasGroups: Bool) { + guard hasGroups != hasNostrGroups else { return } + hasNostrGroups = hasGroups + reevaluate() + } + /// Stops all internet-facing work at the synchronous panic boundary and /// restores the default Tor-enabled posture so a wiped device never stays /// on clearnet after recovery. `start()` may be called again only after @@ -232,6 +259,7 @@ final class NetworkActivationService: ObservableObject { started = false reachabilityMonitor.stop() activationAllowed = false + hasNostrGroups = false torAutoStartDesired = false userTorEnabled = true storage.removeObject(forKey: Self.torPreferenceKey) @@ -310,7 +338,8 @@ final class NetworkActivationService: ObservableObject { // is itself an internet feature in active use, which is exactly what // this gate is meant to detect. let inLocationChannel = locationChannelSelectedProvider() - return permOK || hasMutual || inLocationChannel + let inHybridGroup = hasNostrGroups || externalHasNostrGroupsProvider() + return permOK || hasMutual || inLocationChannel || inHybridGroup } /// Effective gate: base policy AND a usable network path. When there is diff --git a/bitchat/Services/NostrFollowsStore.swift b/bitchat/Services/NostrFollowsStore.swift index 0a83211a..0c207e4e 100644 --- a/bitchat/Services/NostrFollowsStore.swift +++ b/bitchat/Services/NostrFollowsStore.swift @@ -45,7 +45,9 @@ final class NostrFollowsStore: ObservableObject { private let keychain: KeychainManagerProtocol private let favoritesProvider: () -> [FavoritesPersistenceService.FavoriteRelationship] + private var contactRoutesProvider: () -> [NostrPeerRouteStore.Route] = { [] } private var favoritesCancellable: AnyCancellable? + private var contactRoutesCancellable: AnyCancellable? #if os(iOS) private var unlockObserver: NSObjectProtocol? #endif @@ -210,6 +212,19 @@ final class NostrFollowsStore: ObservableObject { return isExplicitlyFollowing(normalized) || favoriteFollowPubkeys.contains(normalized) } + func configureContactRoutesStore(_ store: NostrPeerRouteStore) { + contactRoutesCancellable?.cancel() + contactRoutesProvider = { [weak store] in + Array(store?.routes.values ?? [:].values) + } + contactRoutesCancellable = store.$routes + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + self?.refreshMergedFollows() + } + refreshMergedFollows() + } + func localAlias(for pubkeyHex: String) -> String? { let normalized = pubkeyHex.lowercased() if let explicit = explicitFollows.first(where: { $0.pubkeyHex == normalized })?.alias?.trimmedOrNilIfEmpty { @@ -223,6 +238,13 @@ final class NostrFollowsStore: ObservableObject { return nick } } + for route in contactRoutesProvider() { + if route.nostrPubkeyHex == normalized, + let nick = route.peerNickname.trimmedOrNilIfEmpty, + nick != "Unknown" { + return nick + } + } return nil } @@ -234,6 +256,11 @@ final class NostrFollowsStore: ObservableObject { favSet.insert(hex) } } + for route in contactRoutesProvider() { + if let hex = NostrProtocol.normalizePubkeyHex(route.nostrPubkeyHex) { + favSet.insert(hex) + } + } favoriteFollowPubkeys = favSet var seen = Set() diff --git a/bitchat/Services/NostrPeerRouteStore.swift b/bitchat/Services/NostrPeerRouteStore.swift new file mode 100644 index 00000000..a74e8c91 --- /dev/null +++ b/bitchat/Services/NostrPeerRouteStore.swift @@ -0,0 +1,240 @@ +// +// NostrPeerRouteStore.swift +// bitchat +// +// Encrypted persistence for cryptographically verified Nostr DM routes learned +// via mutual 1:1 BLE DM exchanges (NoisePayloadType.nostrRouteExchange). +// Kept separate from user-visible favorites so hybrid mesh ↔ Nostr 1:1 DMs +// work seamlessly without fabricating star/favorite state. +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import BitFoundation +import BitLogger +import Combine +import CryptoKit +import Foundation +import Security + +@MainActor +final class NostrPeerRouteStore: ObservableObject { + struct Route: Codable, Equatable { + let peerNoisePublicKey: Data + let nostrPubkeyHex: String + var peerNickname: String + let updatedAt: Date + } + + private static let encryptionKeychainKey = "nostrPeerRoutesEncryptionKey" + private static let maxRoutes = 256 + + @Published private(set) var routes: [Data: Route] = [:] { + didSet { rebuildReverseIndex() } + } + + private var noiseKeyByNostrHex: [String: Data] = [:] + private let keychain: KeychainManagerProtocol + private let fileStore: AppSupportFileStore + private var cachedKey: SymmetricKey? + private var loadUnavailable = false + + init( + keychain: KeychainManagerProtocol, + persistsToDisk: Bool = true, + fileURL: URL? = nil + ) { + self.keychain = keychain + self.fileStore = AppSupportFileStore( + persistsToDisk: persistsToDisk, + fileURL: fileURL, + subdirectory: "nostr", + fileName: "peer_routes.sealed", + protection: .untilFirstUserAuthentication + ) + if persistsToDisk { + loadFromDisk() + } + } + + func nostrPubkeyHex(forNoiseKey noiseKey: Data) -> String? { + routes[noiseKey]?.nostrPubkeyHex + } + + func nostrPubkeyHex(forPeerID peerID: PeerID) -> String? { + if let noiseKey = peerID.noiseKey { + return routes[noiseKey]?.nostrPubkeyHex + } + let short = peerID.toShort() + for (noiseKey, route) in routes where PeerID(publicKey: noiseKey) == short { + return route.nostrPubkeyHex + } + return nil + } + + func noisePublicKey(forNostrPubkey nostrPubkey: String) -> Data? { + guard let hex = FavoritesPersistenceService.nostrPubkeyHex(from: nostrPubkey) else { return nil } + return noiseKeyByNostrHex[hex] + } + + func nickname(forNoiseKey noiseKey: Data) -> String? { + routes[noiseKey]?.peerNickname + } + + @discardableResult + func upsert( + noisePublicKey: Data, + nostrPubkey: String, + nickname: String, + now: Date = Date() + ) -> Bool { + guard noisePublicKey.count == FavoritesPersistenceService.expectedNoiseKeyLength, + let hex = FavoritesPersistenceService.nostrPubkeyHex(from: nostrPubkey) else { + return false + } + if loadUnavailable { + loadFromDisk() + } + // Prevent hijacking a Nostr pubkey already bound to another Noise key. + if let existingOwner = noiseKeyByNostrHex[hex], existingOwner != noisePublicKey { + return false + } + let cleanNick = nickname.trimmingCharacters(in: .whitespacesAndNewlines) + let resolvedNick = cleanNick.isEmpty ? (routes[noisePublicKey]?.peerNickname ?? "") : cleanNick + let next = Route( + peerNoisePublicKey: noisePublicKey, + nostrPubkeyHex: hex, + peerNickname: resolvedNick, + updatedAt: now + ) + if let existing = routes[noisePublicKey], + existing.nostrPubkeyHex == next.nostrPubkeyHex, + existing.peerNickname == next.peerNickname { + return false + } + routes[noisePublicKey] = next + if routes.count > Self.maxRoutes { + let overflow = routes.count - Self.maxRoutes + let oldestKeys = routes.values + .sorted { $0.updatedAt < $1.updatedAt } + .prefix(overflow) + .map(\.peerNoisePublicKey) + for key in oldestKeys { + routes.removeValue(forKey: key) + } + } + persist() + return true + } + + func removeRoute(forFingerprint fingerprint: String) { + let matching = routes.keys.filter { $0.sha256Fingerprint() == fingerprint } + guard !matching.isEmpty else { return } + for key in matching { + routes.removeValue(forKey: key) + } + persist() + } + + func wipe() { + loadUnavailable = false + routes.removeAll() + cachedKey = nil + _ = keychain.deleteIdentityKey(forKey: Self.encryptionKeychainKey) + fileStore.removeIgnoringErrors() + } + + private func rebuildReverseIndex() { + var index: [String: Data] = [:] + index.reserveCapacity(routes.count) + for (noiseKey, route) in routes { + index[route.nostrPubkeyHex] = noiseKey + } + noiseKeyByNostrHex = index + } + + private func loadOrCreateEncryptionKey() -> SymmetricKey? { + if let cachedKey { return cachedKey } + switch keychain.getIdentityKeyWithResult(forKey: Self.encryptionKeychainKey) { + case .success(let keyData) where keyData.count == 32: + let key = SymmetricKey(data: keyData) + cachedKey = key + return key + case .itemNotFound, .success: + var bytes = Data(count: 32) + let status = bytes.withUnsafeMutableBytes { buf -> OSStatus in + guard let base = buf.baseAddress else { return errSecParam } + return SecRandomCopyBytes(kSecRandomDefault, 32, base) + } + guard status == errSecSuccess, + keychain.saveIdentityKey(bytes, forKey: Self.encryptionKeychainKey) else { + return nil + } + let key = SymmetricKey(data: bytes) + cachedKey = key + return key + case .deviceLocked, .authenticationFailed, .accessDenied, .otherError: + loadUnavailable = true + return nil + } + } + + private func loadFromDisk() { + AppSupportFileStore.drainPendingWrites() + guard let fileURL = fileStore.fileURL, + FileManager.default.fileExists(atPath: fileURL.path) else { + loadUnavailable = false + return + } + let sealedData: Data + do { + sealedData = try Data(contentsOf: fileURL) + } catch { + loadUnavailable = true + return + } + switch keychain.getIdentityKeyWithResult(forKey: Self.encryptionKeychainKey) { + case .success(let keyData) where keyData.count == 32: + let key = SymmetricKey(data: keyData) + cachedKey = key + do { + let box = try ChaChaPoly.SealedBox(combined: sealedData) + let plaintext = try ChaChaPoly.open(box, using: key) + let decoded = try JSONDecoder().decode([Route].self, from: plaintext) + loadUnavailable = false + var loaded = routes + for route in decoded where route.peerNoisePublicKey.count == FavoritesPersistenceService.expectedNoiseKeyLength { + if loaded[route.peerNoisePublicKey] == nil { + loaded[route.peerNoisePublicKey] = route + } + } + routes = loaded + } catch { + loadUnavailable = false + fileStore.removeIgnoringErrors() + } + case .itemNotFound, .success: + loadUnavailable = false + fileStore.removeIgnoringErrors() + case .deviceLocked, .authenticationFailed, .accessDenied, .otherError: + loadUnavailable = true + } + } + + private func persist() { + guard fileStore.fileURL != nil, !loadUnavailable else { return } + if routes.isEmpty { + fileStore.removeIgnoringErrors() + return + } + guard let key = loadOrCreateEncryptionKey() else { return } + do { + let plaintext = try JSONEncoder().encode(Array(routes.values)) + let sealed = try ChaChaPoly.seal(plaintext, using: key).combined + try fileStore.writeRawOffMain(sealed) + } catch { + SecureLogger.error("Failed to persist Nostr peer routes: \(error)", category: .session) + } + } +} diff --git a/bitchat/Services/NostrTransport.swift b/bitchat/Services/NostrTransport.swift index 98cf9797..c79f77cd 100644 --- a/bitchat/Services/NostrTransport.swift +++ b/bitchat/Services/NostrTransport.swift @@ -13,6 +13,10 @@ final class NostrTransport: Transport, @unchecked Sendable { let currentIdentity: @MainActor () throws -> NostrIdentity? let registerPendingGiftWrap: @MainActor (String) -> Void let sendEvent: @MainActor (NostrEvent) -> Void + /// Confirmed relay send (NIP-01 `OK` on at least one connected DM relay). + /// Used by durable outboxes (e.g. hybrid group Nostr deliveries) so sends + /// stay queued until a relay actually accepts the event. + let sendEventImmediately: @MainActor (NostrEvent, @escaping @MainActor (Bool) -> Void) -> Void /// Emits whether a relay that carries private messages is up /// (fail-closed behind Tor). A connected geohash/custom relay alone /// doesn't count: DM sends target the default relay set and would @@ -30,6 +34,7 @@ final class NostrTransport: Transport, @unchecked Sendable { currentIdentity: @escaping @MainActor () throws -> NostrIdentity?, registerPendingGiftWrap: @escaping @MainActor (String) -> Void, sendEvent: @escaping @MainActor (NostrEvent) -> Void, + sendEventImmediately: (@MainActor (NostrEvent, @escaping @MainActor (Bool) -> Void) -> Void)? = nil, scheduleAfter: @escaping @Sendable (TimeInterval, @escaping @Sendable () -> Void) -> Void, relayConnectivity: @escaping @MainActor () -> AnyPublisher, ackPacer: AckPacer? = nil @@ -41,6 +46,10 @@ final class NostrTransport: Transport, @unchecked Sendable { self.currentIdentity = currentIdentity self.registerPendingGiftWrap = registerPendingGiftWrap self.sendEvent = sendEvent + self.sendEventImmediately = sendEventImmediately ?? { event, completion in + sendEvent(event) + completion(true) + } self.relayConnectivity = relayConnectivity // Default pacer drives its throttle through the same injected // scheduler, so tests that step scheduleAfter manually keep @@ -58,6 +67,9 @@ final class NostrTransport: Transport, @unchecked Sendable { currentIdentity: { try idBridge.getCurrentNostrIdentity() }, registerPendingGiftWrap: { NostrRelayManager.registerPendingGiftWrap(id: $0) }, sendEvent: { NostrRelayManager.shared.sendEvent($0) }, + sendEventImmediately: { event, completion in + NostrRelayManager.shared.sendEventImmediately(event, completion: completion) + }, scheduleAfter: { delay, action in DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: action) }, @@ -168,6 +180,10 @@ final class NostrTransport: Transport, @unchecked Sendable { /// valid 32-byte Nostr public key. private var reachablePeers: Set = [] private var reachableShortPeers: Set = [] + /// Additional 1:1 Nostr routes learned from mutual 1:1 DM exchanges or + /// shared encrypted private groups (keyed by both 16-hex short ID and + /// 64-hex Noise key when known -> normalized Bech32 npub). + private var additionalReachableNpubs: [PeerID: String] = [:] /// Peers with any stored valid Nostr public key (including one-sided /// relationships) so `[FAVORITED]`/`[UNFAVORITED]` notifications can be /// resolved synchronously before a removal deletes the relationship. @@ -180,6 +196,9 @@ final class NostrTransport: Transport, @unchecked Sendable { /// higher layers (e.g. MessageRouter outbox flush) always observe the /// updated `canDeliverPromptly` state with no barrier race. var onRelayConnectivityChanged: (@MainActor (Bool) -> Void)? + /// Invoked on the main actor when a 1:1 Nostr DM send settles with NIP-01 + /// `OK` confirmation (`accepted == true`) or failure/offline drop (`false`). + var onPrivateMessageSendResult: (@MainActor (_ messageID: String, _ peerID: PeerID, _ accepted: Bool) -> Void)? private let queue = DispatchQueue(label: "nostr.transport.state", attributes: .concurrent) @MainActor @@ -271,6 +290,26 @@ final class NostrTransport: Transport, @unchecked Sendable { } } + /// Updates supplemental 1:1 Nostr routes learned from mutual 1:1 DM + /// key exchanges and shared encrypted private groups. Values may be `npub1...` + /// or 64-char hex and are normalized before storage. + @MainActor + func updateAdditionalNostrRoutes(_ routes: [PeerID: String]) { + var normalized: [PeerID: String] = [:] + normalized.reserveCapacity(routes.count * 2) + for (peerID, rawKey) in routes { + guard let npub = FavoritesPersistenceService.normalizeNostrNpub(rawKey) else { continue } + normalized[peerID] = npub + let short = peerID.toShort() + if short != peerID { + normalized[short] = npub + } + } + queue.sync(flags: .barrier) { + self.additionalReachableNpubs = normalized + } + } + // MARK: - Transport Protocol Conformance weak var eventDelegate: TransportEventDelegate? @@ -283,7 +322,10 @@ final class NostrTransport: Transport, @unchecked Sendable { // 64-hex noise key (offline favorites), so compare in short form. let short = peerID.toShort() return queue.sync { - reachablePeers.contains(peerID) || reachableShortPeers.contains(short) + reachablePeers.contains(peerID) + || reachableShortPeers.contains(short) + || additionalReachableNpubs[peerID] != nil + || additionalReachableNpubs[short] != nil } } @@ -296,6 +338,10 @@ final class NostrTransport: Transport, @unchecked Sendable { } } + var hasConnectedDMRelay: Bool { + queue.sync { relaysConnected } + } + func canDeliverPromptly(to peerID: PeerID) -> Bool { // A known npub makes a peer "reachable", but with no relay // connection a send only joins the local queue. Answering honestly @@ -317,16 +363,30 @@ final class NostrTransport: Transport, @unchecked Sendable { func sendPrivateMessage(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String) { let generation = dependencies.ackPacer.currentGeneration() Task { @MainActor in - guard dependencies.ackPacer.currentGeneration() == generation else { return } + guard dependencies.ackPacer.currentGeneration() == generation else { + onPrivateMessageSendResult?(messageID, peerID, false) + return + } guard let recipientNpub = resolveRecipientNpub(for: peerID), let recipientHex = npubToHex(recipientNpub), - let senderIdentity = try? dependencies.currentIdentity() else { return } + let senderIdentity = try? dependencies.currentIdentity() else { + onPrivateMessageSendResult?(messageID, peerID, false) + return + } SecureLogger.debug("NostrTransport: preparing PM to \(recipientNpub.prefix(16))… id=\(messageID.prefix(8))…", category: .session) guard let embedded = NostrEmbeddedBitChat.encodePMForNostr(content: content, messageID: messageID, recipientPeerID: peerID, senderPeerID: senderPeerID) else { SecureLogger.error("NostrTransport: failed to embed PM packet", category: .session) + onPrivateMessageSendResult?(messageID, peerID, false) return } - sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: senderIdentity, expectedGeneration: generation) + sendWrappedMessageConfirmed( + content: embedded, + recipientHex: recipientHex, + senderIdentity: senderIdentity, + expectedGeneration: generation + ) { [weak self] accepted in + self?.onPrivateMessageSendResult?(messageID, peerID, accepted) + } } } @@ -393,10 +453,18 @@ final class NostrTransport: Transport, @unchecked Sendable { sendGroupState(type: .groupInvite, payload: payload, to: peerID) } + func sendGroupInvite(_ payload: Data, toPubkeyHex recipientHex: String) { + sendGroupState(type: .groupInvite, payload: payload, toPubkeyHex: recipientHex) + } + func sendGroupKeyUpdate(_ payload: Data, to peerID: PeerID) { sendGroupState(type: .groupKeyUpdate, payload: payload, to: peerID) } + func sendGroupKeyUpdate(_ payload: Data, toPubkeyHex recipientHex: String) { + sendGroupState(type: .groupKeyUpdate, payload: payload, toPubkeyHex: recipientHex) + } + func sendGroupMessage(_ payload: Data, to peerID: PeerID) { let generation = dependencies.ackPacer.currentGeneration() Task { @MainActor in @@ -421,6 +489,49 @@ final class NostrTransport: Transport, @unchecked Sendable { } } + /// Sends an already-sealed group message envelope to `recipientHex` over + /// currently connected default DM relays and invokes `completion(true)` + /// only after at least one relay explicitly accepts the gift wrap via + /// NIP-01 `OK`. Used by `ChatGroupCoordinator`'s durable group outbox so + /// offline/disconnected sends stay queued until confirmed. + func sendGroupMessageConfirmed( + _ payload: Data, + toPubkeyHex recipientHex: String, + completion: @escaping @MainActor (Bool) -> Void + ) { + let generation = dependencies.ackPacer.currentGeneration() + Task { @MainActor in + guard dependencies.ackPacer.currentGeneration() == generation else { + completion(false) + return + } + let normalized = recipientHex.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard normalized.count == 64, + Data(hexString: normalized)?.count == 32, + let senderIdentity = try? dependencies.currentIdentity() else { + completion(false) + return + } + let recipientPeerID = PeerID(nostr_: normalized) + guard let embedded = NostrEmbeddedBitChat.encodeGroupMessageForNostr( + payload: payload, + recipientPeerID: recipientPeerID, + senderPeerID: senderPeerID + ) else { + SecureLogger.error("NostrTransport: failed to embed confirmed group message packet", category: .session) + completion(false) + return + } + sendWrappedMessageConfirmed( + content: embedded, + recipientHex: normalized, + senderIdentity: senderIdentity, + expectedGeneration: generation, + completion: completion + ) + } + } + @MainActor private func sendGroupMessage( _ payload: Data, @@ -450,25 +561,52 @@ final class NostrTransport: Transport, @unchecked Sendable { Task { @MainActor in guard dependencies.ackPacer.currentGeneration() == generation else { return } guard let recipientNpub = resolveRecipientNpub(for: peerID), - let recipientHex = npubToHex(recipientNpub), - let senderIdentity = try? dependencies.currentIdentity() else { return } - guard let embedded = NostrEmbeddedBitChat.encodeGroupStateForNostr( + let recipientHex = npubToHex(recipientNpub) else { return } + sendGroupState(type: type, payload: payload, toPubkeyHex: recipientHex, recipientPeerID: peerID, generation: generation) + } + } + + private func sendGroupState(type: NoisePayloadType, payload: Data, toPubkeyHex recipientHex: String) { + let generation = dependencies.ackPacer.currentGeneration() + Task { @MainActor in + guard dependencies.ackPacer.currentGeneration() == generation else { return } + let normalized = recipientHex.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard normalized.count == 64, Data(hexString: normalized)?.count == 32 else { return } + sendGroupState( type: type, payload: payload, - recipientPeerID: peerID, - senderPeerID: senderPeerID - ) else { - SecureLogger.error("NostrTransport: failed to embed group state packet", category: .session) - return - } - sendWrappedMessage( - content: embedded, - recipientHex: recipientHex, - senderIdentity: senderIdentity, - expectedGeneration: generation + toPubkeyHex: normalized, + recipientPeerID: PeerID(nostr_: normalized), + generation: generation ) } } + + @MainActor + private func sendGroupState( + type: NoisePayloadType, + payload: Data, + toPubkeyHex recipientHex: String, + recipientPeerID: PeerID, + generation: UInt64 + ) { + guard let senderIdentity = try? dependencies.currentIdentity() else { return } + guard let embedded = NostrEmbeddedBitChat.encodeGroupStateForNostr( + type: type, + payload: payload, + recipientPeerID: recipientPeerID, + senderPeerID: senderPeerID + ) else { + SecureLogger.error("NostrTransport: failed to embed group state packet", category: .session) + return + } + sendWrappedMessage( + content: embedded, + recipientHex: recipientHex, + senderIdentity: senderIdentity, + expectedGeneration: generation + ) + } } // MARK: - Geohash Helpers @@ -498,6 +636,39 @@ extension NostrTransport { sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true, expectedGeneration: generation) } } + + /// Sends a geohash DM over currently connected default DM relays and + /// invokes `completion(true)` only after at least one relay confirms `OK`. + func sendPrivateMessageGeohashConfirmed( + content: String, + toRecipientHex recipientHex: String, + from identity: NostrIdentity, + messageID: String, + completion: @escaping @MainActor (Bool) -> Void + ) { + let generation = dependencies.ackPacer.currentGeneration() + Task { @MainActor in + guard dependencies.ackPacer.currentGeneration() == generation, + !recipientHex.isEmpty else { + completion(false) + return + } + SecureLogger.debug("GeoDM: send confirmed PM mid=\(messageID.prefix(8))…", category: .session) + guard let embedded = NostrEmbeddedBitChat.encodePMForNostrNoRecipient(content: content, messageID: messageID) else { + SecureLogger.error("NostrTransport: failed to embed geohash PM packet", category: .session) + completion(false) + return + } + sendWrappedMessageConfirmed( + content: embedded, + recipientHex: recipientHex, + senderIdentity: identity, + registerPending: true, + expectedGeneration: generation, + completion: completion + ) + } + } } // MARK: - Private Helpers @@ -545,6 +716,39 @@ extension NostrTransport { } } + @MainActor + private func sendWrappedMessageConfirmed( + content: String, + recipientHex: String, + senderIdentity: NostrIdentity, + registerPending: Bool = false, + expectedGeneration: UInt64, + completion: @escaping @MainActor (Bool) -> Void + ) { + let dependencies = self.dependencies + Task.detached(priority: .userInitiated) { + guard let event = try? NostrProtocol.createPrivateMessage( + content: content, + recipientPubkey: recipientHex, + senderIdentity: senderIdentity + ) else { + SecureLogger.error("NostrTransport: failed to build confirmed Nostr event", category: .session) + await MainActor.run { completion(false) } + return + } + await MainActor.run { + guard dependencies.ackPacer.currentGeneration() == expectedGeneration else { + completion(false) + return + } + if registerPending { + dependencies.registerPendingGiftWrap(event.id) + } + dependencies.sendEventImmediately(event, completion) + } + } + } + /// Sends a single ack item (invoked by the pacer, one per interval) private func sendAckItem(_ item: QueuedAck, generation: UInt64) { @@ -600,6 +804,9 @@ extension NostrTransport { let npub = fav.peerNostrPublicKey { return npub } - return nil + let short = peerID.toShort() + return queue.sync { + additionalReachableNpubs[peerID] ?? additionalReachableNpubs[short] + } } } diff --git a/bitchat/Services/UnifiedPeerService.swift b/bitchat/Services/UnifiedPeerService.swift index 77a25dee..0ffb836f 100644 --- a/bitchat/Services/UnifiedPeerService.swift +++ b/bitchat/Services/UnifiedPeerService.swift @@ -30,6 +30,8 @@ final class UnifiedPeerService: ObservableObject, TransportPeerEventsDelegate { private let identityManager: SecureIdentityStateManagerProtocol weak var messageRouter: MessageRouter? private let favoritesService = FavoritesPersistenceService.shared + private weak var nostrPeerRouteStore: NostrPeerRouteStore? + private var routeCancellable: AnyCancellable? private var cancellables = Set() // MARK: - Initialization @@ -65,6 +67,17 @@ final class UnifiedPeerService: ObservableObject, TransportPeerEventsDelegate { .store(in: &cancellables) } + func configureNostrPeerRouteStore(_ store: NostrPeerRouteStore) { + routeCancellable?.cancel() + nostrPeerRouteStore = store + routeCancellable = store.$routes + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + self?.updatePeers() + } + updatePeers() + } + // TransportPeerEventsDelegate func didUpdatePeerSnapshots(_: [TransportPeerSnapshot]) { updatePeers() @@ -89,13 +102,14 @@ final class UnifiedPeerService: ObservableObject, TransportPeerEventsDelegate { // "Reachable" means mesh-attached via at least one live link. let hasAnyConnected = meshPeers.contains { $0.isConnected } let favorites = favoritesService.favorites + let contactRoutes = nostrPeerRouteStore?.routes ?? [:] let now = Date() var enrichedPeers: [BitchatPeer] = [] - enrichedPeers.reserveCapacity(meshPeers.count + favorites.count) + enrichedPeers.reserveCapacity(meshPeers.count + favorites.count + contactRoutes.count) var connected: Set = [] var addedPeerIDs: Set = [] - var meshNoiseKeys: Set = [] + var addedNoiseKeys: Set = [] // Phase 1: Add all mesh peers (connected and reachable) for peerInfo in meshPeers { @@ -109,6 +123,7 @@ final class UnifiedPeerService: ObservableObject, TransportPeerEventsDelegate { fingerprint: fingerprint, now: now, favorites: favorites, + contactRoutes: contactRoutes, meshAttached: hasAnyConnected ) @@ -118,38 +133,66 @@ final class UnifiedPeerService: ObservableObject, TransportPeerEventsDelegate { // Update fingerprint cache if let publicKey = peerInfo.noisePublicKey, let fingerprint { - meshNoiseKeys.insert(publicKey) + addedNoiseKeys.insert(publicKey) fingerprintCache[peerID] = fingerprint } } - // Phase 2: Add offline favorites that we actively favorite. - // Mesh rows use the short 16-hex peer ID while favorites are keyed by + // Phase 2: Add offline contacts from friend invites / legacy favorites. + // Mesh rows use the short 16-hex peer ID while contacts are keyed by // the full 32-byte noise key, so dedup must compare noise keys — a // PeerID comparison between the two forms can never match. for (favoriteKey, favorite) in favorites where favorite.isFavorite { - if meshNoiseKeys.contains(favoriteKey) { continue } + if addedNoiseKeys.contains(favoriteKey) { continue } let peerID = PeerID(hexData: favoriteKey) if addedPeerIDs.contains(peerID) { continue } let fingerprint = favoriteKey.sha256Fingerprint() - let peer = buildPeerFromFavorite(favorite: favorite, peerID: peerID, fingerprint: fingerprint) + let peer = buildPeerFromFavorite( + favorite: favorite, + contactRoute: contactRoutes[favoriteKey], + peerID: peerID, + fingerprint: fingerprint + ) enrichedPeers.append(peer) addedPeerIDs.insert(peerID) + addedNoiseKeys.insert(favoriteKey) // Update fingerprint cache fingerprintCache[peerID] = fingerprint } + + // Phase 2b: Add offline contacts learned from mutual 1:1 DM Nostr + // route exchanges (no star/favorite required). + for (noiseKey, route) in contactRoutes { + if addedNoiseKeys.contains(noiseKey) { continue } + let peerID = PeerID(hexData: noiseKey) + if addedPeerIDs.contains(peerID) { continue } + + let fingerprint = noiseKey.sha256Fingerprint() + guard !identityManager.isBlocked(fingerprint: fingerprint), + !identityManager.isNostrBlocked(pubkeyHexLowercased: route.nostrPubkeyHex) else { continue } + let peer = buildPeerFromContactRoute(route: route, peerID: peerID, fingerprint: fingerprint) + enrichedPeers.append(peer) + addedPeerIDs.insert(peerID) + addedNoiseKeys.insert(noiseKey) + fingerprintCache[peerID] = fingerprint + } // Phase 3: Sort peers enrichedPeers.sort { lhs, rhs in - // Connectivity rank: connected > reachable > others - func rank(_ p: BitchatPeer) -> Int { p.isConnected ? 2 : (p.isReachable ? 1 : 0) } + // Connectivity rank: connected > reachable > nostrAvailable > offline + func rank(_ p: BitchatPeer) -> Int { + switch p.connectionState { + case .bluetoothConnected: return 3 + case .meshReachable: return 2 + case .nostrAvailable: return 1 + case .offline: return 0 + } + } let lr = rank(lhs), rr = rank(rhs) if lr != rr { return lr > rr } - // Then favorites inside same rank - if lhs.isFavorite != rhs.isFavorite { return lhs.isFavorite } // Finally alphabetical return lhs.displayName < rhs.displayName } @@ -167,9 +210,9 @@ final class UnifiedPeerService: ObservableObject, TransportPeerEventsDelegate { } } - // Phase 5: Filter out offline non-mutual peers and publish only when state changed. + // Phase 5: Keep live mesh peers and offline contacts with a Nostr route. let filtered = enrichedPeers.filter { p in - p.isConnected || p.isReachable || p.isMutualFavorite + p.isConnected || p.isReachable || p.isMutualFavorite || p.hasDirectNostrRoute } self.peerIndex = newIndex if !Self.peersVisuallyEqual(self.peers, filtered) { @@ -200,6 +243,7 @@ final class UnifiedPeerService: ObservableObject, TransportPeerEventsDelegate { a.isFavorite != b.isFavorite || a.isMutualFavorite != b.isMutualFavorite || a.theyFavoritedUs != b.theyFavoritedUs || + a.hasDirectNostrRoute != b.hasDirectNostrRoute || a.reachableNostrPublicKey != b.reachableNostrPublicKey || a.noisePublicKey != b.noisePublicKey { return false @@ -215,12 +259,13 @@ final class UnifiedPeerService: ObservableObject, TransportPeerEventsDelegate { fingerprint: String?, now: Date, favorites: [Data: FavoritesPersistenceService.FavoriteRelationship], + contactRoutes: [Data: NostrPeerRouteStore.Route], meshAttached: Bool ) -> BitchatPeer { // Determine reachability based on lastSeen and identity trust let isVerified = fingerprint.map { identityManager.isVerified(fingerprint: $0) } ?? false - let isFav = peerInfo.noisePublicKey.flatMap { favorites[$0]?.isFavorite } ?? false - let retention: TimeInterval = (isVerified || isFav) ? TransportConfig.bleReachabilityRetentionVerifiedSeconds : TransportConfig.bleReachabilityRetentionUnverifiedSeconds + let isContact = peerInfo.noisePublicKey.map { favorites[$0]?.isFavorite == true || contactRoutes[$0] != nil } ?? false + let retention: TimeInterval = (isVerified || isContact) ? TransportConfig.bleReachabilityRetentionVerifiedSeconds : TransportConfig.bleReachabilityRetentionUnverifiedSeconds // A peer is reachable if we recently saw them AND we are attached to the mesh let withinRetention = now.timeIntervalSince(peerInfo.lastSeen) <= retention let isReachable = peerInfo.isConnected ? true : (withinRetention && meshAttached) @@ -235,11 +280,15 @@ final class UnifiedPeerService: ObservableObject, TransportPeerEventsDelegate { localPetname: localPetname(forFingerprint: fingerprint) ) - // Check for favorite status - if let noiseKey = peerInfo.noisePublicKey, - let favoriteStatus = favorites[noiseKey] { - peer.favoriteStatus = favoriteStatus - peer.nostrPublicKey = favoriteStatus.peerNostrPublicKey + if let noiseKey = peerInfo.noisePublicKey { + if let favoriteStatus = favorites[noiseKey] { + peer.favoriteStatus = favoriteStatus + peer.nostrPublicKey = favoriteStatus.peerNostrPublicKey + } + if let route = contactRoutes[noiseKey] { + peer.nostrPublicKey = peer.nostrPublicKey ?? route.nostrPubkeyHex + peer.hasDirectNostrRoute = true + } } return peer @@ -247,6 +296,7 @@ final class UnifiedPeerService: ObservableObject, TransportPeerEventsDelegate { private func buildPeerFromFavorite( favorite: FavoritesPersistenceService.FavoriteRelationship, + contactRoute: NostrPeerRouteStore.Route?, peerID: PeerID, fingerprint: String ) -> BitchatPeer { @@ -261,10 +311,30 @@ final class UnifiedPeerService: ObservableObject, TransportPeerEventsDelegate { ) peer.favoriteStatus = favorite - peer.nostrPublicKey = favorite.peerNostrPublicKey + peer.nostrPublicKey = favorite.peerNostrPublicKey ?? contactRoute?.nostrPubkeyHex + peer.hasDirectNostrRoute = contactRoute != nil || (favorite.isMutual && favorite.hasValidNostrPublicKey) return peer } + + private func buildPeerFromContactRoute( + route: NostrPeerRouteStore.Route, + peerID: PeerID, + fingerprint: String + ) -> BitchatPeer { + var peer = BitchatPeer( + peerID: peerID, + noisePublicKey: route.peerNoisePublicKey, + nickname: route.peerNickname, + lastSeen: route.updatedAt, + isConnected: false, + isReachable: false, + localPetname: localPetname(forFingerprint: fingerprint) + ) + peer.nostrPublicKey = route.nostrPubkeyHex + peer.hasDirectNostrRoute = true + return peer + } /// Rebuild peer rows after a social-identity write (local alias, etc.) so /// display names update without waiting for a mesh event. diff --git a/bitchat/Sync/GossipSyncManager.swift b/bitchat/Sync/GossipSyncManager.swift index b25f1d52..bff06883 100644 --- a/bitchat/Sync/GossipSyncManager.swift +++ b/bitchat/Sync/GossipSyncManager.swift @@ -374,10 +374,11 @@ final class GossipSyncManager { let (idHex, entry) = Self.makeEntry(packet) fileTransfers.insert(idHex: idHex, hash64: entry.hash64, packet: packet, capacity: max(1, config.fileTransferCapacity), byteBudget: config.fileTransferByteBudget) case .groupMessage: - // Opaque ciphertext to non-members; carried and served like any - // other broadcast so members get backfill from any relay. + // Opaque ciphertext to non-members; carried, persisted, and served + // like public chat so offline members get BLE backfill on reconnect. let (idHex, entry) = Self.makeEntry(packet) groupMessages.insert(idHex: idHex, hash64: entry.hash64, packet: packet, capacity: max(1, config.groupMessageCapacity), byteBudget: config.groupMessageByteBudget) + archiveDirty = true case .prekeyBundle: // Callers only feed verified bundles here (own bundles at send // time, peers' after signature verification), so gossip never @@ -705,7 +706,11 @@ final class GossipSyncManager { fileTransfers.removeExpired(isFresh: isFresh) } if !groupMessages.packets.isEmpty { + let groupCountBefore = groupMessages.packets.count groupMessages.removeExpired(isFresh: isFresh) + if groupMessages.packets.count != groupCountBefore { + archiveDirty = true + } } if !latestPrekeyBundleByPeer.isEmpty { latestPrekeyBundleByPeer = latestPrekeyBundleByPeer.filter { _, entry in @@ -728,30 +733,52 @@ final class GossipSyncManager { private func restoreArchivedMessages() { guard let archive else { return } let nowMs = UInt64(Date().timeIntervalSince1970 * 1000) - let capacity = max(1, config.seenCapacity) - var kept: [(idHex: String, hash64: UInt64, packet: BitchatPacket)] = [] - var keptBytes = 0 + let publicCapacity = max(1, config.seenCapacity) + let groupCapacity = max(1, config.groupMessageCapacity) + var keptPublic: [(idHex: String, hash64: UInt64, packet: BitchatPacket)] = [] + var keptPublicBytes = 0 + var keptGroup: [(idHex: String, hash64: UInt64, packet: BitchatPacket)] = [] + var keptGroupBytes = 0 var droppedAny = false for data in archive.load().reversed() { - guard kept.count < capacity else { break } guard let packet = BitchatPacket.from(data), - packet.type == MessageType.message.rawValue, isPacketFresh(packet, nowMs: nowMs) else { droppedAny = true continue } - guard keptBytes + packet.payload.count <= config.messageByteBudget else { break } - keptBytes += packet.payload.count - let (idHex, entry) = Self.makeEntry(packet) - kept.append((idHex, entry.hash64, packet)) + if packet.type == MessageType.message.rawValue { + guard keptPublic.count < publicCapacity, + keptPublicBytes + packet.payload.count <= config.messageByteBudget else { + droppedAny = true + continue + } + keptPublicBytes += packet.payload.count + let (idHex, entry) = Self.makeEntry(packet) + keptPublic.append((idHex, entry.hash64, packet)) + } else if packet.type == MessageType.groupMessage.rawValue { + guard config.groupMessageCapacity > 0, + keptGroup.count < groupCapacity, + keptGroupBytes + packet.payload.count <= config.groupMessageByteBudget else { + droppedAny = true + continue + } + keptGroupBytes += packet.payload.count + let (idHex, entry) = Self.makeEntry(packet) + keptGroup.append((idHex, entry.hash64, packet)) + } else { + droppedAny = true + } } - for entry in kept.reversed() { - messages.insert(idHex: entry.idHex, hash64: entry.hash64, packet: entry.packet, capacity: capacity, byteBudget: config.messageByteBudget) + for entry in keptPublic.reversed() { + messages.insert(idHex: entry.idHex, hash64: entry.hash64, packet: entry.packet, capacity: publicCapacity, byteBudget: config.messageByteBudget) } - if !kept.isEmpty { - SecureLogger.debug("Restored \(kept.count) archived public message(s) for gossip sync", category: .sync) + for entry in keptGroup.reversed() { + groupMessages.insert(idHex: entry.idHex, hash64: entry.hash64, packet: entry.packet, capacity: groupCapacity, byteBudget: config.groupMessageByteBudget) } - if !kept.isEmpty || droppedAny { + if !keptPublic.isEmpty || !keptGroup.isEmpty { + SecureLogger.debug("Restored \(keptPublic.count) public and \(keptGroup.count) group message(s) for gossip sync", category: .sync) + } + if !keptPublic.isEmpty || !keptGroup.isEmpty || droppedAny { archiveDirty = true } } @@ -760,7 +787,9 @@ final class GossipSyncManager { guard archiveDirty, let archive else { return } archiveDirty = false let nowMs = UInt64(Date().timeIntervalSince1970 * 1000) - let packets = messages.allPackets { isPacketFresh($0, nowMs: nowMs) } + let publicPackets = messages.allPackets { isPacketFresh($0, nowMs: nowMs) } + let groupPackets = groupMessages.allPackets { isPacketFresh($0, nowMs: nowMs) } + let packets = (publicPackets + groupPackets) .compactMap { $0.toBinaryData(padding: false) } archive.save(packets) } @@ -880,11 +909,15 @@ final class GossipSyncManager { queue.async { [weak self] in guard let self else { return } self.messages.remove { _ in true } - self.archiveDirty = true - // Persist now rather than waiting for maintenance: a relaunch in - // the gap would restore the purged messages from disk. - self.archiveDirty = false - self.archive?.wipe() + if self.groupMessages.packets.isEmpty { + // Persist now rather than waiting for maintenance: a relaunch in + // the gap would restore the purged messages from disk. + self.archiveDirty = false + self.archive?.wipe() + } else { + self.archiveDirty = true + self.persistArchiveIfDirty() + } } } @@ -904,7 +937,11 @@ final class GossipSyncManager { } fragments.remove { PeerID(hexData: $0.senderID) == peerID } fileTransfers.remove { PeerID(hexData: $0.senderID) == peerID } + let groupCountBefore = groupMessages.packets.count groupMessages.remove { PeerID(hexData: $0.senderID) == peerID } + if groupMessages.packets.count != groupCountBefore { + archiveDirty = true + } } } diff --git a/bitchat/ViewModels/ChatGroupCoordinator.swift b/bitchat/ViewModels/ChatGroupCoordinator.swift index d4c10b48..f81be645 100644 --- a/bitchat/ViewModels/ChatGroupCoordinator.swift +++ b/bitchat/ViewModels/ChatGroupCoordinator.swift @@ -17,6 +17,7 @@ protocol ChatGroupContext: AnyObject { var selectedPrivateChatPeer: PeerID? { get } var isAppActive: Bool { get } var groupStore: GroupStore { get } + var groupOutboxStore: GroupOutboxStore? { get } /// Fingerprint of our own Noise static identity key. func myNoiseFingerprint() -> String @@ -31,6 +32,8 @@ protocol ChatGroupContext: AnyObject { func peerNickname(for peerID: PeerID) -> String? /// The peer's Noise fingerprint from the live session/registry. func meshFingerprint(for peerID: PeerID) -> String? + /// Full 64-hex Nostr sender pubkey recorded for `peerID` (for inbound Nostr key updates). + func senderNostrPubkeyHex(for peerID: PeerID) -> String? /// The peer's persisted crypto identity (fingerprint + signing key), if /// the identity store has a signature-verified announce for them. func cryptoIdentity(for peerID: PeerID) -> (fingerprint: String, signingKey: Data)? @@ -46,17 +49,26 @@ protocol ChatGroupContext: AnyObject { func isFingerprintBlocked(_ fingerprint: String) -> Bool // MARK: Transport + func isNostrDMRelayConnected() -> Bool func sendGroupInvitePayload(_ payload: Data, to peerID: PeerID) func sendGroupKeyUpdatePayload(_ payload: Data, to peerID: PeerID) func broadcastGroupMessagePayload(_ payload: Data) func sendGroupInviteViaNostr(_ payload: Data, to peerID: PeerID) + func sendGroupInviteViaNostr(_ payload: Data, toPubkeyHex pubkeyHex: String) func sendGroupKeyUpdateViaNostr(_ payload: Data, to peerID: PeerID) + func sendGroupKeyUpdateViaNostr(_ payload: Data, toPubkeyHex pubkeyHex: String) func sendGroupMessageViaNostr(_ payload: Data, to peerID: PeerID) func sendGroupMessageViaNostr(_ payload: Data, toPubkeyHex pubkeyHex: String) + func sendGroupMessageViaNostrConfirmed( + _ payload: Data, + toPubkeyHex pubkeyHex: String, + completion: @escaping @MainActor (Bool) -> Void + ) // MARK: Conversation intents (group chats are direct-keyed) @discardableResult func appendPrivateMessage(_ message: BitchatMessage, to peerID: PeerID) -> Bool + func setPrivateMessageDeliveryStatus(_ status: DeliveryStatus, forMessageID messageID: String) func markPrivateChatUnread(_ peerID: PeerID) func removePrivateChat(_ peerID: PeerID) func startPrivateChat(with peerID: PeerID) @@ -67,13 +79,27 @@ protocol ChatGroupContext: AnyObject { } extension ChatGroupContext { + var groupOutboxStore: GroupOutboxStore? { nil } + func senderNostrPubkeyHex(for peerID: PeerID) -> String? { nil } func nostrReachablePeerID(forFingerprint fingerprint: String) -> PeerID? { nil } func myNostrPubkeyHex() -> String? { nil } func nostrPubkeyHex(forFingerprint fingerprint: String) -> String? { nil } + func isNostrDMRelayConnected() -> Bool { true } func sendGroupInviteViaNostr(_ payload: Data, to peerID: PeerID) {} + func sendGroupInviteViaNostr(_ payload: Data, toPubkeyHex pubkeyHex: String) {} func sendGroupKeyUpdateViaNostr(_ payload: Data, to peerID: PeerID) {} + func sendGroupKeyUpdateViaNostr(_ payload: Data, toPubkeyHex pubkeyHex: String) {} func sendGroupMessageViaNostr(_ payload: Data, to peerID: PeerID) {} func sendGroupMessageViaNostr(_ payload: Data, toPubkeyHex pubkeyHex: String) {} + func sendGroupMessageViaNostrConfirmed( + _ payload: Data, + toPubkeyHex pubkeyHex: String, + completion: @escaping @MainActor (Bool) -> Void + ) { + sendGroupMessageViaNostr(payload, toPubkeyHex: pubkeyHex) + completion(true) + } + func setPrivateMessageDeliveryStatus(_ status: DeliveryStatus, forMessageID messageID: String) {} } extension ChatViewModel: ChatGroupContext { @@ -147,13 +173,39 @@ extension ChatViewModel: ChatGroupContext { if fingerprint == myNoiseFingerprint() { return myNostrPubkeyHex() } + // Prefer mutual favorites, then fall back to any stored favorite with + // a validated Nostr pubkey (e.g. one-sided favorite / friend invite). + var fallbackHex: String? for (noiseKey, rel) in FavoritesPersistenceService.shared.favorites { - guard rel.isMutual, - noiseKey.sha256Fingerprint() == fingerprint, + guard noiseKey.sha256Fingerprint() == fingerprint, let hex = FavoritesPersistenceService.nostrPubkeyHex(from: rel.peerNostrPublicKey) else { continue } - return hex + if rel.isMutual { + return hex + } + fallbackHex = fallbackHex ?? hex } - return nil + return fallbackHex + } + + /// Resolves the best Nostr x-only pubkey (64-hex) for a group member: + /// local favorites first, then creator-distributed or message-learned + /// `member.nostrPubkeyHex`. Shared by sending and transport-status UI so + /// both always agree on whether a member is Nostr-routable. + func resolvedNostrPubkeyHex(for member: GroupMember) -> String? { + if let known = nostrPubkeyHex(forFingerprint: member.fingerprint) { + return known + } + return FavoritesPersistenceService.nostrPubkeyHex(from: member.nostrPubkeyHex) + } + + func senderNostrPubkeyHex(for peerID: PeerID) -> String? { + fullNostrHex(forSenderPeerID: peerID) + } + + func isNostrDMRelayConnected() -> Bool { + networkActivationAllowed + && NetworkActivationService.shared.activationAllowed + && (messageRouter.nostrTransport?.hasConnectedDMRelay ?? NostrRelayManager.shared.isDMRelayConnected) } func isFingerprintBlocked(_ fingerprint: String) -> Bool { @@ -179,10 +231,18 @@ extension ChatViewModel: ChatGroupContext { messageRouter.nostrTransport?.sendGroupInvite(payload, to: peerID) } + func sendGroupInviteViaNostr(_ payload: Data, toPubkeyHex pubkeyHex: String) { + messageRouter.nostrTransport?.sendGroupInvite(payload, toPubkeyHex: pubkeyHex) + } + func sendGroupKeyUpdateViaNostr(_ payload: Data, to peerID: PeerID) { messageRouter.nostrTransport?.sendGroupKeyUpdate(payload, to: peerID) } + func sendGroupKeyUpdateViaNostr(_ payload: Data, toPubkeyHex pubkeyHex: String) { + messageRouter.nostrTransport?.sendGroupKeyUpdate(payload, toPubkeyHex: pubkeyHex) + } + func sendGroupMessageViaNostr(_ payload: Data, to peerID: PeerID) { messageRouter.nostrTransport?.sendGroupMessage(payload, to: peerID) } @@ -191,6 +251,22 @@ extension ChatViewModel: ChatGroupContext { messageRouter.nostrTransport?.sendGroupMessage(payload, toPubkeyHex: pubkeyHex) } + func sendGroupMessageViaNostrConfirmed( + _ payload: Data, + toPubkeyHex pubkeyHex: String, + completion: @escaping @MainActor (Bool) -> Void + ) { + guard let nostrTransport = messageRouter.nostrTransport else { + completion(false) + return + } + nostrTransport.sendGroupMessageConfirmed(payload, toPubkeyHex: pubkeyHex, completion: completion) + } + + func setPrivateMessageDeliveryStatus(_ status: DeliveryStatus, forMessageID messageID: String) { + _ = conversations.setDeliveryStatus(status, forMessageID: messageID) + } + // MARK: CommandContextProvider group commands (parsed by CommandProcessor) func groupCreate(named name: String) -> CommandResult { @@ -215,17 +291,31 @@ extension ChatViewModel: ChatGroupContext { } /// Owns the private-groups feature: creating groups, creator-managed invites -/// and key rotation over Noise, and sealing/opening group message broadcasts. -/// Delivery is fire-and-flood like public chat — no per-member acks in v1 — -/// with gossip-sync backfill as the only offline catch-up. +/// and key rotation over Noise/Nostr, sealing/opening group message broadcasts, +/// and durable Nostr outbox delivery with automatic Nostr routing discovery. @MainActor final class ChatGroupCoordinator { private unowned let context: any ChatGroupContext + private var inFlightDeliveries: Set = [] + private var retryTask: Task? + private var wipeGeneration: UInt64 = 0 init(context: any ChatGroupContext) { self.context = context } + deinit { + retryTask?.cancel() + } + + func resetForPanic() { + wipeGeneration &+= 1 + retryTask?.cancel() + retryTask = nil + inFlightDeliveries.removeAll() + context.groupOutboxStore?.wipe() + } + // MARK: - Commands func createGroup(named rawName: String) -> CommandResult { @@ -368,7 +458,7 @@ final class ChatGroupCoordinator { return .error(message: String(localized: "system.group.cannot_remove_creator", comment: "Error when the creator tries to remove themselves")) } - let remaining = group.members.filter { $0.fingerprint != member.fingerprint } + let remaining = enrichedRoutingMembers(group.members.filter { $0.fingerprint != member.fingerprint }) guard let (rotated, newKey) = context.groupStore.rotateKey(groupID: group.groupID, members: remaining), let payload = signedStatePayload(for: rotated, key: newKey) else { return .error(message: String(localized: "system.group.rotate_failed", comment: "Error when rotating the group key fails")) @@ -392,6 +482,7 @@ final class ChatGroupCoordinator { // resurrect the conversation we're about to remove. context.endPrivateChat() context.removePrivateChat(group.peerID) + context.groupOutboxStore?.removeGroup(withID: group.groupID) context.groupStore.removeGroup(withID: group.groupID) return .success(message: String( format: String(localized: "system.group.left", comment: "System message after leaving a group; placeholder is the group name"), @@ -439,6 +530,7 @@ final class ChatGroupCoordinator { messageID: messageID, senderNickname: context.nickname, senderSigningKey: context.mySigningPublicKey(), + senderNostrPubkeyHex: context.myNostrPubkeyHex(), timestampMs: UInt64(timestamp.timeIntervalSince1970 * 1000), groupID: group.groupID, epoch: group.epoch, @@ -454,6 +546,16 @@ final class ChatGroupCoordinator { return } + let myFingerprint = context.myNoiseFingerprint() + let otherMembers = group.members.filter { $0.fingerprint != myFingerprint } + let anyMeshConnected = otherMembers.contains { context.connectedPeerID(forFingerprint: $0.fingerprint) != nil } + let anyNostrRoute = otherMembers.contains { resolvedNostrPubkeyHex(for: $0) != nil } + let hasDurableOutbox = context.groupOutboxStore != nil + // When nobody is on BLE mesh right now and we have a Nostr route, start + // in `.sending` so the user sees queued progress until a DM relay + // confirms NIP-01 `OK` (either immediately or on reconnect). + let initialStatus: DeliveryStatus = (hasDurableOutbox && !anyMeshConnected && anyNostrRoute) ? .sending : .sent + let message = BitchatMessage( id: messageID, sender: context.nickname, @@ -465,21 +567,143 @@ final class ChatGroupCoordinator { recipientNickname: group.name, senderPeerID: context.myPeerID, mentions: nil, - deliveryStatus: .sent + deliveryStatus: initialStatus ) context.appendPrivateMessage(message, to: groupPeerID) context.broadcastGroupMessagePayload(payload) - // Hybrid delivery: also fan out over Nostr to any roster members who - // are reachable via local favorites OR via creator-distributed Nostr - // routing keys in the group roster (deduped by messageID if they also get BLE). - let myFingerprint = context.myNoiseFingerprint() - for member in group.members where member.fingerprint != myFingerprint { - if let nostrPeerID = context.nostrReachablePeerID(forFingerprint: member.fingerprint) { - context.sendGroupMessageViaNostr(payload, to: nostrPeerID) - } else if let pubkeyHex = member.nostrPubkeyHex, !pubkeyHex.isEmpty { - context.sendGroupMessageViaNostr(payload, toPubkeyHex: pubkeyHex) + // Hybrid delivery: enqueue for every other member in the durable Nostr + // outbox (confirmed via NIP-01 OK, flushed immediately when online and + // retried automatically on relay reconnect or when a member's Nostr + // pubkey is learned). Fall back to direct send when no outbox store is + // wired (e.g. lightweight unit tests). + if let outboxStore = context.groupOutboxStore { + let pendingFingerprints = Set(otherMembers.map(\.fingerprint)) + if !pendingFingerprints.isEmpty { + let evicted = outboxStore.enqueue(GroupOutboxStore.Entry( + groupID: group.groupID, + messageID: messageID, + payload: payload, + pendingMemberFingerprints: pendingFingerprints, + hadMeshDeliveryAtSend: anyMeshConnected, + createdAt: timestamp + )) + for dropped in evicted where !dropped.hadMeshDeliveryAtSend && !dropped.hadAnyNostrConfirmation { + markGroupMessageFailed(dropped.messageID) + } + flushPendingNostrDeliveries(now: timestamp) } + } else { + for member in otherMembers { + if let nostrPeerID = context.nostrReachablePeerID(forFingerprint: member.fingerprint) { + context.sendGroupMessageViaNostr(payload, to: nostrPeerID) + } else if let pubkeyHex = resolvedNostrPubkeyHex(for: member) { + context.sendGroupMessageViaNostr(payload, toPubkeyHex: pubkeyHex) + } + } + } + } + + /// Flushes any queued group Nostr deliveries over currently connected DM + /// relays. Safe to call on launch, relay reconnect, foreground resume, + /// periodic sweep, or after learning a member's Nostr pubkey. + func flushPendingNostrDeliveries(now: Date = Date()) { + guard let outboxStore = context.groupOutboxStore else { return } + + let myFingerprint = context.myNoiseFingerprint() + var validMembersByGroupID: [Data: Set] = [:] + for group in context.groupStore.groups { + validMembersByGroupID[group.groupID] = Set( + group.members.filter { $0.fingerprint != myFingerprint }.map(\.fingerprint) + ) + } + let expiredFailures = outboxStore.prune(now: now, validMembersByGroupID: validMembersByGroupID) + for dropped in expiredFailures { + markGroupMessageFailed(dropped.messageID) + } + + guard context.isNostrDMRelayConnected() else { return } + + let generation = wipeGeneration + let snapshot = outboxStore.entries + for entry in snapshot { + guard let group = context.groupStore.group(withID: entry.groupID) else { continue } + for memberFingerprint in entry.pendingMemberFingerprints { + guard let member = group.members.first(where: { $0.fingerprint == memberFingerprint }), + let pubkeyHex = resolvedNostrPubkeyHex(for: member) else { + continue + } + let deliveryKey = "\(entry.groupID.hexEncodedString()):\(entry.messageID):\(memberFingerprint)" + guard inFlightDeliveries.insert(deliveryKey).inserted else { continue } + + context.sendGroupMessageViaNostrConfirmed(entry.payload, toPubkeyHex: pubkeyHex) { [weak self] succeeded in + guard let self, self.wipeGeneration == generation else { return } + self.inFlightDeliveries.remove(deliveryKey) + guard let outboxStore = self.context.groupOutboxStore else { return } + if succeeded { + let (_, shouldMarkSent) = outboxStore.markDelivered( + messageID: entry.messageID, + groupID: entry.groupID, + memberFingerprint: memberFingerprint + ) + if shouldMarkSent { + self.context.setPrivateMessageDeliveryStatus(.sent, forMessageID: entry.messageID) + } + } else if self.context.isNostrDMRelayConnected() { + // Only burn retry budget when a DM relay was still up + // (e.g. relay rejected/timed out); offline drops keep + // the entry intact for reconnect. + if let dropped = outboxStore.recordRelayAttemptFailure( + messageID: entry.messageID, + groupID: entry.groupID + ) { + if !dropped.hadMeshDeliveryAtSend && !dropped.hadAnyNostrConfirmation { + self.markGroupMessageFailed(dropped.messageID) + } + } else { + self.scheduleOutboxRetryIfNeeded() + } + } + } + } + } + } + + private func scheduleOutboxRetryIfNeeded(delaySeconds: TimeInterval = 15) { + guard retryTask == nil, + let outboxStore = context.groupOutboxStore, + !outboxStore.entries.isEmpty else { return } + let generation = wipeGeneration + retryTask = Task { @MainActor [weak self] in + try? await Task.sleep(nanoseconds: UInt64(delaySeconds * 1_000_000_000)) + guard let self, !Task.isCancelled, self.wipeGeneration == generation else { return } + self.retryTask = nil + self.flushPendingNostrDeliveries() + } + } + + /// Refreshes all stored group rosters with any Nostr pubkeys now known via + /// local favorites or our own Nostr identity, then flushes any queued + /// group deliveries that just became Nostr-routable. + func refreshMemberNostrRoutingFromFavorites() { + var anyUpdated = false + for group in context.groupStore.groups { + var updates: [String: String] = [:] + for member in group.members { + if let hex = context.nostrPubkeyHex(forFingerprint: member.fingerprint) { + updates[member.fingerprint] = hex + } + } + if context.groupStore.updateMemberNostrPubkeys( + groupID: group.groupID, + updates: updates, + overwriteExisting: true + ) { + anyUpdated = true + } + } + if anyUpdated { + flushPendingNostrDeliveries() } } @@ -576,7 +800,7 @@ final class ChatGroupCoordinator { guard member.fingerprint != group.creatorFingerprint else { return .error(message: String(localized: "system.group.cannot_remove_creator", comment: "Error when the creator tries to remove themselves")) } - let remaining = group.members.filter { $0.fingerprint != member.fingerprint } + let remaining = enrichedRoutingMembers(group.members.filter { $0.fingerprint != member.fingerprint }) guard let (rotated, newKey) = context.groupStore.rotateKey(groupID: group.groupID, members: remaining), let payload = signedStatePayload(for: rotated, key: newKey) else { return .error(message: String(localized: "system.group.rotate_failed", comment: "Error when rotating the group key fails")) @@ -598,6 +822,7 @@ final class ChatGroupCoordinator { context.endPrivateChat() } context.removePrivateChat(group.peerID) + context.groupOutboxStore?.removeGroup(withID: group.groupID) context.groupStore.removeGroup(withID: group.groupID) return .success(message: String( format: String(localized: "system.group.left", comment: "System message after leaving a group; placeholder is the group name"), @@ -643,6 +868,18 @@ final class ChatGroupCoordinator { return } + // Learn the sender's Nostr pubkey from inside the encrypted group + // envelope so BLE-formed groups seamlessly gain Nostr delivery without + // requiring manual 1:1 mutual favoriting. + if let learnedNostrHex = plaintext.senderNostrPubkeyHex, + context.groupStore.updateMemberNostrPubkeys( + groupID: group.groupID, + updates: [member.fingerprint: learnedNostrHex], + overwriteExisting: false + ) { + flushPendingNostrDeliveries() + } + let groupPeerID = group.peerID // Trust the authenticated inner timestamp (clamped so a future-dated // message cannot pin itself to the bottom of the timeline). @@ -705,15 +942,37 @@ private extension ChatGroupCoordinator { return trimmed.hasPrefix("@") ? String(trimmed.dropFirst()) : trimmed } - func enrichedRoutingMembers(_ members: [GroupMember]) -> [GroupMember] { + func resolvedNostrPubkeyHex(for member: GroupMember) -> String? { + if let known = context.nostrPubkeyHex(forFingerprint: member.fingerprint) { + return known + } + return FavoritesPersistenceService.nostrPubkeyHex(from: member.nostrPubkeyHex) + } + + func markGroupMessageFailed(_ messageID: String) { + context.setPrivateMessageDeliveryStatus( + .failed(reason: String(localized: "content.delivery.reason.not_delivered", comment: "Failure reason shown when the router gave up delivering a message")), + forMessageID: messageID + ) + } + + func enrichedRoutingMembers(_ members: [GroupMember], preserving existing: [GroupMember] = []) -> [GroupMember] { let myFingerprint = context.myNoiseFingerprint() + let existingPubkeys = Dictionary( + existing.compactMap { member -> (String, String)? in + guard let hex = FavoritesPersistenceService.nostrPubkeyHex(from: member.nostrPubkeyHex) else { return nil } + return (member.fingerprint, hex) + }, + uniquingKeysWith: { first, _ in first } + ) return members.map { member in - guard member.nostrPubkeyHex == nil else { return member } var copy = member if member.fingerprint == myFingerprint { - copy.nostrPubkeyHex = context.myNostrPubkeyHex() - } else { - copy.nostrPubkeyHex = context.nostrPubkeyHex(forFingerprint: member.fingerprint) + copy.nostrPubkeyHex = context.myNostrPubkeyHex() ?? copy.nostrPubkeyHex ?? existingPubkeys[member.fingerprint] + } else if let known = context.nostrPubkeyHex(forFingerprint: member.fingerprint) { + copy.nostrPubkeyHex = known + } else if copy.nostrPubkeyHex == nil, let preserved = existingPubkeys[member.fingerprint] { + copy.nostrPubkeyHex = preserved } return copy } @@ -752,6 +1011,13 @@ private extension ChatGroupCoordinator { case .keyUpdate: context.sendGroupKeyUpdateViaNostr(payload, to: nostrPeerID) } + } else if let pubkeyHex = resolvedNostrPubkeyHex(for: member) { + switch type { + case .invite: + context.sendGroupInviteViaNostr(payload, toPubkeyHex: pubkeyHex) + case .keyUpdate: + context.sendGroupKeyUpdateViaNostr(payload, toPubkeyHex: pubkeyHex) + } } } } @@ -764,6 +1030,8 @@ private extension ChatGroupCoordinator { } if let nostrPeerID = context.nostrReachablePeerID(forFingerprint: removed.fingerprint) { context.sendGroupKeyUpdateViaNostr(payload, to: nostrPeerID) + } else if let pubkeyHex = resolvedNostrPubkeyHex(for: removed) { + context.sendGroupKeyUpdateViaNostr(payload, toPubkeyHex: pubkeyHex) } } @@ -772,10 +1040,27 @@ private extension ChatGroupCoordinator { SecureLogger.warning("Malformed group state payload from \(peerID.id.prefix(8))…", category: .security) return } - // The Noise session already authenticated `peerID`; require that the + let existing = context.groupStore.group(withID: state.groupID) + // The Noise/Nostr session authenticated `peerID`; require that the // authenticated peer IS the creator whose key signed the state, so a - // member can't re-invite or rotate on the creator's behalf. - guard let senderFingerprint = context.meshFingerprint(for: peerID), + // member can't re-invite or rotate on the creator's behalf. For an + // existing group receiving a Nostr key update from a non-favorite + // creator, match the full Nostr sender pubkey against the pinned + // creator's `nostrPubkeyHex` (the creator's Ed25519 signature and + // stored-creator pin are still enforced below). + let senderFingerprint: String? = { + if let direct = context.meshFingerprint(for: peerID) { + return direct + } + if let existing, + let senderNostrHex = context.senderNostrPubkeyHex(for: peerID)?.lowercased(), + let creatorNostrHex = existing.creator?.nostrPubkeyHex?.lowercased(), + senderNostrHex == creatorNostrHex { + return existing.creatorFingerprint + } + return nil + }() + guard let senderFingerprint, senderFingerprint == state.creatorFingerprint else { SecureLogger.warning("Dropping group state from non-creator \(peerID.id.prefix(8))…", category: .security) return @@ -797,7 +1082,6 @@ private extension ChatGroupCoordinator { } let myFingerprint = context.myNoiseFingerprint() - let existing = context.groupStore.group(withID: state.groupID) if let existing { // A group keeps the creator it was created with. The checks above @@ -830,6 +1114,7 @@ private extension ChatGroupCoordinator { context.endPrivateChat() } context.removePrivateChat(existing.peerID) + context.groupOutboxStore?.removeGroup(withID: existing.groupID) context.groupStore.removeGroup(withID: existing.groupID) context.addSystemMessage(String( format: String(localized: "system.group.removed_from", comment: "System message when removed from a group; placeholder is the group name"), @@ -843,6 +1128,10 @@ private extension ChatGroupCoordinator { let isNewMembership = existing == nil var sanitizedGroup = state.asGroup sanitizedGroup.name = trimmedName + sanitizedGroup.members = enrichedRoutingMembers( + sanitizedGroup.members, + preserving: existing?.members ?? [] + ) guard context.groupStore.upsert(sanitizedGroup, key: state.key) else { SecureLogger.error("Failed to store group state for \(trimmedName)", category: .session) return diff --git a/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift b/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift index ec342bd9..72272a6d 100644 --- a/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift +++ b/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift @@ -77,10 +77,17 @@ protocol ChatPrivateConversationContext: ChatIdentityContext, ChatDirectMessageS func isNostrBlocked(pubkeyHexLowercased: String) -> Bool func displayNameForNostrPubkey(_ pubkeyHex: String) -> String func deriveNostrIdentity(forGeohash geohash: String) throws -> NostrIdentity + func currentNostrIdentity() -> NostrIdentity? + /// Originating geohash bound to a GeoDM conversation, if recorded. + func geohashForGeoDM(_ peerID: PeerID) -> String? /// Whether at least one default (DM-capable) Nostr relay is connected right /// now. Prevents offline mutual-favorite DMs from falsely showing `.sent` /// while they are actually queued in the outbox waiting for internet. var isNostrRelayConnected: Bool { get } + /// True when the transport stack confirms Nostr 1:1 DM sends asynchronously + /// via NIP-01 `OK` (`MessageRouter.onMessageSent`) instead of stamping + /// `.sent` synchronously before any relay accepts the event. + var usesConfirmedNostrPrivateSend: Bool { get } // MARK: Routing & acknowledgements func routePrivateMessage(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String) @@ -93,11 +100,25 @@ protocol ChatPrivateConversationContext: ChatIdentityContext, ChatDirectMessageS func routeReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) -> Bool func sendMeshReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) func sendGeohashPrivateMessage(_ content: String, toRecipientHex recipientHex: String, from identity: NostrIdentity, messageID: String) + func sendGeohashPrivateMessageConfirmed( + _ content: String, + toRecipientHex recipientHex: String, + from identity: NostrIdentity, + messageID: String, + completion: @escaping @MainActor (Bool) -> Void + ) func sendGeohashDeliveryAck(for messageID: String, toRecipientHex recipientHex: String, from identity: NostrIdentity) func sendGeohashReadReceipt(_ messageID: String, toRecipientHex recipientHex: String, from identity: NostrIdentity) + /// Sends a signed Nostr route binding payload over the Noise session. + func sendNostrRouteExchangePayload(_ payload: Data, to peerID: PeerID) + /// Persists a verified mutual-DM Nostr route and refreshes transport routing. + func storeNostrPeerRoute(noiseKey: Data, nostrPubkey: String, nickname: String) + /// Known nickname from a learned mutual-DM route or shared group, if any. + func hybridSenderNickname(for peerID: PeerID, noiseKey: Data?) -> String? + /// True when `peerID` has any 1:1 Nostr route (favorite, mutual DM, or shared group). + func hasDirectNostrRoute(for peerID: PeerID) -> Bool // MARK: System messages - func addMeshOnlySystemMessage(_ content: String) /// Appends a local-only system line into a specific private thread — /// errors about a DM belong in that DM, not on the active timeline. func addLocalPrivateSystemMessage(_ content: String, to peerID: PeerID) @@ -113,6 +134,8 @@ protocol ChatPrivateConversationContext: ChatIdentityContext, ChatDirectMessageS func favoriteNoiseKey(forNostrPubkey nostrPubkey: String) -> Data? /// Our own 32-byte Noise static public key (used to reject self-favorites). func myNoisePublicKey() -> Data + /// Our own 32-byte Ed25519 signing public key (used to sign mutual-DM Nostr route bindings). + func mySigningPublicKey() -> Data /// Persists that the peer favorited/unfavorited us (favorites store write). func updatePeerFavoritedUs(noiseKey: Data, favorited: Bool, nickname: String, nostrPublicKey: String?) /// Posts the incoming-private-message local notification. @@ -122,10 +145,28 @@ protocol ChatPrivateConversationContext: ChatIdentityContext, ChatDirectMessageS extension ChatPrivateConversationContext { var sendReadReceiptsEnabled: Bool { true } var isNostrRelayConnected: Bool { true } + var usesConfirmedNostrPrivateSend: Bool { false } + func currentNostrIdentity() -> NostrIdentity? { nil } + func geohashForGeoDM(_ peerID: PeerID) -> String? { nil } func reconcileDisappearingTimer(from sourcePeerID: PeerID, to destinationPeerID: PeerID) {} func registerVerifiedFriendInviteIdentity(_ invite: FriendInvite) {} func favoriteNoiseKey(forNostrPubkey nostrPubkey: String) -> Data? { nil } func myNoisePublicKey() -> Data { Data() } + func mySigningPublicKey() -> Data { Data() } + func sendNostrRouteExchangePayload(_ payload: Data, to peerID: PeerID) {} + func storeNostrPeerRoute(noiseKey: Data, nostrPubkey: String, nickname: String) {} + func hybridSenderNickname(for peerID: PeerID, noiseKey: Data?) -> String? { nil } + func hasDirectNostrRoute(for peerID: PeerID) -> Bool { false } + func sendGeohashPrivateMessageConfirmed( + _ content: String, + toRecipientHex recipientHex: String, + from identity: NostrIdentity, + messageID: String, + completion: @escaping @MainActor (Bool) -> Void + ) { + sendGeohashPrivateMessage(content, toRecipientHex: recipientHex, from: identity, messageID: messageID) + completion(true) + } @discardableResult func routeReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) -> Bool { sendMeshReadReceipt(receipt, to: peerID) @@ -201,7 +242,58 @@ extension ChatViewModel: ChatPrivateConversationContext { } var isNostrRelayConnected: Bool { - NostrRelayManager.shared.isDMRelayConnected + isNostrDMRelayConnected() + } + + var usesConfirmedNostrPrivateSend: Bool { true } + + func sendGeohashPrivateMessageConfirmed( + _ content: String, + toRecipientHex recipientHex: String, + from identity: NostrIdentity, + messageID: String, + completion: @escaping @MainActor (Bool) -> Void + ) { + makeGeohashNostrTransport().sendPrivateMessageGeohashConfirmed( + content: content, + toRecipientHex: recipientHex, + from: identity, + messageID: messageID, + completion: completion + ) + } + + func sendNostrRouteExchangePayload(_ payload: Data, to peerID: PeerID) { + (meshService as? MeshGroupMessaging)?.sendNostrRouteExchange(payload, to: peerID) + } + + func storeNostrPeerRoute(noiseKey: Data, nostrPubkey: String, nickname: String) { + if nostrPeerRouteStore.upsert(noisePublicKey: noiseKey, nostrPubkey: nostrPubkey, nickname: nickname) { + syncDirectNostrRoutes() + messageRouter.flushOutbox(for: PeerID(hexData: noiseKey)) + messageRouter.flushOutbox(for: PeerID(publicKey: noiseKey)) + } + } + + func hybridSenderNickname(for peerID: PeerID, noiseKey: Data?) -> String? { + if let noiseKey, + let routeNick = nostrPeerRouteStore.nickname(forNoiseKey: noiseKey), + !routeNick.isEmpty { + return routeNick + } + if let meshNick = peerNickname(for: peerID), !meshNick.isEmpty { + return meshNick + } + let short = peerID.toShort() + let myFP = myNoiseFingerprint() + for group in groupStore.groups { + if let member = group.members.first(where: { + $0.fingerprint != myFP && String($0.fingerprint.prefix(16)) == short.id + }), !member.nickname.isEmpty { + return member.nickname + } + } + return nil } func routePrivateMessage(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String) { @@ -294,10 +386,42 @@ final class ChatPrivateConversationCoordinator { private var seenInboundGeoDMOrder: [String] = [] private static let seenInboundGeoDMCap = 512 + private struct PendingGeoDM { + let messageID: String + let peerID: PeerID + let content: String + let recipientHex: String + let geohash: String + let createdAt: Date + var attempts: Int = 0 + } + private var pendingGeohashDMs: [PendingGeoDM] = [] + private var inFlightGeoDMIDs: Set = [] + private var geoDMRetryTask: Task? + private var wipeGeneration: UInt64 = 0 + /// Noise keys to which we already sent our signed `nostrRouteExchange` + /// this session, preventing repeated sends on every message. + private var sentNostrRouteExchanges: Set = [] + init(context: any ChatPrivateConversationContext) { self.context = context } + deinit { + geoDMRetryTask?.cancel() + } + + func resetForPanic() { + wipeGeneration &+= 1 + geoDMRetryTask?.cancel() + geoDMRetryTask = nil + pendingGeohashDMs.removeAll() + inFlightGeoDMIDs.removeAll() + sentNostrRouteExchanges.removeAll() + seenInboundGeoDMIDs.removeAll() + seenInboundGeoDMOrder.removeAll() + } + /// Returns `false` if this GeoDM message ID was already handled. private func markInboundGeoDMSeen(_ messageId: String) -> Bool { guard !seenInboundGeoDMIDs.contains(messageId) else { return false } @@ -440,12 +564,19 @@ final class ChatPrivateConversationCoordinator { recipientNickname: recipientNickname, messageID: messageID ) - if isConnected || isReachable || (isMutualFavorite && hasNostrKey && context.isNostrRelayConnected) { + let hasNostrPath = (isMutualFavorite && hasNostrKey) || context.hasDirectNostrRoute(for: peerID) + if isConnected || isReachable || (!context.usesConfirmedNostrPrivateSend && hasNostrPath && context.isNostrRelayConnected) { context.setPrivateDeliveryStatus(.sent, forMessageID: messageID, peerID: peerID) } + // If we are chatting live over BLE and both sides have exchanged a DM, + // silently share our signed Nostr route over Noise so subsequent DMs + // keep flowing over Nostr once we walk out of radio range. + if isConnected { + maybeExchangeNostrRouteOverNoise(with: peerID) + } // Otherwise the message stays "sending"; router callbacks move it to - // carried (📦) when a courier/bridge copy ships, delivered/read on - // acks, or failed when the outbox TTL expires. + // sent (on NIP-01 OK), carried (📦) when a courier/bridge copy ships, + // delivered/read on acks, or failed when the outbox TTL expires. } private func initialDeliveryStatus(for content: String) -> DeliveryStatus { @@ -462,7 +593,13 @@ final class ChatPrivateConversationCoordinator { } func sendGeohashDM(_ content: String, to peerID: PeerID) { - guard case .location(let channel) = context.activeChannel else { + let resolvedGeohash: String? = context.geohashForGeoDM(peerID) ?? { + if case .location(let channel) = context.activeChannel { + return channel.geohash + } + return nil + }() + guard let geohash = resolvedGeohash else { // The failure happened inside a geoDM thread — surface it there, // not on the public timeline (matches the sibling blocked/unknown // errors routed into the thread by #1415). @@ -517,7 +654,7 @@ final class ChatPrivateConversationCoordinator { } do { - let identity = try context.deriveNostrIdentity(forGeohash: channel.geohash) + let identity = try context.deriveNostrIdentity(forGeohash: geohash) if recipientHex.lowercased() == identity.publicKeyHex.lowercased() { context.setPrivateDeliveryStatus( .failed( @@ -529,17 +666,23 @@ final class ChatPrivateConversationCoordinator { return } - SecureLogger.debug( - "GeoDM: local send mid=\(messageID.prefix(8))… to=\(recipientHex.prefix(8))… conv=\(peerID)", - category: .session - ) - context.sendGeohashPrivateMessage( - content, - toRecipientHex: recipientHex, - from: identity, - messageID: messageID - ) - context.setPrivateDeliveryStatus(.sent, forMessageID: messageID, peerID: peerID) + pendingGeohashDMs.append(PendingGeoDM( + messageID: messageID, + peerID: peerID, + content: content, + recipientHex: recipientHex, + geohash: geohash, + createdAt: Date() + )) + if pendingGeohashDMs.count > 100 { + let evicted = pendingGeohashDMs.removeFirst() + context.setPrivateDeliveryStatus( + .failed(reason: String(localized: "content.delivery.reason.not_delivered", comment: "Failure reason shown when the router gave up delivering a message")), + forMessageID: evicted.messageID, + peerID: evicted.peerID + ) + } + flushPendingGeohashDMs() } catch { context.setPrivateDeliveryStatus( .failed( @@ -551,6 +694,86 @@ final class ChatPrivateConversationCoordinator { } } + /// Flushes queued GeoDMs over connected DM relays, advancing `.sending` → `.sent` + /// only after a relay explicitly confirms NIP-01 `OK`. + func flushPendingGeohashDMs(now: Date = Date()) { + guard !pendingGeohashDMs.isEmpty else { return } + + // Expire items older than 24 hours. + var fresh: [PendingGeoDM] = [] + for item in pendingGeohashDMs { + if now.timeIntervalSince(item.createdAt) > 24 * 60 * 60 { + context.setPrivateDeliveryStatus( + .failed(reason: String(localized: "content.delivery.reason.not_delivered", comment: "Failure reason shown when the router gave up delivering a message")), + forMessageID: item.messageID, + peerID: item.peerID + ) + } else { + fresh.append(item) + } + } + pendingGeohashDMs = fresh + + guard context.isNostrRelayConnected else { return } + let generation = wipeGeneration + + for item in pendingGeohashDMs { + guard inFlightGeoDMIDs.insert(item.messageID).inserted else { continue } + guard let identity = try? context.deriveNostrIdentity(forGeohash: item.geohash) else { + inFlightGeoDMIDs.remove(item.messageID) + pendingGeohashDMs.removeAll { $0.messageID == item.messageID } + context.setPrivateDeliveryStatus( + .failed(reason: String(localized: "content.delivery.reason.send_error", comment: "Failure reason for a generic send error")), + forMessageID: item.messageID, + peerID: item.peerID + ) + continue + } + + SecureLogger.debug( + "GeoDM: local send mid=\(item.messageID.prefix(8))… to=\(item.recipientHex.prefix(8))… conv=\(item.peerID)", + category: .session + ) + context.sendGeohashPrivateMessageConfirmed( + item.content, + toRecipientHex: item.recipientHex, + from: identity, + messageID: item.messageID + ) { [weak self] accepted in + guard let self, self.wipeGeneration == generation else { return } + self.inFlightGeoDMIDs.remove(item.messageID) + if accepted { + self.pendingGeohashDMs.removeAll { $0.messageID == item.messageID } + self.context.setPrivateDeliveryStatus(.sent, forMessageID: item.messageID, peerID: item.peerID) + } else if self.context.isNostrRelayConnected, + let idx = self.pendingGeohashDMs.firstIndex(where: { $0.messageID == item.messageID }) { + self.pendingGeohashDMs[idx].attempts += 1 + if self.pendingGeohashDMs[idx].attempts >= 8 { + let dropped = self.pendingGeohashDMs.remove(at: idx) + self.context.setPrivateDeliveryStatus( + .failed(reason: String(localized: "content.delivery.reason.not_delivered", comment: "Failure reason shown when the router gave up delivering a message")), + forMessageID: dropped.messageID, + peerID: dropped.peerID + ) + } else { + self.scheduleGeoDMRetryIfNeeded() + } + } + } + } + } + + private func scheduleGeoDMRetryIfNeeded(delaySeconds: TimeInterval = 15) { + guard geoDMRetryTask == nil, !pendingGeohashDMs.isEmpty else { return } + let generation = wipeGeneration + geoDMRetryTask = Task { @MainActor [weak self] in + try? await Task.sleep(nanoseconds: UInt64(delaySeconds * 1_000_000_000)) + guard let self, !Task.isCancelled, self.wipeGeneration == generation else { return } + self.geoDMRetryTask = nil + self.flushPendingGeohashDMs() + } + } + func handlePrivateMessage( _ payload: NoisePayload, senderPubkey: String, @@ -641,6 +864,11 @@ final class ChatPrivateConversationCoordinator { !favoriteNickname.isEmpty { return favoriteNickname } + if !convKey.isGeoDM, + let hybridNick = context.hybridSenderNickname(for: convKey, noiseKey: convKey.noiseKey), + !hybridNick.isEmpty { + return hybridNick + } return context.displayNameForNostrPubkey(senderPubkey) } @@ -652,7 +880,7 @@ final class ChatPrivateConversationCoordinator { guard let messageID = String(data: payload.data, encoding: .utf8) else { return } let aliases = accountConversationAliases(for: convKey) - let clearedRetainedMessage = convKey.noiseKey != nil + let clearedRetainedMessage = !convKey.isGeoDM ? context.markMessageDelivered(messageID, for: aliases) : false let isOutgoingMessage = context.isOutgoingPrivateMessage(messageID, toAny: Set(aliases)) @@ -689,7 +917,7 @@ final class ChatPrivateConversationCoordinator { guard let messageID = String(data: payload.data, encoding: .utf8) else { return } let aliases = accountConversationAliases(for: convKey) - let clearedRetainedMessage = convKey.noiseKey != nil + let clearedRetainedMessage = !convKey.isGeoDM ? context.markMessageDelivered(messageID, for: aliases) : false let isOutgoingMessage = context.isOutgoingPrivateMessage(messageID, toAny: Set(aliases)) @@ -784,6 +1012,110 @@ final class ChatPrivateConversationCoordinator { context.notifyPrivateMessage(from: message.sender, message: message.content, peerID: peerID) } + // Once both sides have sent a 1:1 DM over BLE, exchange signed Nostr + // routing keys over the authenticated Noise session so future DMs work + // seamlessly over Nostr when out of Bluetooth range. + if context.isPeerConnected(peerID) { + maybeExchangeNostrRouteOverNoise(with: peerID) + } + } + + /// Processes a signed `NoisePayloadType.nostrRouteExchange` received over + /// an authenticated Noise session. Requires a valid Schnorr proof binding + /// the peer's Nostr npub to the exact Noise static key of this session. + func handleNostrRouteExchangePayload(from peerID: PeerID, payload: Data) { + guard let payloadString = String(data: payload, encoding: .utf8), + let peerNoiseKey = peerID.noiseKey ?? context.noisePublicKey(for: peerID), + peerNoiseKey.count == FavoritesPersistenceService.expectedNoiseKeyLength else { + return + } + let myNoiseKey = context.myNoisePublicKey() + guard peerNoiseKey != myNoiseKey else { return } + + let stablePeerID = PeerID(hexData: peerNoiseKey) + guard !context.isPeerBlocked(peerID), !context.isPeerBlocked(stablePeerID) else { + return + } + + let senderNickname = context.peerNickname(for: peerID) ?? "" + guard let verified = FriendInvite.parseFavoriteAcceptancePayload( + payloadString, + expectedSenderPubkeyHex: nil, + nickname: senderNickname + ) else { + SecureLogger.warning("⚠️ Dropping invalid signed Nostr route exchange from \(peerID.id.prefix(8))…", category: .security) + return + } + guard verified.noisePublicKey == peerNoiseKey else { + SecureLogger.warning("🚫 Dropping Nostr route exchange with mismatched Noise key from \(peerID.id.prefix(8))…", category: .security) + return + } + if let existingOwner = context.favoriteNoiseKey(forNostrPubkey: verified.nostrNpub), + existingOwner != peerNoiseKey { + SecureLogger.warning("🚫 Dropping Nostr route exchange claiming another peer's npub", category: .security) + return + } + + context.storeNostrPeerRoute( + noiseKey: peerNoiseKey, + nostrPubkey: verified.nostrNpub, + nickname: senderNickname + ) + SecureLogger.info("🌐 Learned verified Nostr DM route over Noise for \(peerID.id.prefix(8))…", category: .session) + + // Reciprocate only when mutual 1:1 DM consent exists (we've also sent + // a message in this thread). + if context.isPeerConnected(peerID) { + maybeExchangeNostrRouteOverNoise(with: peerID) + } + } + + private func maybeExchangeNostrRouteOverNoise(with peerID: PeerID) { + guard !peerID.isGeoDM, !peerID.isGroup, + let peerNoiseKey = peerID.noiseKey ?? context.noisePublicKey(for: peerID), + peerNoiseKey.count == FavoritesPersistenceService.expectedNoiseKeyLength, + peerNoiseKey != context.myNoisePublicKey(), + !sentNostrRouteExchanges.contains(peerNoiseKey), + hasMutualDMConversation(with: peerID, peerNoiseKey: peerNoiseKey) else { + return + } + guard let myNostrIdentity = context.currentNostrIdentity() else { return } + let myNoiseKey = context.myNoisePublicKey() + let mySigningKey = context.mySigningPublicKey() + guard myNoiseKey.count == FavoritesPersistenceService.expectedNoiseKeyLength, + mySigningKey.count == 32, + let signed = FriendInvite.makeSigned( + nickname: context.nickname, + noisePublicKey: myNoiseKey, + signingPublicKey: mySigningKey, + nostrIdentity: myNostrIdentity + ), + let payload = signed.favoriteAcceptancePayload().data(using: .utf8) else { + return + } + sentNostrRouteExchanges.insert(peerNoiseKey) + context.sendNostrRouteExchangePayload(payload, to: peerID) + } + + /// True when both we and `peerID` have sent at least one non-system message + /// in this 1:1 conversation (mutual conversation consent). + private func hasMutualDMConversation(with peerID: PeerID, peerNoiseKey: Data) -> Bool { + let aliases = Set([peerID, peerID.toShort(), PeerID(hexData: peerNoiseKey)]) + var hasOwnMessage = false + var hasPeerMessage = false + for alias in aliases { + for message in context.privateMessages(for: alias) where message.sender != "system" { + if message.senderPeerID == context.myPeerID { + hasOwnMessage = true + } else { + hasPeerMessage = true + } + if hasOwnMessage && hasPeerMessage { + return true + } + } + } + return false } /// O(1)-per-conversation dedup via the store's message-ID indexes @@ -926,7 +1258,6 @@ final class ChatPrivateConversationCoordinator { nostrPubkey = nil } - let prior = context.favoriteRelationship(forNoiseKey: finalNoiseKey)?.theyFavoritedUs ?? false context.updatePeerFavoritedUs( noiseKey: finalNoiseKey, favorited: isFavorite, @@ -935,16 +1266,16 @@ final class ChatPrivateConversationCoordinator { ) if isFavorite, let nostrPubkey { + context.storeNostrPeerRoute( + noiseKey: finalNoiseKey, + nostrPubkey: nostrPubkey, + nickname: senderNickname + ) SecureLogger.info( "💾 Storing Nostr key association for \(senderNickname): \(nostrPubkey.prefix(16))...", category: .session ) } - - if prior != isFavorite { - let action = isFavorite ? "favorited" : "unfavorited" - context.addMeshOnlySystemMessage("\(senderNickname) \(action) you") - } } func processActionMessage(_ message: BitchatMessage) -> BitchatMessage { diff --git a/bitchat/ViewModels/ChatTransportEventCoordinator.swift b/bitchat/ViewModels/ChatTransportEventCoordinator.swift index ae56d983..345ffe6b 100644 --- a/bitchat/ViewModels/ChatTransportEventCoordinator.swift +++ b/bitchat/ViewModels/ChatTransportEventCoordinator.swift @@ -88,6 +88,7 @@ protocol ChatTransportEventContext: AnyObject { // MARK: Group payloads (creator-signed state over Noise) func handleGroupInvitePayload(from peerID: PeerID, payload: Data) func handleGroupKeyUpdatePayload(from peerID: PeerID, payload: Data) + func handleNostrRouteExchangePayload(from peerID: PeerID, payload: Data) func handleVouchPayload(from peerID: PeerID, payload: Data) } @@ -173,6 +174,10 @@ extension ChatViewModel: ChatTransportEventContext { groupCoordinator.handleGroupKeyUpdatePayload(from: peerID, payload: payload) } + func handleNostrRouteExchangePayload(from peerID: PeerID, payload: Data) { + privateConversationCoordinator.handleNostrRouteExchangePayload(from: peerID, payload: payload) + } + func handleVouchPayload(from peerID: PeerID, payload: Data) { vouchCoordinator.handleVouchPayload(from: peerID, payload: payload) } @@ -473,6 +478,9 @@ private extension ChatTransportEventCoordinator { // state inside the transport. Neither payload crosses this // UI-facing typed-payload fallback. break + + case .nostrRouteExchange: + context.handleNostrRouteExchangePayload(from: peerID, payload: payload) } } diff --git a/bitchat/ViewModels/ChatViewModel.swift b/bitchat/ViewModels/ChatViewModel.swift index 33caf947..f2bb8ed9 100644 --- a/bitchat/ViewModels/ChatViewModel.swift +++ b/bitchat/ViewModels/ChatViewModel.swift @@ -355,6 +355,8 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel private var isPanicResetting = false /// Private group membership: keys in the keychain, metadata on disk. let groupStore: GroupStore + let groupOutboxStore: GroupOutboxStore? + let nostrPeerRouteStore: NostrPeerRouteStore /// Encrypted local persistence for private DMs and group chats, plus /// per-chat disappearing message timers. let encryptedHistoryStore: EncryptedHistoryStore @@ -1234,6 +1236,14 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel keychain: keychain, loadSynchronously: TestEnvironment.isRunningTests ) + self.groupOutboxStore = GroupOutboxStore( + keychain: keychain, + persistsToDisk: !TestEnvironment.isRunningTests + ) + self.nostrPeerRouteStore = NostrPeerRouteStore( + keychain: keychain, + persistsToDisk: !TestEnvironment.isRunningTests + ) self.encryptedHistoryStore = encryptedHistoryStore ?? EncryptedHistoryStore( keychain: keychain, persistsToDisk: !TestEnvironment.isRunningTests @@ -1615,17 +1625,6 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel peerIdentityCoordinator.hasUnreadMessages(for: peerID) } - @MainActor - @discardableResult - func toggleFavorite(peerID: PeerID) -> FavoriteToggleOutcome { - peerIdentityCoordinator.toggleFavorite(peerID: peerID) - } - - @MainActor - func isFavorite(peerID: PeerID) -> Bool { - peerIdentityCoordinator.isFavorite(peerID: peerID) - } - // MARK: - Friend Invites @MainActor @@ -1672,6 +1671,12 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel peerNostrPublicKey: invite.nostrNpub, peerNickname: invite.nickname ) + nostrPeerRouteStore.upsert( + noisePublicKey: invite.noisePublicKey, + nostrPubkey: invite.nostrNpub, + nickname: invite.nickname + ) + syncDirectNostrRoutes() if let (hrp, data) = try? Bech32.decode(invite.nostrNpub), hrp == "npub" { registerNostrKeyMapping(data.hexEncodedString(), for: invite.stablePeerID) @@ -1699,6 +1704,12 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel signingPublicKey: invite.signingPublicKey, claimedNickname: invite.nickname ) + nostrPeerRouteStore.upsert( + noisePublicKey: invite.noisePublicKey, + nostrPubkey: invite.nostrNpub, + nickname: invite.nickname + ) + syncDirectNostrRoutes() if let (hrp, data) = try? Bech32.decode(invite.nostrNpub), hrp == "npub" { registerNostrKeyMapping(data.hexEncodedString(), for: invite.stablePeerID) } @@ -1838,7 +1849,7 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel @MainActor private func setMeshPeerBlocked(_ peerID: PeerID, blocked: Bool, displayName: String) { - guard unifiedPeerService.setBlocked(peerID, blocked: blocked) != nil else { + guard let fingerprint = unifiedPeerService.setBlocked(peerID, blocked: blocked) else { addCommandOutput( String( format: String( @@ -1851,6 +1862,10 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel ) return } + if blocked { + nostrPeerRouteStore.removeRoute(forFingerprint: fingerprint) + } + syncDirectNostrRoutes() addCommandOutput( String( format: String( @@ -1933,6 +1948,75 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel @objc func handleFavoriteStatusChanged(_ notification: Notification) { peerIdentityCoordinator.handleFavoriteStatusChanged(notification) + groupCoordinator.refreshMemberNostrRoutingFromFavorites() + syncDirectNostrRoutes() + } + + /// Rebuilds supplemental 1:1 Nostr DM routes from mutual-DM key exchanges + /// (`nostrPeerRouteStore`) and shared encrypted private groups (`groupStore`), + /// pushing them to `NostrTransport` and keeping default Nostr relay + /// activation alive when any hybrid route exists. + func syncDirectNostrRoutes() { + var routes: [PeerID: String] = [:] + let myFingerprint = myNoiseFingerprint() + + // 1. Learned mutual-DM Nostr routes (cryptographically bound over Noise). + for (noiseKey, route) in nostrPeerRouteStore.routes { + let fingerprint = noiseKey.sha256Fingerprint() + guard !identityManager.isBlocked(fingerprint: fingerprint), + !identityManager.isNostrBlocked(pubkeyHexLowercased: route.nostrPubkeyHex) else { continue } + routes[PeerID(hexData: noiseKey)] = route.nostrPubkeyHex + routes[PeerID(publicKey: noiseKey)] = route.nostrPubkeyHex + } + + // 2. Shared encrypted private-group members with known Nostr pubkeys. + for group in groupStore.groups { + for member in group.members where member.fingerprint != myFingerprint { + guard !identityManager.isBlocked(fingerprint: member.fingerprint), + let pubkeyHex = FavoritesPersistenceService.nostrPubkeyHex(from: member.nostrPubkeyHex), + !identityManager.isNostrBlocked(pubkeyHexLowercased: pubkeyHex) else { continue } + let shortID = PeerID(str: String(member.fingerprint.prefix(16))) + if routes[shortID] == nil { + routes[shortID] = pubkeyHex + } + if let identity = identityManager.getCryptoIdentitiesByPeerIDPrefix(shortID) + .first(where: { $0.fingerprint == member.fingerprint }) { + let fullID = PeerID(hexData: identity.publicKey) + if routes[fullID] == nil { + routes[fullID] = pubkeyHex + } + } + } + } + + messageRouter.nostrTransport?.updateAdditionalNostrRoutes(routes) + let hasHybridNostr = groupStore.hasActiveMultiMemberGroup || !routes.isEmpty + if networkActivationAllowed && !TestEnvironment.isRunningTests { + NetworkActivationService.shared.setHasNostrGroups(hasHybridNostr) + } + } + + /// True when `peerID` has a known 1:1 Nostr route via mutual favorite, + /// mutual-DM Noise exchange, or shared encrypted group membership. + func hasDirectNostrRoute(for peerID: PeerID) -> Bool { + if let nostr = messageRouter.nostrTransport, nostr.isPeerReachable(peerID) { + return true + } + if nostrPeerRouteStore.nostrPubkeyHex(forPeerID: peerID) != nil { + return true + } + let short = peerID.toShort() + let myFingerprint = myNoiseFingerprint() + for group in groupStore.groups { + if group.members.contains(where: { + $0.fingerprint != myFingerprint + && String($0.fingerprint.prefix(16)) == short.id + && FavoritesPersistenceService.nostrPubkeyHex(from: $0.nostrPubkeyHex) != nil + }) { + return true + } + } + return false } // MARK: - App Lifecycle @@ -2119,8 +2203,12 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel CashuTokenDecoder.resetForPanic() Color.clearPeerColorCache() - // Drop private group keys and rosters (keychain + disk) + // Drop private group outbox, keys, and rosters (keychain + disk) + groupCoordinator.resetForPanic() groupStore.wipe() + nostrPeerRouteStore.wipe() + privateConversationCoordinator.resetForPanic() + messageRouter.nostrTransport?.updateAdditionalNostrRoutes([:]) // Drop cached peers' prekey bundles (who we could write to is // metadata too). Our own prekey privates are keychain-backed and go // with deleteAllKeychainData above plus the identity reset below. diff --git a/bitchat/ViewModels/ChatViewModelBootstrapper.swift b/bitchat/ViewModels/ChatViewModelBootstrapper.swift index 3545a811..265919c3 100644 --- a/bitchat/ViewModels/ChatViewModelBootstrapper.swift +++ b/bitchat/ViewModels/ChatViewModelBootstrapper.swift @@ -97,10 +97,15 @@ final class ChatViewModelBootstrapper { private extension ChatViewModelBootstrapper { func wireServiceGraph() { - LocalWebOfTrustService.shared.configure(identityManager: viewModel.identityManager) + LocalWebOfTrustService.shared.configure( + identityManager: viewModel.identityManager, + nostrPeerRouteStore: viewModel.nostrPeerRouteStore + ) + NostrFollowsStore.shared.configureContactRoutesStore(viewModel.nostrPeerRouteStore) viewModel.privateChatManager.conversationStore = viewModel.conversations viewModel.privateChatManager.unifiedPeerService = viewModel.unifiedPeerService viewModel.unifiedPeerService.messageRouter = viewModel.messageRouter + viewModel.unifiedPeerService.configureNostrPeerRouteStore(viewModel.nostrPeerRouteStore) // Surface silent outbox drops (attempt cap, TTL expiry, overflow // eviction) as a visible failure. The store's no-downgrade rule does // not cover `.failed` over confirmed receipts, so guard here: a drop @@ -152,13 +157,29 @@ private extension ChatViewModelBootstrapper { guard let viewModel else { return } _ = viewModel.conversations.setDeliveryStatus(.sent, forMessageID: messageID) } + // Settle Nostr 1:1 DM sends against real NIP-01 `OK` relay acceptance + // so half-dead sockets or transient rejections stay `.sending` and retry. + viewModel.messageRouter.nostrTransport?.onPrivateMessageSendResult = { [weak viewModel] messageID, peerID, accepted in + viewModel?.messageRouter.handleNostrPrivateMessageSendResult( + messageID: messageID, + peerID: peerID, + accepted: accepted + ) + } // Offline → online DM handoff: flush retained outbox messages, retry - // bridge courier drops, and emit any deferred read receipts for the - // currently viewed chat the moment a DM-capable Nostr relay connects. + // bridge courier drops, flush queued hybrid group Nostr deliveries, + // flush queued GeoDMs, ensure the gift-wrap inbox subscription is + // registered, and emit any deferred read receipts for the currently + // viewed chat the moment a DM-capable Nostr relay connects. viewModel.messageRouter.nostrTransport?.onRelayConnectivityChanged = { [weak viewModel] connected in guard let viewModel, connected else { return } + if viewModel.networkActivationAllowed { + viewModel.ensureNostrMessageHandlingSubscribed() + } viewModel.messageRouter.flushAllOutbox() viewModel.messageRouter.retryBridgeCourierDeposits() + viewModel.groupCoordinator.flushPendingNostrDeliveries() + viewModel.privateConversationCoordinator.flushPendingGeohashDMs() if viewModel.isAppActive, let selectedPeer = viewModel.selectedPrivateChatPeer { viewModel.markPrivateMessagesAsRead(from: selectedPeer) } @@ -185,6 +206,31 @@ private extension ChatViewModelBootstrapper { } } .store(in: &viewModel.cancellables) + + // Keep Nostr network activation, supplemental 1:1 Nostr routes, and + // default DM relays alive whenever the user belongs to a multi-member + // encrypted group or has mutual-DM Nostr routes. + viewModel.groupStore.$groups + .receive(on: DispatchQueue.main) + .sink { [weak viewModel] groups in + MainActor.assumeIsolated { + guard let viewModel else { return } + if groups.contains(where: { $0.members.count > 1 }) { + viewModel.groupCoordinator.refreshMemberNostrRoutingFromFavorites() + } + viewModel.syncDirectNostrRoutes() + } + } + .store(in: &viewModel.cancellables) + + viewModel.nostrPeerRouteStore.$routes + .receive(on: DispatchQueue.main) + .sink { [weak viewModel] _ in + MainActor.assumeIsolated { + viewModel?.syncDirectNostrRoutes() + } + } + .store(in: &viewModel.cancellables) } func loadPersistedViewState() { @@ -217,7 +263,11 @@ private extension ChatViewModelBootstrapper { } viewModel.nostrRelayManager = NostrRelayManager.shared + viewModel.syncDirectNostrRoutes() viewModel.messageRouter.flushAllOutbox() + viewModel.groupCoordinator.refreshMemberNostrRoutingFromFavorites() + viewModel.groupCoordinator.flushPendingNostrDeliveries() + viewModel.privateConversationCoordinator.flushPendingGeohashDMs() Task { @MainActor [weak viewModel] in guard let viewModel else { return } @@ -644,9 +694,15 @@ private extension ChatViewModelBootstrapper { .receive(on: DispatchQueue.main) .sink { [weak viewModel] connected in BridgeCourierService.shared.refresh() - guard connected, - let viewModel, - viewModel.isAppActive, + guard connected, let viewModel else { + return + } + if viewModel.networkActivationAllowed { + viewModel.ensureNostrMessageHandlingSubscribed() + } + viewModel.groupCoordinator.flushPendingNostrDeliveries() + viewModel.privateConversationCoordinator.flushPendingGeohashDMs() + guard viewModel.isAppActive, let peerID = viewModel.selectedPrivateChatPeer else { return } @@ -654,15 +710,21 @@ private extension ChatViewModelBootstrapper { } .store(in: &viewModel.cancellables) - // Retry deferred GeoDM/Nostr read receipts when network activation or - // general relay connectivity returns while a private chat is open. + // Retry deferred GeoDM/Nostr read receipts and queued hybrid group / + // GeoDM Nostr deliveries when network activation returns. NetworkActivationService.shared.$activationAllowed .removeDuplicates() .receive(on: DispatchQueue.main) .sink { [weak viewModel] allowed in - guard allowed, - let viewModel, - viewModel.isAppActive, + guard allowed, let viewModel else { + return + } + if viewModel.networkActivationAllowed { + viewModel.ensureNostrMessageHandlingSubscribed() + } + viewModel.groupCoordinator.flushPendingNostrDeliveries() + viewModel.privateConversationCoordinator.flushPendingGeohashDMs() + guard viewModel.isAppActive, let peerID = viewModel.selectedPrivateChatPeer else { return } diff --git a/bitchat/ViewModels/Extensions/ChatViewModel+Nostr.swift b/bitchat/ViewModels/Extensions/ChatViewModel+Nostr.swift index 1cfd1610..8be36f66 100644 --- a/bitchat/ViewModels/Extensions/ChatViewModel+Nostr.swift +++ b/bitchat/ViewModels/Extensions/ChatViewModel+Nostr.swift @@ -60,6 +60,11 @@ extension ChatViewModel { nostrCoordinator.subscriptions.setupNostrMessageHandling() } + @MainActor + func ensureNostrMessageHandlingSubscribed() { + nostrCoordinator.subscriptions.ensureNostrMessageHandlingSubscribed() + } + @MainActor func findNoiseKey(for nostrPubkey: String) -> Data? { nostrCoordinator.inbound.findNoiseKey(for: nostrPubkey) diff --git a/bitchat/ViewModels/GeohashSubscriptionManager.swift b/bitchat/ViewModels/GeohashSubscriptionManager.swift index 533277b3..318fbcba 100644 --- a/bitchat/ViewModels/GeohashSubscriptionManager.swift +++ b/bitchat/ViewModels/GeohashSubscriptionManager.swift @@ -420,4 +420,15 @@ final class GeohashSubscriptionManager { } } } + + /// Re-registers the account DM / group gift-wrap subscription when + /// `chat-messages` was previously skipped or registered against an empty + /// relay list (e.g. before default relays opened for a new hybrid group). + @MainActor + func ensureNostrMessageHandlingSubscribed() { + guard let context else { return } + let relayManager = context.nostrRelayManager ?? NostrRelayManager.shared + guard !relayManager.hasRegisteredSubscription(id: "chat-messages") else { return } + setupNostrMessageHandling() + } } diff --git a/bitchat/ViewModels/NostrInboundPipeline.swift b/bitchat/ViewModels/NostrInboundPipeline.swift index 794ff699..3b3335d3 100644 --- a/bitchat/ViewModels/NostrInboundPipeline.swift +++ b/bitchat/ViewModels/NostrInboundPipeline.swift @@ -21,10 +21,13 @@ protocol NostrInboundPipelineContext: AnyObject { func isNostrBlocked(pubkeyHexLowercased: String) -> Bool func displayNameForNostrPubkey(_ pubkeyHex: String) -> String - // MARK: Favorites bridge + // MARK: Favorites & hybrid route bridge /// Fast reverse lookup from a Nostr pubkey (hex or npub) to a favorite's /// Noise static key. func favoriteNoiseKey(forNostrPubkey nostrPubkey: String) -> Data? + /// Fallback reverse lookup for mutual-DM learned routes or shared private + /// group members when the sender is not in `FavoritesPersistenceService`. + func hybridAccountDMConversationKey(forNostrPubkey nostrPubkey: String) -> PeerID? // MARK: Presence & key mapping func setGeoNickname(_ nickname: String, forPubkey pubkeyHex: String) @@ -88,6 +91,7 @@ extension NostrInboundPipelineContext { func handleNostrGroupInvite(_ payload: Data, from senderPeerID: PeerID) {} func handleNostrGroupKeyUpdate(_ payload: Data, from senderPeerID: PeerID) {} func handleNostrGroupMessage(_ payload: Data, timestamp: Date) {} + func hybridAccountDMConversationKey(forNostrPubkey nostrPubkey: String) -> PeerID? { nil } } extension ChatViewModel: NostrInboundPipelineContext { @@ -101,6 +105,31 @@ extension ChatViewModel: NostrInboundPipelineContext { func favoriteNoiseKey(forNostrPubkey nostrPubkey: String) -> Data? { FavoritesPersistenceService.shared.noisePublicKey(forNostrPubkey: nostrPubkey) + ?? nostrPeerRouteStore.noisePublicKey(forNostrPubkey: nostrPubkey) + } + + func hybridAccountDMConversationKey(forNostrPubkey nostrPubkey: String) -> PeerID? { + guard let normalized = FavoritesPersistenceService.nostrPubkeyHex(from: nostrPubkey) else { + return nil + } + if let noiseKey = nostrPeerRouteStore.noisePublicKey(forNostrPubkey: normalized) { + return PeerID(hexData: noiseKey) + } + let myFP = myNoiseFingerprint() + for group in groupStore.groups { + if let member = group.members.first(where: { + $0.fingerprint != myFP + && FavoritesPersistenceService.nostrPubkeyHex(from: $0.nostrPubkeyHex) == normalized + }) { + let shortID = PeerID(str: String(member.fingerprint.prefix(16))) + if let identity = identityManager.getCryptoIdentitiesByPeerIDPrefix(shortID) + .first(where: { $0.fingerprint == member.fingerprint }) { + return PeerID(hexData: identity.publicKey) + } + return shortID + } + } + return nil } func recordProcessedNostrEvent(_ eventID: String) { @@ -420,7 +449,13 @@ final class NostrInboundPipeline { } } else { let actualSenderNoiseKey = self.findNoiseKey(for: senderPubkey) - convKey = PeerID(str: actualSenderNoiseKey?.hexEncodedString()) ?? PeerID(nostr_: senderPubkey) + if let actualSenderNoiseKey { + convKey = PeerID(hexData: actualSenderNoiseKey) + } else if let hybridKey = context.hybridAccountDMConversationKey(forNostrPubkey: senderPubkey) { + convKey = hybridKey + } else { + convKey = PeerID(nostr_: senderPubkey) + } } context.registerNostrKeyMapping(senderPubkey, for: convKey) @@ -446,7 +481,7 @@ final class NostrInboundPipeline { if !isGeohashDM { context.handleNostrGroupKeyUpdate(payload.data, from: convKey) } - case .verifyChallenge, .verifyResponse, .vouch, .voiceFrame, .privateFile, .authenticatedPeerState: + case .verifyChallenge, .verifyResponse, .vouch, .voiceFrame, .privateFile, .authenticatedPeerState, .nostrRouteExchange: break } } diff --git a/bitchat/Views/AppInfoView.swift b/bitchat/Views/AppInfoView.swift index 1d417e54..a6f150cb 100644 --- a/bitchat/Views/AppInfoView.swift +++ b/bitchat/Views/AppInfoView.swift @@ -194,11 +194,6 @@ struct AppInfoView: View { title: "app_info.features.mentions.title", description: "app_info.features.mentions.description" ) - static let favorites = AppInfoFeatureInfo( - icon: "star.fill", - title: "app_info.features.favorites.title", - description: "app_info.features.favorites.description" - ) static let geohash = AppInfoFeatureInfo( icon: "number", title: "app_info.features.geohash.title", @@ -227,7 +222,6 @@ struct AppInfoView: View { ("lock.fill", nil, String(localized: "app_info.legend.encrypted")), ("lock.slash", nil, String(localized: "app_info.legend.encryption_failed")), ("checkmark.seal.fill", nil, String(localized: "app_info.legend.verified")), - ("star.fill", nil, String(localized: "app_info.legend.favorite")), ("envelope.fill", nil, String(localized: "app_info.legend.unread")), ("nosign", nil, String(localized: "app_info.legend.blocked")) ] @@ -1066,8 +1060,6 @@ struct AppInfoView: View { FeatureRow(info: Strings.Features.bridge) - FeatureRow(info: Strings.Features.favorites) - FeatureRow(info: Strings.Features.geohash) FeatureRow(info: Strings.Features.mentions) diff --git a/bitchat/Views/ContactDetailSheet.swift b/bitchat/Views/ContactDetailSheet.swift index 0cce7995..c73d9944 100644 --- a/bitchat/Views/ContactDetailSheet.swift +++ b/bitchat/Views/ContactDetailSheet.swift @@ -275,34 +275,6 @@ struct ContactDetailSheet: View { } .padding(.vertical, 4) - if headerState?.supportsFavoriteToggle == true { - Divider().background(palette.divider).padding(.vertical, 8) - - Button { - privateConversationModel.toggleFavoriteForSelectedConversation() - } label: { - HStack(spacing: 12) { - Image(systemName: headerState?.isFavorite == true ? "star.fill" : "star") - .font(.system(size: 15, weight: .medium)) - .foregroundColor(headerState?.isFavorite == true ? .yellow : palette.secondary) - .frame(width: 22) - - Text( - headerState?.isFavorite == true - ? String(localized: "content.accessibility.remove_favorite", defaultValue: "Remove from Favorites", comment: "Button to unfavorite a peer") - : String(localized: "content.accessibility.add_favorite", defaultValue: "Add to Favorites", comment: "Button to favorite a peer") - ) - .bitchatFont(size: 14, weight: .medium) - .foregroundColor(palette.primary) - - Spacer() - } - .padding(.vertical, 4) - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - } - Divider().background(palette.divider).padding(.vertical, 8) HStack(spacing: 12) { @@ -678,6 +650,8 @@ struct ContactDetailSheet: View { return ("point.3.filled.connected.trianglepath.dotted", palette.accentBlue, String(localized: "inbox.status.mesh_relayed", defaultValue: "Reachable on mesh", comment: "Reachability status")) case .nostrAvailable: return ("globe", .purple, String(localized: "content.accessibility.available_nostr", defaultValue: "Available via Nostr", comment: "Reachability status")) + case .nostrQueued: + return ("clock.arrow.circlepath", .purple.opacity(0.85), String(localized: "content.private.transport.group_nostr_queued", defaultValue: "Encrypted · Queued for Nostr relay", comment: "Group transport caption when members have Nostr keys and messages will flush once a Nostr relay connects")) case .offline, .none: return ("antenna.radiowaves.left.and.right.slash", palette.secondary, String(localized: "mesh_peers.state.offline", defaultValue: "Offline", comment: "Reachability status")) } diff --git a/bitchat/Views/ContentSheetViews.swift b/bitchat/Views/ContentSheetViews.swift index 55961d96..65b61c11 100644 --- a/bitchat/Views/ContentSheetViews.swift +++ b/bitchat/Views/ContentSheetViews.swift @@ -329,9 +329,6 @@ private struct ContentPeopleListView: View { peerListModel.startConversation(with: peerID) showSidebar = true }, - onToggleFavorite: { peerID in - peerListModel.toggleFavorite(peerID: peerID) - }, onShowFingerprint: { peerID in appChromeModel.showFingerprint(for: peerID) }, @@ -532,19 +529,6 @@ private struct ContentPrivateChatSheetView: View { .accessibilityLabel( String(localized: "chat.timer.label", defaultValue: "Disappearing messages", comment: "Accessibility label for disappearing messages menu") ) - - if headerState.supportsFavoriteToggle { - TopBarIconButton( - systemImage: headerState.isFavorite ? "star.fill" : "star", - accessibilityLabel: headerState.isFavorite - ? String(localized: "content.accessibility.remove_favorite", comment: "Accessibility label to remove a favorite") - : String(localized: "content.accessibility.add_favorite", comment: "Accessibility label to add a favorite"), - color: headerState.isFavorite ? Color.yellow : palette.secondary, - action: { - privateConversationModel.toggleFavoriteForSelectedConversation() - } - ) - } } } @@ -697,6 +681,7 @@ private struct ContentPrivateChatSheetView: View { if header.isGroupConversation { let mesh = header.groupMeshReachableCount let nostr = header.groupNostrReachableCount + let nostrQueued = header.groupNostrQueuedCount if mesh > 0 && nostr > 0 { return ( "lock.fill", @@ -728,6 +713,12 @@ private struct ContentPrivateChatSheetView: View { nostr ) ) + } else if nostrQueued > 0 { + return ( + "clock.arrow.circlepath", + .purple.opacity(0.85), + String(localized: "content.private.transport.group_nostr_queued", defaultValue: "Encrypted · Queued for Nostr relay", comment: "Group transport caption when members have Nostr keys and messages will flush once a Nostr relay connects") + ) } else if header.groupOtherMemberCount > 0 { return ( "clock.arrow.circlepath", @@ -769,6 +760,13 @@ private struct ContentPrivateChatSheetView: View { : String(localized: "content.private.transport.nostr_relay", defaultValue: "Encrypted · Nostr relay", comment: "DM transport caption for a Nostr-routed DM") return ("globe", .purple, text) + case .nostrQueued: + return ( + "clock.arrow.circlepath", + .purple.opacity(0.85), + String(localized: "content.private.transport.group_nostr_queued", defaultValue: "Encrypted · Queued for Nostr relay", comment: "Group transport caption when members have Nostr keys and messages will flush once a Nostr relay connects") + ) + case .offline: return ( "clock.arrow.circlepath", @@ -818,6 +816,11 @@ private struct ContentPrivateHeaderInfoButton: View { .font(.system(size: 14, weight: .medium)) .foregroundColor(.purple) .accessibilityLabel(String(localized: "content.accessibility.available_nostr", comment: "Accessibility label for Nostr-available peer indicator")) + case .nostrQueued: + Image(systemName: "clock.arrow.circlepath") + .font(.system(size: 14, weight: .medium)) + .foregroundColor(.purple.opacity(0.85)) + .accessibilityLabel(String(localized: "content.private.transport.group_nostr_queued", defaultValue: "Encrypted · Queued for Nostr relay", comment: "Group transport caption when members have Nostr keys and messages will flush once a Nostr relay connects")) case .offline: Image(systemName: "antenna.radiowaves.left.and.right.slash") .font(.system(size: 14, weight: .medium)) diff --git a/bitchat/Views/MeshPeerList.swift b/bitchat/Views/MeshPeerList.swift index 3cc843cb..f93d4f9c 100644 --- a/bitchat/Views/MeshPeerList.swift +++ b/bitchat/Views/MeshPeerList.swift @@ -5,7 +5,6 @@ struct MeshPeerList: View { @EnvironmentObject private var peerListModel: PeerListModel @ThemedPalette private var palette let onTapPeer: (PeerID) -> Void - let onToggleFavorite: (PeerID) -> Void let onShowFingerprint: (PeerID) -> Void /// Optional so existing call sites (and previews/tests) keep compiling; /// when absent the block/unblock context-menu entry is hidden. @@ -22,13 +21,10 @@ struct MeshPeerList: View { static let reachable = String(localized: "content.accessibility.reachable_mesh", comment: "Accessibility label for mesh-reachable peer indicator") static let nostr = String(localized: "content.accessibility.available_nostr", comment: "Accessibility label for Nostr-available peer indicator") static let offline = String(localized: "mesh_peers.state.offline", comment: "State label for a peer that is not currently reachable") - static let favorite = String(localized: "mesh_peers.state.favorite", comment: "State label for a favorited peer") static let unread = String(localized: "mesh_peers.state.unread", comment: "State label for a peer with unread private messages") static let blocked = String(localized: "mesh_peers.state.blocked", comment: "State label for a blocked peer") static let vouched = String(localized: "mesh_peers.state.vouched", comment: "State label for a peer vouched for by someone the user verified") static let vouchedTooltip = String(localized: "mesh_peers.tooltip.vouched", comment: "Tooltip for the vouched (unfilled seal) badge next to a peer") - static let addFavorite = String(localized: "content.accessibility.add_favorite", comment: "Accessibility label to add a favorite") - static let removeFavorite = String(localized: "content.accessibility.remove_favorite", comment: "Accessibility label to remove a favorite") static let showFingerprint = String(localized: "mesh_peers.action.fingerprint", comment: "Context menu action that shows a peer's fingerprint/verification screen") static let openDMHint = String(localized: "mesh_peers.accessibility.open_dm_hint", comment: "Accessibility hint on a peer row explaining activation opens a private chat") static let directMessage = String(localized: "content.actions.direct_message", comment: "Action that opens a private chat with the person") @@ -160,20 +156,6 @@ struct MeshPeerList: View { .foregroundColor(.orange) .help(Strings.newMessagesTooltip) } - - if !isMe { - Button(action: { onToggleFavorite(peer.peerID) }) { - Image(systemName: peer.isFavorite ? "star.fill" : "star") - .font(.bitchatSystem(size: 12)) - .foregroundColor(peer.isFavorite ? .yellow : palette.secondary) - // Widen the tap target beyond the bare glyph; - // height stays row-bound so neighboring rows - // keep their own taps. - .frame(width: 36) - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - } } .padding(.horizontal) .padding(.vertical, 4) @@ -187,9 +169,6 @@ struct MeshPeerList: View { Button(Strings.directMessage) { onTapPeer(peer.peerID) } - Button(peer.isFavorite ? Strings.removeFavorite : Strings.addFavorite) { - onToggleFavorite(peer.peerID) - } Button(Strings.showFingerprint) { onShowFingerprint(peer.peerID) } @@ -212,9 +191,6 @@ struct MeshPeerList: View { .accessibilityHint(isMe ? "" : Strings.openDMHint) .accessibilityActions { if !isMe { - Button(peer.isFavorite ? Strings.removeFavorite : Strings.addFavorite) { - onToggleFavorite(peer.peerID) - } Button(Strings.showFingerprint) { onShowFingerprint(peer.peerID) } @@ -254,7 +230,6 @@ struct MeshPeerList: View { } } if peer.showsVouchedBadge { parts.append(Strings.vouched) } - if peer.isFavorite { parts.append(Strings.favorite) } if peer.hasUnread { parts.append(Strings.unread) } if peer.isBlocked { parts.append(Strings.blocked) } return parts.joined(separator: ", ") diff --git a/bitchat/Views/PublicProfileSheet.swift b/bitchat/Views/PublicProfileSheet.swift index be0dd0c1..c7db7e61 100644 --- a/bitchat/Views/PublicProfileSheet.swift +++ b/bitchat/Views/PublicProfileSheet.swift @@ -190,7 +190,7 @@ struct PublicProfileSheet: View { ) ThemedCard(spacing: 12) { - Text(String(localized: "public_profile.following.privacy_note", defaultValue: "Stored only in your device Keychain and never published as a public follow list. Mutual mesh favorites with Nostr keys are included automatically.", comment: "Privacy explanation for local-only following list")) + Text(String(localized: "public_profile.following.privacy_note", defaultValue: "Stored only in your device Keychain and never published as a public follow list. Contacts with Nostr keys are included automatically.", comment: "Privacy explanation for local-only following list")) .bitchatFont(size: 12) .foregroundColor(palette.secondary) .fixedSize(horizontal: false, vertical: true) @@ -249,7 +249,7 @@ struct PublicProfileSheet: View { if !followsStore.favoriteFollowPubkeys.isEmpty { Text( String( - format: String(localized: "public_profile.following.favorites_included", defaultValue: "+ %lld favorited mesh peers with Nostr keys", comment: "Caption showing count of favorited mesh peers automatically included in Following"), + format: String(localized: "public_profile.following.favorites_included", defaultValue: "+ %lld contacts with Nostr keys", comment: "Caption showing count of contacts automatically included in Following"), locale: .current, followsStore.favoriteFollowPubkeys.count ) diff --git a/bitchatTests/ChatGroupCoordinatorContextTests.swift b/bitchatTests/ChatGroupCoordinatorContextTests.swift index 309bb47a..24203f7e 100644 --- a/bitchatTests/ChatGroupCoordinatorContextTests.swift +++ b/bitchatTests/ChatGroupCoordinatorContextTests.swift @@ -26,6 +26,7 @@ private final class MockChatGroupContext: ChatGroupContext { var selectedPrivateChatPeer: PeerID? var isAppActive = true let groupStore = GroupStore(keychain: MockKeychain(), persistsToDisk: false) + var groupOutboxStore: GroupOutboxStore? private let identity: TestIdentity @@ -40,22 +41,47 @@ private final class MockChatGroupContext: ChatGroupContext { // Peers: the fingerprint each Noise session authenticated. var fingerprintsByPeerID: [PeerID: String] = [:] + var senderNostrPubkeysByPeerID: [PeerID: String] = [:] + var nostrPubkeyHexByFingerprint: [String: String] = [:] + var ownNostrPubkeyHex: String? var blockedFingerprints: Set = [] + var dmRelayConnected = true func getPeerIDForNickname(_ nickname: String) -> PeerID? { nil } func isPeerConnected(_ peerID: PeerID) -> Bool { false } func peerNickname(for peerID: PeerID) -> String? { nil } func meshFingerprint(for peerID: PeerID) -> String? { fingerprintsByPeerID[peerID] } + func senderNostrPubkeyHex(for peerID: PeerID) -> String? { senderNostrPubkeysByPeerID[peerID] } func cryptoIdentity(for peerID: PeerID) -> (fingerprint: String, signingKey: Data)? { nil } func connectedPeerID(forFingerprint fingerprint: String) -> PeerID? { nil } + func myNostrPubkeyHex() -> String? { ownNostrPubkeyHex } + func nostrPubkeyHex(forFingerprint fingerprint: String) -> String? { nostrPubkeyHexByFingerprint[fingerprint] } func isFingerprintBlocked(_ fingerprint: String) -> Bool { blockedFingerprints.contains(fingerprint) } + func isNostrDMRelayConnected() -> Bool { dmRelayConnected } + + // Transport + private(set) var confirmedNostrSends: [(payload: Data, pubkeyHex: String)] = [] + var confirmedNostrHandler: ((Data, String, @escaping @MainActor (Bool) -> Void) -> Void)? - // Transport (outbound state is not exercised by these tests) func sendGroupInvitePayload(_ payload: Data, to peerID: PeerID) {} func sendGroupKeyUpdatePayload(_ payload: Data, to peerID: PeerID) {} func broadcastGroupMessagePayload(_ payload: Data) {} + func sendGroupMessageViaNostrConfirmed( + _ payload: Data, + toPubkeyHex pubkeyHex: String, + completion: @escaping @MainActor (Bool) -> Void + ) { + confirmedNostrSends.append((payload, pubkeyHex)) + if let handler = confirmedNostrHandler { + handler(payload, pubkeyHex, completion) + } else { + completion(true) + } + } // Conversation intents + private(set) var appendedMessages: [(message: BitchatMessage, peerID: PeerID)] = [] + private(set) var deliveryStatusUpdates: [(messageID: String, status: DeliveryStatus)] = [] private(set) var unreadMarkedPeers: [PeerID] = [] private(set) var notifiedMessages: [(from: String, message: String, peerID: PeerID)] = [] private(set) var removedPrivateChats: [PeerID] = [] @@ -63,7 +89,13 @@ private final class MockChatGroupContext: ChatGroupContext { private(set) var systemMessages: [String] = [] @discardableResult - func appendPrivateMessage(_ message: BitchatMessage, to peerID: PeerID) -> Bool { true } + func appendPrivateMessage(_ message: BitchatMessage, to peerID: PeerID) -> Bool { + appendedMessages.append((message, peerID)) + return true + } + func setPrivateMessageDeliveryStatus(_ status: DeliveryStatus, forMessageID messageID: String) { + deliveryStatusUpdates.append((messageID, status)) + } func markPrivateChatUnread(_ peerID: PeerID) { unreadMarkedPeers.append(peerID) } func removePrivateChat(_ peerID: PeerID) { removedPrivateChats.append(peerID) } func startPrivateChat(with peerID: PeerID) {} @@ -386,4 +418,137 @@ struct ChatGroupCoordinatorContextTests { #expect(context.unreadMarkedPeers.isEmpty) #expect(context.notifiedMessages.isEmpty) } + + // MARK: Hybrid Nostr outbox & routing discovery + + @Test + func offlineGroupSendQueuesDurablyAndFlushesOnNostrReconnect() throws { + let outboxKeychain = MockKeychain() + let outboxURL = FileManager.default.temporaryDirectory + .appendingPathComponent("group-outbox-\(UUID().uuidString).sealed") + defer { try? FileManager.default.removeItem(at: outboxURL) } + + let creatorNostrHex = String(repeating: "11", count: 32) + let memberNostrHex = String(repeating: "22", count: 32) + let context = MockChatGroupContext(identity: me) + context.ownNostrPubkeyHex = String(repeating: "33", count: 32) + context.groupOutboxStore = GroupOutboxStore(keychain: outboxKeychain, persistsToDisk: true, fileURL: outboxURL) + context.dmRelayConnected = false + + var creatorMember = creator.member + creatorMember.nostrPubkeyHex = creatorNostrHex + var otherMember = member.member + otherMember.nostrPubkeyHex = memberNostrHex + + let group = BitchatGroup( + groupID: groupID, + name: "kooks", + epoch: 1, + members: [creatorMember, otherMember, me.member], + creatorFingerprint: creator.fingerprint + ) + #expect(context.groupStore.upsert(group, key: groupKey)) + + let coordinator = ChatGroupCoordinator(context: context) + coordinator.sendGroupMessage("miss you already", to: group.peerID) + + // While offline: local echo starts in `.sending`, nothing sent to relays yet, + // and the entry is persisted to disk. + let echoed = try #require(context.appendedMessages.last?.message) + #expect(echoed.deliveryStatus == .sending) + #expect(context.confirmedNostrSends.isEmpty) + #expect(context.groupOutboxStore?.entries.count == 1) + + // Simulate app restart: reload outbox from encrypted disk store. + let reloadedOutbox = GroupOutboxStore(keychain: outboxKeychain, persistsToDisk: true, fileURL: outboxURL) + #expect(reloadedOutbox.entries.count == 1) + context.groupOutboxStore = reloadedOutbox + + // Relays come online -> flush confirms delivery to both members and advances `.sending` -> `.sent`. + context.dmRelayConnected = true + coordinator.flushPendingNostrDeliveries() + + #expect(Set(context.confirmedNostrSends.map(\.pubkeyHex)) == [creatorNostrHex, memberNostrHex]) + #expect(reloadedOutbox.entries.isEmpty) + #expect(context.deliveryStatusUpdates.contains { $0.messageID == echoed.id && $0.status == .sent }) + + // Sealed payload also carries our own Nostr pubkey for automatic discovery. + let sentPayload = try #require(context.confirmedNostrSends.first?.payload) + let sentEnvelope = try #require(GroupMessageEnvelope.decode(sentPayload)) + let opened = try GroupCrypto.openMessage(sentEnvelope, key: groupKey) + #expect(opened.senderNostrPubkeyHex == context.ownNostrPubkeyHex) + } + + @Test + func incomingGroupMessageLearnsMemberNostrPubkeyAndFlushesQueuedMessages() throws { + let (context, coordinator, joined) = try makeJoinedGroup() + context.groupOutboxStore = GroupOutboxStore(keychain: MockKeychain(), persistsToDisk: false) + context.dmRelayConnected = true + + // Neither creator nor member has a Nostr pubkey yet (BLE-formed group). + coordinator.sendGroupMessage("hello over ble", to: joined.peerID) + #expect(context.confirmedNostrSends.isEmpty) + #expect(context.groupOutboxStore?.entries.count == 1) + + // Member sends a message containing their Nostr pubkey inside the encrypted group payload. + let learnedMemberHex = String(repeating: "aa", count: 32) + let incomingPayload = try GroupCrypto.sealMessage( + content: "hey!", + messageID: "member-hello-1", + senderNickname: member.nickname, + senderSigningKey: member.member.signingKey, + senderNostrPubkeyHex: learnedMemberHex, + timestampMs: UInt64(Date().timeIntervalSince1970 * 1000), + groupID: joined.groupID, + epoch: joined.epoch, + key: groupKey, + sign: member.sign + ) + coordinator.handleGroupMessagePayload(incomingPayload, timestamp: Date()) + + // Roster learned member's Nostr key AND immediately flushed the queued message to them. + let updatedGroup = try #require(context.groupStore.group(withID: joined.groupID)) + let updatedMember = try #require(updatedGroup.members.first { $0.fingerprint == member.fingerprint }) + #expect(updatedMember.nostrPubkeyHex == learnedMemberHex) + #expect(context.confirmedNostrSends.map(\.pubkeyHex) == [learnedMemberHex]) + } + + @Test + func nonFavoriteCreatorNostrKeyUpdateIsAcceptedAndPreservesLearnedRoutes() throws { + let context = MockChatGroupContext(identity: me) + let coordinator = ChatGroupCoordinator(context: context) + let creatorNostrHex = String(repeating: "cc", count: 32) + let learnedMemberHex = String(repeating: "dd", count: 32) + + var creatorMember = creator.member + creatorMember.nostrPubkeyHex = creatorNostrHex + var otherMember = member.member + otherMember.nostrPubkeyHex = learnedMemberHex + + let initialGroup = BitchatGroup( + groupID: groupID, + name: "kooks", + epoch: 1, + members: [creatorMember, otherMember, me.member], + creatorFingerprint: creator.fingerprint + ) + #expect(context.groupStore.upsert(initialGroup, key: groupKey)) + + // Creator sends epoch 2 over Nostr (not in local favorites, so only `senderNostrPubkeyHex` resolves). + let nostrSenderPeerID = PeerID(nostr_: creatorNostrHex) + context.senderNostrPubkeysByPeerID[nostrSenderPeerID] = creatorNostrHex + let rotatedKey = Data(repeating: 0x77, count: 32) + // Incoming state omits `member`'s learned Nostr key — it must be preserved. + let updatePayload = try creatorState( + epoch: 2, + members: [creatorMember, member.member, me.member], + key: rotatedKey + ) + coordinator.handleGroupKeyUpdatePayload(from: nostrSenderPeerID, payload: updatePayload) + + let updated = try #require(context.groupStore.group(withID: groupID)) + #expect(updated.epoch == 2) + #expect(context.groupStore.key(forGroupID: groupID) == rotatedKey) + #expect(updated.members.first(where: { $0.fingerprint == member.fingerprint })?.nostrPubkeyHex == learnedMemberHex) + } } diff --git a/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift b/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift index d60d5f5d..4de78cca 100644 --- a/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift +++ b/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift @@ -151,6 +151,23 @@ private final class MockChatPrivateConversationContext: ChatPrivateConversationC // Nostr identity var blockedNostrPubkeys: Set = [] var displayNamesByPubkey: [String: String] = [:] + var geohashesByGeoDM: [PeerID: String] = [:] + var nostrRelayConnected = true + var myNostrIdentityOverride: NostrIdentity? + var mySigningKeyOverride = Data(repeating: 0x55, count: 32) + private(set) var sentNostrRouteExchanges: [(payload: Data, peerID: PeerID)] = [] + private(set) var storedNostrPeerRoutes: [(noiseKey: Data, nostrPubkey: String, nickname: String)] = [] + + var isNostrRelayConnected: Bool { nostrRelayConnected } + func currentNostrIdentity() -> NostrIdentity? { myNostrIdentityOverride } + func geohashForGeoDM(_ peerID: PeerID) -> String? { geohashesByGeoDM[peerID] } + func mySigningPublicKey() -> Data { mySigningKeyOverride } + func sendNostrRouteExchangePayload(_ payload: Data, to peerID: PeerID) { + sentNostrRouteExchanges.append((payload, peerID)) + } + func storeNostrPeerRoute(noiseKey: Data, nostrPubkey: String, nickname: String) { + storedNostrPeerRoutes.append((noiseKey, nostrPubkey, nickname)) + } func isNostrBlocked(pubkeyHexLowercased: String) -> Bool { blockedNostrPubkeys.contains(pubkeyHexLowercased) @@ -252,12 +269,6 @@ private final class MockChatPrivateConversationContext: ChatPrivateConversationC } // System messages - private(set) var meshOnlySystemMessages: [String] = [] - - func addMeshOnlySystemMessage(_ content: String) { - meshOnlySystemMessages.append(content) - } - private(set) var privateSystemMessages: [(content: String, peerID: PeerID)] = [] func addLocalPrivateSystemMessage(_ content: String, to peerID: PeerID) { @@ -1491,27 +1502,26 @@ struct ChatPrivateConversationCoordinatorContextTests { )) let signedPayload = signedInvite.favoriteAcceptancePayload() - // First signed mesh [FAVORITED] flips theyFavoritedUs and binds the verified npub. + // First signed mesh [FAVORITED] silently flips theyFavoritedUs, binds the + // verified npub, and stores the contact route without noisy chat banners. coordinator.handleFavoriteNotification(signedPayload, from: peerID, senderNickname: "alice") #expect(context.peerFavoritedUsUpdates.count == 1) #expect(context.peerFavoritedUsUpdates.first?.noiseKey == noiseKey) #expect(context.peerFavoritedUsUpdates.first?.favorited == true) #expect(context.peerFavoritedUsUpdates.first?.nostrPublicKey == aliceIdentity.npub) - #expect(context.meshOnlySystemMessages == ["alice favorited you"]) + #expect(context.storedNostrPeerRoutes.count == 1) + #expect(context.storedNostrPeerRoutes.first?.nostrPubkey == aliceIdentity.npub) - // Same state again: store write still happens, but no repeat announcement. + // Repeat state and [UNFAVORITED] update silently without system message spam. context.favoriteRelationshipsByNoiseKey[noiseKey] = makeFavoriteRelationship( noiseKey: noiseKey, theyFavoritedUs: true ) coordinator.handleFavoriteNotification(signedPayload, from: peerID, senderNickname: "alice") #expect(context.peerFavoritedUsUpdates.count == 2) - #expect(context.meshOnlySystemMessages == ["alice favorited you"]) - // [UNFAVORITED] transition announces again. coordinator.handleFavoriteNotification("[UNFAVORITED]", from: peerID, senderNickname: "alice") #expect(context.peerFavoritedUsUpdates.last?.favorited == false) - #expect(context.meshOnlySystemMessages == ["alice favorited you", "alice unfavorited you"]) } @Test @MainActor @@ -1610,7 +1620,6 @@ struct ChatPrivateConversationCoordinatorContextTests { #expect(context.registeredFriendInvites.isEmpty) #expect(context.peerFavoritedUsUpdates.isEmpty) - #expect(context.meshOnlySystemMessages.isEmpty) } @Test @MainActor @@ -1696,8 +1705,8 @@ struct ChatPrivateConversationCoordinatorContextTests { #expect(context.peerFavoritedUsUpdates.first?.noiseKey == noiseKey) #expect(context.peerFavoritedUsUpdates.first?.favorited == true) #expect(context.peerFavoritedUsUpdates.first?.nostrPublicKey == aliceIdentity.npub) + #expect(context.storedNostrPeerRoutes.count == 1) #expect(context.privateChats[convKey, default: []].isEmpty) - #expect(context.meshOnlySystemMessages == ["alice#1234 favorited you"]) } @Test @MainActor @@ -1799,4 +1808,118 @@ struct ChatPrivateConversationCoordinatorContextTests { #expect(context.routedPrivateMessages.map(\.content) == (isGeohash ? [] : [boundaryContent])) #expect(context.geoPrivateMessages.map(\.content) == (isGeohash ? [boundaryContent] : [])) } + + @Test @MainActor + func sendGeohashDM_usesBoundGeohashFromMeshAndQueuesWhileOffline() throws { + let context = MockChatPrivateConversationContext() + let coordinator = ChatPrivateConversationCoordinator(context: context) + let recipientHex = String(repeating: "b", count: 64) + let convKey = PeerID(nostr_: recipientHex) + + // Active public tab is `#mesh`, but this GeoDM thread already knows its geohash. + context.activeChannel = .mesh + context.geohashesByGeoDM[convKey] = "u4pruydq" + context.nostrKeyMapping[convKey] = recipientHex + context.nostrRelayConnected = false + + coordinator.sendGeohashDM("still works from mesh!", to: convKey) + + // Queued (stays `.sending`) instead of failing with "not in location channel" or dropping. + #expect(context.privateChats[convKey]?.count == 1) + #expect(context.privateChats[convKey]?.first?.content == "still works from mesh!") + #expect(context.privateChats[convKey]?.first?.deliveryStatus == .sending) + #expect(context.geoPrivateMessages.isEmpty) + + // Relays come online -> flushes queued GeoDM and advances `.sending` -> `.sent`. + context.nostrRelayConnected = true + coordinator.flushPendingGeohashDMs() + + #expect(context.geoPrivateMessages.map(\.content) == ["still works from mesh!"]) + #expect(context.privateChats[convKey]?.first?.deliveryStatus == .sent) + } + + @Test @MainActor + func mutualBLEDM_autoExchangesSignedNostrRouteAndVerifiesInboundProof() throws { + let context = MockChatPrivateConversationContext() + let coordinator = ChatPrivateConversationCoordinator(context: context) + let myNostr = try NostrIdentity.generate() + let bobNostr = try NostrIdentity.generate() + let bobNoiseKey = Data(repeating: 0x77, count: 32) + let bobSigningKey = Data(repeating: 0x88, count: 32) + let bobShortID = PeerID(publicKey: bobNoiseKey) + + context.myNostrIdentityOverride = myNostr + context.connectedPeers.insert(bobShortID) + context.noiseKeysByPeerID[bobShortID] = bobNoiseKey + context.nicknamesByPeerID[bobShortID] = "bob" + + // 1. Unilateral DM from us -> no route exchange yet (no spam to one-way contacts). + coordinator.sendPrivateMessage("hey bob", to: bobShortID) + #expect(context.sentNostrRouteExchanges.isEmpty) + + // 2. Bob replies over BLE -> mutual conversation consent exists -> we emit signed route exchange. + let bobReply = BitchatMessage( + id: "bob-reply-1", + sender: "bob", + content: "yo!", + timestamp: Date(), + isRelay: false, + isPrivate: true, + recipientNickname: context.nickname, + senderPeerID: bobShortID + ) + coordinator.handlePrivateMessage(bobReply) + #expect(context.sentNostrRouteExchanges.count == 1) + #expect(context.sentNostrRouteExchanges.first?.peerID == bobShortID) + + // 3. Valid signed route exchange from Bob is accepted and stored. + let bobSigned = try #require(FriendInvite.makeSigned( + nickname: "bob", + noisePublicKey: bobNoiseKey, + signingPublicKey: bobSigningKey, + nostrIdentity: bobNostr + )) + let bobPayload = try #require(bobSigned.favoriteAcceptancePayload().data(using: .utf8)) + coordinator.handleNostrRouteExchangePayload(from: bobShortID, payload: bobPayload) + #expect(context.storedNostrPeerRoutes.count == 1) + #expect(context.storedNostrPeerRoutes.first?.noiseKey == bobNoiseKey) + #expect(context.storedNostrPeerRoutes.first?.nostrPubkey == bobNostr.npub) + + // 4. Forged route exchange claiming a mismatched Noise key is rejected. + let wrongNoiseSigned = try #require(FriendInvite.makeSigned( + nickname: "evil", + noisePublicKey: Data(repeating: 0x99, count: 32), + signingPublicKey: bobSigningKey, + nostrIdentity: try NostrIdentity.generate() + )) + let wrongPayload = try #require(wrongNoiseSigned.favoriteAcceptancePayload().data(using: .utf8)) + coordinator.handleNostrRouteExchangePayload(from: bobShortID, payload: wrongPayload) + #expect(context.storedNostrPeerRoutes.count == 1) + } + + @Test @MainActor + func nostrPeerRouteStore_persistsEncryptedAcrossRestartAndBlocksHijack() throws { + let keychain = MockKeychain() + let fileURL = FileManager.default.temporaryDirectory + .appendingPathComponent("nostr-peer-routes-\(UUID().uuidString).sealed") + defer { try? FileManager.default.removeItem(at: fileURL) } + + let aliceNoise = Data(repeating: 0x11, count: 32) + let bobNoise = Data(repeating: 0x22, count: 32) + let aliceNostrHex = String(repeating: "aa", count: 32) + + let store = NostrPeerRouteStore(keychain: keychain, persistsToDisk: true, fileURL: fileURL) + #expect(store.upsert(noisePublicKey: aliceNoise, nostrPubkey: aliceNostrHex, nickname: "alice")) + // Another peer cannot claim Alice's Nostr pubkey. + #expect(!store.upsert(noisePublicKey: bobNoise, nostrPubkey: aliceNostrHex, nickname: "bob")) + + let reloaded = NostrPeerRouteStore(keychain: keychain, persistsToDisk: true, fileURL: fileURL) + #expect(reloaded.nostrPubkeyHex(forNoiseKey: aliceNoise) == aliceNostrHex) + #expect(reloaded.noisePublicKey(forNostrPubkey: aliceNostrHex) == aliceNoise) + #expect(reloaded.nickname(forNoiseKey: aliceNoise) == "alice") + + reloaded.wipe() + #expect(reloaded.routes.isEmpty) + #expect(!FileManager.default.fileExists(atPath: fileURL.path)) + } } diff --git a/bitchatTests/ChatTransportEventCoordinatorContextTests.swift b/bitchatTests/ChatTransportEventCoordinatorContextTests.swift index cf7d0b73..0cc31035 100644 --- a/bitchatTests/ChatTransportEventCoordinatorContextTests.swift +++ b/bitchatTests/ChatTransportEventCoordinatorContextTests.swift @@ -186,6 +186,13 @@ private final class MockChatTransportEventContext: ChatTransportEventContext { func handleVoiceFramePayload(from peerID: PeerID, payload: Data, timestamp: Date) { voiceFramePayloads.append((peerID, payload, timestamp)) } + + // Nostr route exchange payloads + private(set) var nostrRouteExchangePayloads: [(peerID: PeerID, payload: Data)] = [] + + func handleNostrRouteExchangePayload(from peerID: PeerID, payload: Data) { + nostrRouteExchangePayloads.append((peerID, payload)) + } } // MARK: - Helpers @@ -464,11 +471,15 @@ struct ChatTransportEventCoordinatorContextTests { Issue.record("expected .read status") } - // Verification payloads are forwarded untouched. + // Verification and Nostr route exchange payloads are forwarded untouched. coordinator.didReceiveNoisePayloadSynchronously(from: peerID, type: .verifyChallenge, payload: Data([0x01]), timestamp: Date()) coordinator.didReceiveNoisePayloadSynchronously(from: peerID, type: .verifyResponse, payload: Data([0x02]), timestamp: Date()) + coordinator.didReceiveNoisePayloadSynchronously(from: peerID, type: .nostrRouteExchange, payload: Data([0x03]), timestamp: Date()) #expect(context.verifyChallengePayloads.count == 1) #expect(context.verifyResponsePayloads.count == 1) + #expect(context.nostrRouteExchangePayloads.count == 1) + #expect(context.nostrRouteExchangePayloads.first?.peerID == peerID) + #expect(context.nostrRouteExchangePayloads.first?.payload == Data([0x03])) // Blocked peers' private messages are dropped (no handling, no ack). context.blockedPeers = [peerID] diff --git a/bitchatTests/CommandProcessorTests.swift b/bitchatTests/CommandProcessorTests.swift index f01625c5..0dd92bc3 100644 --- a/bitchatTests/CommandProcessorTests.swift +++ b/bitchatTests/CommandProcessorTests.swift @@ -308,11 +308,8 @@ struct CommandProcessorTests { #expect(context.geohashBlockListChangeCount == 2) } - /// /fav must go through toggleFavorite (which persists by the real noise - /// key) — not write the hex peer ID into the favorites store, and not - /// send a second favorite notification. @MainActor - @Test func favoriteCommandTogglesWithoutDirectStoreWrite() async { + @Test func removedFavoriteCommandsAreUnknownAndOmittedFromHelp() async { let identityManager = MockIdentityManager(MockKeychain()) let context = MockCommandContextProvider() let processor = CommandProcessor( @@ -320,71 +317,29 @@ struct CommandProcessorTests { meshService: MockTransport(), identityManager: identityManager ) - let peerID = PeerID(str: "00aa00bb00cc00dd") - context.nicknameToPeerID["alice"] = peerID - let result = await withSelectedChannel(.mesh, context: context) { + let favResult = await withSelectedChannel(.mesh, context: context) { processor.process("/fav alice") } - - switch result { - case .success(let message): - #expect(message == "added alice to favorites") + switch favResult { + case .error(let message): + #expect(message.contains("unknown command")) default: - Issue.record("Expected success result") + Issue.record("Expected unknown command error for removed /fav") } - #expect(context.toggledFavorites == [peerID]) - #expect(context.favoriteNotifications.isEmpty) - // The 8-byte routing ID must never be stored as a "noise key". - let bogusKey = Data(hexString: peerID.id)! - #expect(FavoritesPersistenceService.shared.getFavoriteStatus(for: bogusKey) == nil) - // Unfavoriting someone who is not a favorite is a no-op. let unfavResult = await withSelectedChannel(.mesh, context: context) { processor.process("/unfav alice") } switch unfavResult { - case .success(let message): - #expect(message == "alice is not a favorite") + case .error(let message): + #expect(message.contains("unknown command")) default: - Issue.record("Expected success result") - } - #expect(context.toggledFavorites == [peerID]) - } - - @MainActor - @Test func favoriteCommandSurfacesNotFoundAndAmbiguousOutcomes() async { - let identityManager = MockIdentityManager(MockKeychain()) - let context = MockCommandContextProvider() - let processor = CommandProcessor( - contextProvider: context, - meshService: MockTransport(), - identityManager: identityManager - ) - let peerID = PeerID(str: "00aa00bb00cc00ee") - context.nicknameToPeerID["ghost"] = peerID - - context.toggleFavoriteOutcome = .notFound - let notFoundResult = await withSelectedChannel(.mesh, context: context) { - processor.process("/fav ghost") - } - switch notFoundResult { - case .error(let msg): - #expect(msg.contains("can't find peer")) - default: - Issue.record("Expected error result when toggleFavorite returns .notFound") + Issue.record("Expected unknown command error for removed /unfav") } - context.toggleFavoriteOutcome = .ambiguous - let ambiguousResult = await withSelectedChannel(.mesh, context: context) { - processor.process("/fav ghost") - } - switch ambiguousResult { - case .error(let msg): - #expect(msg.contains("ambiguous")) - default: - Issue.record("Expected error result when toggleFavorite returns .ambiguous") - } + #expect(!CommandProcessor.helpText.contains("/fav")) + #expect(!CommandProcessor.helpText.contains("/unfav")) } @MainActor @@ -429,29 +384,6 @@ struct CommandProcessorTests { #expect(!identityManager.isNostrBlocked(pubkeyHexLowercased: nostrHex)) } - @MainActor - @Test func favoriteCommandIsRejectedOutsideMesh() async { - let identityManager = MockIdentityManager(MockKeychain()) - let context = MockCommandContextProvider() - let processor = CommandProcessor( - contextProvider: context, - meshService: MockTransport(), - identityManager: identityManager - ) - let channel = ChannelID.location(GeohashChannel(level: .city, geohash: "u4pruy")) - - let result = await withSelectedChannel(channel, context: context) { - processor.process("/fav alice") - } - - switch result { - case .error(let message): - #expect(message == "favorites are only for mesh peers in #mesh") - default: - Issue.record("Expected error result") - } - } - // MARK: - /pay @MainActor @@ -709,8 +641,6 @@ private final class MockCommandContextProvider: CommandContextProvider { private(set) var publicSystemMessages: [String] = [] private(set) var commandOutputs: [String] = [] private(set) var commandOutputDestinations: [CommandOutputDestination] = [] - private(set) var toggledFavorites: [PeerID] = [] - private(set) var favoriteNotifications: [(peerID: PeerID, isFavorite: Bool)] = [] private(set) var geohashBlockListChangeCount = 0 init(nickname: String = "tester", idBridge: NostrIdentityBridge = NostrIdentityBridge(keychain: MockKeychain())) { @@ -781,14 +711,6 @@ private final class MockCommandContextProvider: CommandContextProvider { commandOutputDestinations.append(destination) } - var toggleFavoriteOutcome: FavoriteToggleOutcome = .toggled - - @discardableResult - func toggleFavorite(peerID: PeerID) -> FavoriteToggleOutcome { - toggledFavorites.append(peerID) - return toggleFavoriteOutcome - } - // Groups: record the parsed subcommand + argument the processor forwarded. private(set) var groupCommands: [(subcommand: String, argument: String)] = [] diff --git a/bitchatTests/ConversationUIModelTests.swift b/bitchatTests/ConversationUIModelTests.swift index 19672f18..78b64756 100644 --- a/bitchatTests/ConversationUIModelTests.swift +++ b/bitchatTests/ConversationUIModelTests.swift @@ -417,8 +417,9 @@ struct ConversationUIModelTests { uiModel.sendMessage("hi stranger") let sent = try #require(Self.privateRow("hi stranger", with: conversation, of: viewModel)) - // Handed to the Nostr transport, not failed on the way there. - #expect(sent.deliveryStatus == .sent) + // Queued for confirmed Nostr relay delivery while offline in tests, + // not failed on the way there. + #expect(sent.deliveryStatus == .sending) #expect(uiModel.isSentByCurrentUser(sent)) } diff --git a/bitchatTests/GossipSyncManagerTests.swift b/bitchatTests/GossipSyncManagerTests.swift index 8c61d1bf..f34c9c7e 100644 --- a/bitchatTests/GossipSyncManagerTests.swift +++ b/bitchatTests/GossipSyncManagerTests.swift @@ -1182,6 +1182,72 @@ struct GossipSyncManagerTests { #expect(!delegate.packets.isEmpty) } + @Test func groupMessagePacketsPersistInArchiveAndSurvivePublicClear() async throws { + let fileURL = FileManager.default.temporaryDirectory + .appendingPathComponent("gossip-group-archive-\(UUID().uuidString).json") + defer { try? FileManager.default.removeItem(at: fileURL) } + + let nowMs = UInt64(Date().timeIntervalSince1970 * 1000) + let senderID = try #require(Data(hexString: "1122334455667788")) + let publicPacket = BitchatPacket( + type: MessageType.message.rawValue, + senderID: senderID, + recipientID: nil, + timestamp: nowMs, + payload: Data("public hello".utf8), + signature: nil, + ttl: 1 + ) + let groupPacket = BitchatPacket( + type: MessageType.groupMessage.rawValue, + senderID: senderID, + recipientID: nil, + timestamp: nowMs + 1, + payload: Data(repeating: 0x5A, count: 64), + signature: nil, + ttl: 1 + ) + + let writer = GossipSyncManager( + myPeerID: myPeerID, + requestSyncManager: RequestSyncManager(), + archive: GossipMessageArchive(fileURL: fileURL) + ) + writer.onPublicPacketSeen(publicPacket) + writer.onPublicPacketSeen(groupPacket) + writer._performMaintenanceSynchronously(now: Date()) + + // Clearing public mesh history must NOT drop carried encrypted group packets. + writer.removeAllPublicMessages() + writer._performMaintenanceSynchronously(now: Date()) + + var restoredConfig = GossipSyncManager.Config() + restoredConfig.messageSyncIntervalSeconds = 0 + restoredConfig.fragmentSyncIntervalSeconds = 0 + restoredConfig.fileTransferSyncIntervalSeconds = 0 + restoredConfig.prekeyBundleSyncIntervalSeconds = 0 + let restored = GossipSyncManager( + myPeerID: myPeerID, + config: restoredConfig, + requestSyncManager: RequestSyncManager(), + archive: GossipMessageArchive(fileURL: fileURL) + ) + let delegate = RecordingDelegate() + restored.delegate = delegate + restored._performMaintenanceSynchronously(now: Date()) + + let request = RequestSyncPacket(p: 4, m: 1, data: Data(), types: [.groupMessage]) + restored.handleRequestSync(from: PeerID(str: "FFFFFFFFFFFFFFFF"), request: request) + restored._performMaintenanceSynchronously(now: Date()) + + try await TestHelpers.waitFor({ delegate.packets.contains { $0.type == MessageType.groupMessage.rawValue } }, timeout: TestConstants.settleTimeout) + #expect(delegate.packets.contains { PacketIdUtil.computeId($0) == PacketIdUtil.computeId(groupPacket) }) + let echoes = await withCheckedContinuation { continuation in + restored.collectPublicMessagePackets { continuation.resume(returning: $0) } + } + #expect(echoes.isEmpty) + } + } private final class RecordingDelegate: GossipSyncManager.Delegate { diff --git a/bitchatTests/ProtocolContractTests.swift b/bitchatTests/ProtocolContractTests.swift index 46cf64cc..e561add5 100644 --- a/bitchatTests/ProtocolContractTests.swift +++ b/bitchatTests/ProtocolContractTests.swift @@ -43,13 +43,12 @@ struct ProtocolContractTests { #expect(CommandInfo.message.alias == "/msg") #expect(CommandInfo.message.placeholder != nil) #expect(CommandInfo.clear.placeholder == nil) - #expect(CommandInfo.favorite.description.isEmpty == false) + #expect(CommandInfo.ping.description.isEmpty == false) #expect(CommandInfo.all(isGeoPublic: false, isGeoDM: false).contains(.help)) - // Favorites are rejected by the processor in geohash contexts, so - // they are suggested only in mesh. - #expect(CommandInfo.all(isGeoPublic: false, isGeoDM: false).contains(.favorite)) - #expect(CommandInfo.all(isGeoPublic: true, isGeoDM: false).contains(.favorite) == false) - #expect(CommandInfo.all(isGeoPublic: false, isGeoDM: true).contains(.unfavorite) == false) + // Mesh diagnostics and groups are suggested only in mesh. + #expect(CommandInfo.all(isGeoPublic: false, isGeoDM: false).contains(.ping)) + #expect(CommandInfo.all(isGeoPublic: true, isGeoDM: false).contains(.ping) == false) + #expect(CommandInfo.all(isGeoPublic: false, isGeoDM: true).contains(.group) == false) } @Test diff --git a/bitchatTests/Services/GroupProtocolTests.swift b/bitchatTests/Services/GroupProtocolTests.swift index f9f19e7f..a964abd7 100644 --- a/bitchatTests/Services/GroupProtocolTests.swift +++ b/bitchatTests/Services/GroupProtocolTests.swift @@ -371,4 +371,41 @@ struct GroupProtocolTests { ) #expect(atEpoch1 != atEpoch2) } + + @Test func sealedMessageRoundTripsOptionalSenderNostrPubkey() throws { + let nostrHex = String(repeating: "ab", count: 32) + let payloadWithNostr = try GroupCrypto.sealMessage( + content: "hello hybrid", + messageID: "msg-nostr-1", + senderNickname: "alice", + senderSigningKey: creator.member.signingKey, + senderNostrPubkeyHex: nostrHex, + timestampMs: 1_700_000_000_000, + groupID: groupID, + epoch: 1, + key: key, + sign: creator.sign + ) + let envelopeWithNostr = try #require(GroupMessageEnvelope.decode(payloadWithNostr)) + let openedWithNostr = try GroupCrypto.openMessage(envelopeWithNostr, key: key) + #expect(openedWithNostr.content == "hello hybrid") + #expect(openedWithNostr.senderNostrPubkeyHex == nostrHex) + + // Legacy messages without senderNostrPubkey still open cleanly with nil. + let payloadLegacy = try GroupCrypto.sealMessage( + content: "hello legacy", + messageID: "msg-legacy-1", + senderNickname: "alice", + senderSigningKey: creator.member.signingKey, + timestampMs: 1_700_000_000_001, + groupID: groupID, + epoch: 1, + key: key, + sign: creator.sign + ) + let envelopeLegacy = try #require(GroupMessageEnvelope.decode(payloadLegacy)) + let openedLegacy = try GroupCrypto.openMessage(envelopeLegacy, key: key) + #expect(openedLegacy.content == "hello legacy") + #expect(openedLegacy.senderNostrPubkeyHex == nil) + } } diff --git a/bitchatTests/Services/MeshDiagnosticsTests.swift b/bitchatTests/Services/MeshDiagnosticsTests.swift index 8ba6cfbd..e0057095 100644 --- a/bitchatTests/Services/MeshDiagnosticsTests.swift +++ b/bitchatTests/Services/MeshDiagnosticsTests.swift @@ -285,8 +285,6 @@ private final class DiagnosticsMockContext: CommandContextProvider { func groupList() -> CommandResult { .handled } func addLocalPrivateSystemMessage(_ content: String, to peerID: PeerID) {} func addPublicSystemMessage(_ content: String) {} - @discardableResult - func toggleFavorite(peerID: PeerID) -> FavoriteToggleOutcome { .toggled } func currentCommandDestination() -> CommandOutputDestination { if let peerID = selectedPrivateChatPeer { diff --git a/bitchatTests/Services/MessageRouterTests.swift b/bitchatTests/Services/MessageRouterTests.swift index 47752aba..94b3b49c 100644 --- a/bitchatTests/Services/MessageRouterTests.swift +++ b/bitchatTests/Services/MessageRouterTests.swift @@ -5,6 +5,7 @@ // Tests for MessageRouter transport selection and outbox behavior. // +import Combine import Testing import Foundation import BitFoundation @@ -1547,6 +1548,89 @@ struct MessageRouterTests { #expect(router.sendReadReceipt(receipt, to: peerID) == true) #expect(nostr.sentReadReceipts.map(\.receipt.originalMessageID) == ["rr-offline"]) } + + @Test @MainActor + func sendFavoriteNotification_queuesOfflineAndFlushesOnReconnect() { + let peerID = PeerID(str: "00000000000000f6") + let ble = MockTransport() + let router = MessageRouter(transports: [ble]) + + // Offline: notification is queued instead of silently dropped. + router.sendFavoriteNotification(to: peerID, isFavorite: true) + #expect(ble.sentFavoriteNotifications.isEmpty) + + // Peer connects on BLE -> flush delivers the queued [FAVORITED] marker. + ble.connectedPeers.insert(peerID) + router.flushOutbox(for: peerID) + #expect(ble.sentFavoriteNotifications.count == 1) + #expect(ble.sentFavoriteNotifications.first?.peerID == peerID) + #expect(ble.sentFavoriteNotifications.first?.isFavorite == true) + + // Subsequent flush does not re-send. + router.flushOutbox(for: peerID) + #expect(ble.sentFavoriteNotifications.count == 1) + } + + @Test @MainActor + func nostrUnconfirmedPrivateMessage_retriesUntilRelayOKAndDoesNotSpamAfterOK() async throws { + let peerNoiseKey = Data(repeating: 0xAA, count: 32) + let peerID = PeerID(hexData: peerNoiseKey) + let peerShortID = PeerID(publicKey: peerNoiseKey) + let peerIdentity = try NostrIdentity.generate() + let senderIdentity = try NostrIdentity.generate() + let relaySubject = CurrentValueSubject(true) + + var relayAccepts = false + var sendAttempts = 0 + let nostr = NostrTransport( + keychain: MockKeychain(), + idBridge: NostrIdentityBridge(keychain: MockKeychain()), + dependencies: NostrTransport.Dependencies( + notificationCenter: NotificationCenter(), + loadFavorites: { [:] }, + favoriteStatusForNoiseKey: { _ in nil }, + favoriteStatusForPeerID: { _ in nil }, + currentIdentity: { senderIdentity }, + registerPendingGiftWrap: { _ in }, + sendEvent: { _ in }, + sendEventImmediately: { _, completion in + sendAttempts += 1 + completion(relayAccepts) + }, + scheduleAfter: { _, _ in }, + relayConnectivity: { relaySubject.eraseToAnyPublisher() } + ) + ) + // Supplemental route (e.g. learned from mutual DM or shared group, no favorite required). + nostr.updateAdditionalNostrRoutes([peerID: peerIdentity.publicKeyHex]) + #expect(nostr.isPeerReachable(peerID)) + #expect(nostr.isPeerReachable(peerShortID)) + + let router = MessageRouter(transports: [nostr]) + var sentMessageIDs: [String] = [] + router.onMessageSent = { id, _ in sentMessageIDs.append(id) } + nostr.onPrivateMessageSendResult = { id, peer, accepted in + router.handleNostrPrivateMessageSendResult(messageID: id, peerID: peer, accepted: accepted) + } + + // First send: relay rejects -> does NOT fire onMessageSent. + router.sendPrivate("hey there", to: peerID, recipientNickname: "Bob", messageID: "nostr-confirm-1") + let firstAttempted = await TestHelpers.waitUntil({ sendAttempts == 1 }, timeout: TestConstants.settleTimeout) + #expect(firstAttempted) + #expect(sentMessageIDs.isEmpty) + + // Relay comes healthy -> retryUnconfirmedNostrMessages retries and confirms OK -> fires onMessageSent. + relayAccepts = true + router.retryUnconfirmedNostrMessages() + let secondAttempted = await TestHelpers.waitUntil({ sentMessageIDs == ["nostr-confirm-1"] }, timeout: TestConstants.settleTimeout) + #expect(secondAttempted) + #expect(sendAttempts == 2) + + // Already confirmed by relay: subsequent retry sweeps must NOT re-spam relays. + router.retryUnconfirmedNostrMessages() + try await Task.sleep(nanoseconds: 50_000_000) + #expect(sendAttempts == 2) + } } /// Mutable wall clock injected into `MessageRouter` so TTL expiry is testable diff --git a/bitchatTests/Services/NetworkActivationServiceTests.swift b/bitchatTests/Services/NetworkActivationServiceTests.swift index e4ef5880..28947aea 100644 --- a/bitchatTests/Services/NetworkActivationServiceTests.swift +++ b/bitchatTests/Services/NetworkActivationServiceTests.swift @@ -213,6 +213,21 @@ final class NetworkActivationServiceTests: XCTestCase { XCTAssertEqual(context.relayController.connectCallCount, 1) } + func test_hasNostrGroups_enablesNetworkWithoutPermissionOrMutualFavorites() { + let context = makeService(permission: .denied, favorites: [], torEnabled: true) + + context.service.start() + XCTAssertFalse(context.service.activationAllowed) + + context.service.setHasNostrGroups(true) + XCTAssertTrue(context.service.activationAllowed) + XCTAssertEqual(context.torController.startIfNeededCallCount, 1) + XCTAssertEqual(context.relayController.connectCallCount, 1) + + context.service.stopForPanic() + XCTAssertFalse(context.service.hasNostrGroups) + } + func test_selectedChannelPublisher_activatesOnEnteringALocationChannel() async { let channelSubject = CurrentValueSubject(.mesh) let context = makeService( diff --git a/bitchatTests/Services/NostrTransportTests.swift b/bitchatTests/Services/NostrTransportTests.swift index 8e453bee..d587c36c 100644 --- a/bitchatTests/Services/NostrTransportTests.swift +++ b/bitchatTests/Services/NostrTransportTests.swift @@ -220,6 +220,75 @@ struct NostrTransportTests { #expect(probe.pendingGiftWrapIDs.isEmpty) } + @Test("Additional Nostr routes make non-favorite peers reachable and report relay OK") + @MainActor + func additionalNostrRoutesEnableNonFavoritePrivateMessagesAndReportRelayOK() async throws { + let keychain = MockKeychain() + let idBridge = NostrIdentityBridge(keychain: keychain) + let sender = try NostrIdentity.generate() + let recipient = try NostrIdentity.generate() + let noiseKey = Data((128..<160).map(UInt8.init)) + let fullPeerID = PeerID(hexData: noiseKey) + let shortPeerID = fullPeerID.toShort() + let probe = NostrTransportProbe() + var relayShouldAccept = false + var results: [(String, PeerID, Bool)] = [] + + let transport = NostrTransport( + keychain: keychain, + idBridge: idBridge, + dependencies: NostrTransport.Dependencies( + notificationCenter: NotificationCenter(), + loadFavorites: { [:] }, + favoriteStatusForNoiseKey: { _ in nil }, + favoriteStatusForPeerID: { _ in nil }, + currentIdentity: { sender }, + registerPendingGiftWrap: probe.recordPendingGiftWrap(id:), + sendEvent: probe.record(event:), + sendEventImmediately: { event, completion in + probe.record(event: event) + completion(relayShouldAccept) + }, + scheduleAfter: { delay, action in + probe.enqueueScheduledAction(delay: delay, action: action) + }, + relayConnectivity: { Just(true).eraseToAnyPublisher() } + ) + ) + transport.senderPeerID = PeerID(str: "0123456789abcdef") + transport.onPrivateMessageSendResult = { messageID, peerID, accepted in + results.append((messageID, peerID, accepted)) + } + + #expect(!transport.isPeerReachable(shortPeerID)) + #expect(!transport.isPeerReachable(fullPeerID)) + + // Learn route via mutual DM / shared private group (no favorite entry). + transport.updateAdditionalNostrRoutes([fullPeerID: recipient.publicKeyHex]) + #expect(transport.isPeerReachable(fullPeerID)) + #expect(transport.isPeerReachable(shortPeerID)) + + // First attempt rejected by relays -> callback reports accepted == false. + transport.sendPrivateMessage("retry me", to: shortPeerID, recipientNickname: "Eve", messageID: "pm-retry") + let firstReported = await TestHelpers.waitUntil({ results.count == 1 }, timeout: TestConstants.settleTimeout) + #expect(firstReported) + #expect(results[0].0 == "pm-retry") + #expect(results[0].1 == shortPeerID) + #expect(results[0].2 == false) + + // Second attempt accepted by relays -> callback reports accepted == true and decrypts cleanly. + relayShouldAccept = true + transport.sendPrivateMessage("retry me", to: shortPeerID, recipientNickname: "Eve", messageID: "pm-retry") + let secondReported = await TestHelpers.waitUntil({ results.count == 2 }, timeout: TestConstants.settleTimeout) + #expect(secondReported) + #expect(results[1].2 == true) + + let decoded = try decodeEmbeddedPayload(from: probe.sentEvents[1], recipient: recipient) + let privateMessage = try decodePrivateMessage(from: decoded.payload) + #expect(privateMessage.messageID == "pm-retry") + #expect(privateMessage.content == "retry me") + } + @Test("Favorite notification embeds current npub") @MainActor func sendFavoriteNotificationEmbedsCurrentIdentity() async throws { diff --git a/bitchatTests/Services/UnifiedPeerServiceTests.swift b/bitchatTests/Services/UnifiedPeerServiceTests.swift index b8cf184c..9f7ca271 100644 --- a/bitchatTests/Services/UnifiedPeerServiceTests.swift +++ b/bitchatTests/Services/UnifiedPeerServiceTests.swift @@ -206,6 +206,59 @@ struct UnifiedPeerServiceTests { #expect(rows.first?.isMutualFavorite == true) } + @Test @MainActor + func contactsUnification_learnedNostrRoutePowersOfflinePeerFollowsAndWoTWithoutFavorite() async throws { + let transport = MockTransport() + let identity = TestIdentityManager() + let service = UnifiedPeerService(meshService: transport, identityManager: identity) + let routeStore = NostrPeerRouteStore(keychain: MockKeychain(), persistsToDisk: false) + service.configureNostrPeerRouteStore(routeStore) + + let noiseKey = Data(repeating: 0x5A, count: 32) + let fingerprint = noiseKey.sha256Fingerprint() + let nostrID = try NostrIdentity.generate() + let nostrHex = nostrID.publicKeyHex.lowercased() + + // Learn route via mutual DM without any favorite relationship. + #expect(routeStore.upsert(noisePublicKey: noiseKey, nostrPubkey: nostrID.npub, nickname: "erin")) + transport.updatePeerSnapshots([]) + service.didUpdatePeerSnapshots([]) + + let offlineRows = service.peers.filter { $0.noisePublicKey == noiseKey } + #expect(offlineRows.count == 1) + #expect(offlineRows.first?.peerID == PeerID(hexData: noiseKey)) + #expect(offlineRows.first?.connectionState == .nostrAvailable) + #expect(offlineRows.first?.isFavorite == false) + + // When Erin returns on BLE mesh, the offline contact collapses into one live mesh row. + let meshID = PeerID(publicKey: noiseKey) + let snapshots = [TransportPeerSnapshot( + peerID: meshID, + nickname: "erin", + isConnected: true, + noisePublicKey: noiseKey, + lastSeen: Date() + )] + transport.updatePeerSnapshots(snapshots) + service.didUpdatePeerSnapshots(snapshots) + let liveRows = service.peers.filter { $0.noisePublicKey == noiseKey } + #expect(liveRows.count == 1) + #expect(liveRows.first?.peerID == meshID) + #expect(liveRows.first?.connectionState == .bluetoothConnected) + #expect(liveRows.first?.hasDirectNostrRoute == true) + + // Feed follows automatically include learned contact routes without a favorite. + let followsStore = NostrFollowsStore(keychain: MockKeychain(), favoritesProvider: { [] }) + followsStore.configureContactRoutesStore(routeStore) + #expect(followsStore.isFollowing(nostrHex)) + #expect(followsStore.localAlias(for: nostrHex) == "erin") + + // Local Web of Trust resolves verified status via learned contact routes without a favorite. + identity.setVerified(fingerprint: fingerprint, verified: true) + let wot = LocalWebOfTrustService(identityManager: identity, nostrPeerRouteStore: routeStore) + #expect(wot.trust(forNostrPubkey: nostrHex) == .verified) + } + @Test @MainActor func setBlocked_unknownIdentityReturnsNil() async { let transport = MockTransport() diff --git a/bitchatTests/ViewSmokeTests.swift b/bitchatTests/ViewSmokeTests.swift index c8d79eee..76c3d9e6 100644 --- a/bitchatTests/ViewSmokeTests.swift +++ b/bitchatTests/ViewSmokeTests.swift @@ -320,14 +320,12 @@ struct ViewSmokeTests { _ = mount( MeshPeerList( onTapPeer: { _ in }, - onToggleFavorite: { _ in }, onShowFingerprint: { _ in } ) .environmentObject(featureModels.peerListModel) ) _ = MeshPeerList( onTapPeer: { _ in }, - onToggleFavorite: { _ in }, onShowFingerprint: { _ in } ) .environmentObject(featureModels.peerListModel) @@ -344,7 +342,6 @@ struct ViewSmokeTests { _ = mount( MeshPeerList( onTapPeer: { _ in }, - onToggleFavorite: { _ in }, onShowFingerprint: { _ in } ) .environmentObject(featureModels.peerListModel)