From 03861ed9ad5267612f4d7841f325b800b4c74347 Mon Sep 17 00:00:00 2001 From: Taksh Date: Thu, 5 Nov 2026 12:45:09 +0530 Subject: [PATCH 1/4] Fail private messages that do not fit the 255-byte wire limit The content TLV is one byte. Encode was returning nil and the bubble stayed on sending, including when /pay handed over a long cashu token. --- bitchat/Protocols/Packets.swift | 9 ++++- bitchat/Services/BLE/BLEService.swift | 18 +++++++++- bitchat/Services/CommandProcessor.swift | 3 ++ bitchat/Services/NostrTransport.swift | 17 ++++++++++ bitchatTests/CommandProcessorTests.swift | 33 +++++++++++++++++++ .../PacketPayloadCapInteropTests.swift | 16 +++++++++ 6 files changed, 94 insertions(+), 2 deletions(-) diff --git a/bitchat/Protocols/Packets.swift b/bitchat/Protocols/Packets.swift index d45f7323..0c1a2446 100644 --- a/bitchat/Protocols/Packets.swift +++ b/bitchat/Protocols/Packets.swift @@ -240,6 +240,13 @@ struct AuthenticatedPeerStatePacket: Equatable { } struct PrivateMessagePacket { + /// Content TLV length is one byte. Longer private messages cannot be encoded. + static let maxContentUTF8Bytes = 255 + + static func contentFitsOnWire(_ content: String) -> Bool { + content.utf8.count <= maxContentUTF8Bytes + } + let messageID: String let content: String @@ -259,7 +266,7 @@ struct PrivateMessagePacket { data.append(messageIDData) // TLV for content - guard let contentData = content.data(using: .utf8), contentData.count <= 255 else { return nil } + guard let contentData = content.data(using: .utf8), contentData.count <= Self.maxContentUTF8Bytes else { return nil } data.append(TLVType.content.rawValue) data.append(UInt8(contentData.count)) data.append(contentData) diff --git a/bitchat/Services/BLE/BLEService.swift b/bitchat/Services/BLE/BLEService.swift index a07e5d31..a5aadbce 100644 --- a/bitchat/Services/BLE/BLEService.swift +++ b/bitchat/Services/BLE/BLEService.swift @@ -5245,6 +5245,17 @@ extension BLEService { let recipientID = recipientID.toShort() SecureLogger.debug("📨 Sending PM to \(recipientID.id.prefix(8))… id=\(messageID.prefix(8))… chars=\(content.count) bytes=\(content.utf8.count)", category: .session) + guard PrivateMessagePacket.contentFitsOnWire(content) else { + SecureLogger.error("Private message is \(content.utf8.count) UTF-8 bytes; the wire limit is \(PrivateMessagePacket.maxContentUTF8Bytes)", category: .session) + notifyUI { [weak self] in + self?.deliverTransportEvent(.messageDeliveryStatusUpdated( + messageID: messageID, + status: .failed(reason: String(localized: "content.delivery.reason.send_error", comment: "Failure reason for a generic send error")) + )) + } + return + } + // Check if we have an established Noise session if noiseService.hasEstablishedSession(with: recipientID) { // Encrypt and send @@ -5375,7 +5386,12 @@ extension BLEService { // Use the same TLV format as normal sends to keep receiver decoding consistent guard let messagePayload = BLENoisePayloadFactory.privateMessage(content: message.content, messageID: message.messageID) else { SecureLogger.error("Failed to encode pending private message TLV") - failedMessages.append(message) + notifyUI { [weak self] in + self?.deliverTransportEvent(.messageDeliveryStatusUpdated( + messageID: message.messageID, + status: .failed(reason: String(localized: "content.delivery.reason.send_error", comment: "Failure reason for a generic send error")) + )) + } continue } diff --git a/bitchat/Services/CommandProcessor.swift b/bitchat/Services/CommandProcessor.swift index 7b8d1bf2..11aa5e4e 100644 --- a/bitchat/Services/CommandProcessor.swift +++ b/bitchat/Services/CommandProcessor.swift @@ -530,6 +530,9 @@ final class CommandProcessor { let summary = info.displayAmount ?? "a cashu token" if let peerID = contextProvider?.selectedPrivateChatPeer { + guard PrivateMessagePacket.contentFitsOnWire(token) else { + return .error(message: String(localized: "content.delivery.reason.send_error", defaultValue: "send error", comment: "Failure reason for a generic send error")) + } contextProvider?.sendPrivateMessage(token, to: peerID) return .success(message: String(format: String(localized: "command.pay.sent_private", defaultValue: "sent %@ — cashu is a bearer token; whoever redeems it first gets the funds", comment: "Confirmation after sending a cashu token in a private chat; placeholder is the amount summary"), locale: .current, summary)) } diff --git a/bitchat/Services/NostrTransport.swift b/bitchat/Services/NostrTransport.swift index 10f51219..1f5dead9 100644 --- a/bitchat/Services/NostrTransport.swift +++ b/bitchat/Services/NostrTransport.swift @@ -260,6 +260,7 @@ final class NostrTransport: Transport, @unchecked Sendable { 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) + reportPrivateMessageSendFailure(messageID) return } sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: senderIdentity) @@ -318,6 +319,7 @@ extension NostrTransport { SecureLogger.debug("GeoDM: send 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) + reportPrivateMessageSendFailure(messageID) return } sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true) @@ -328,6 +330,21 @@ extension NostrTransport { // MARK: - Private Helpers extension NostrTransport { + /// A private message that cannot be embedded never leaves, so the bubble + /// must leave "sending". Same reason string the mesh path uses. + @MainActor + fileprivate func reportPrivateMessageSendFailure(_ messageID: String) { + let event = TransportEvent.messageDeliveryStatusUpdated( + messageID: messageID, + status: .failed(reason: String(localized: "content.delivery.reason.send_error", comment: "Failure reason for a generic send error")) + ) + if let eventDelegate { + eventDelegate.didReceiveTransportEvent(event) + } else { + delegate?.receiveTransportEvent(event) + } + } + /// Converts npub bech32 string to hex pubkey @MainActor private func npubToHex(_ npub: String) -> String? { diff --git a/bitchatTests/CommandProcessorTests.swift b/bitchatTests/CommandProcessorTests.swift index 183dcccb..2ea4db20 100644 --- a/bitchatTests/CommandProcessorTests.swift +++ b/bitchatTests/CommandProcessorTests.swift @@ -486,6 +486,23 @@ struct CommandProcessorTests { #expect(context.sentPrivateMessages.first?.content == Self.validV4Token) } + @MainActor + @Test func payRefusesAPrivateTokenThatDoesNotFitTheWire() { + let context = MockCommandContextProvider() + context.selectedPrivateChatPeer = PeerID(str: "abcd1234abcd1234") + let processor = makePayProcessor(context: context) + let token = Self.cashuV3Token(mint: "https://mint.example.com/" + String(repeating: "a", count: 240)) + #expect(token.utf8.count > PrivateMessagePacket.maxContentUTF8Bytes) + + switch processor.process("/pay \(token)") { + case .error(let message): + #expect(message == "send error") + default: + Issue.record("Expected the oversized token to be refused") + } + #expect(context.sentPrivateMessages.isEmpty) + } + /// 21-sat single-mint V3 token (proofs of 1+4+16). private static let validV3Token: String = { let json: [String: Any] = [ @@ -503,6 +520,22 @@ struct CommandProcessorTests { return "cashuA" + b64 }() + private static func cashuV3Token(mint: String) -> String { + let json: [String: Any] = [ + "token": [[ + "mint": mint, + "proofs": [1, 4, 16].map { ["amount": $0, "id": "009a1f293253e41e", "secret": "s", "C": "02c"] } + ]], + "unit": "sat" + ] + let data = try! JSONSerialization.data(withJSONObject: json) + let b64 = data.base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") + return "cashuA" + b64 + } + /// 21-sat single-mint definite-length V4 (CBOR) token (proofs of 1+4+16). private static let validV4Token: String = { func head(_ major: UInt8, _ value: UInt64) -> [UInt8] { diff --git a/bitchatTests/Protocols/PacketPayloadCapInteropTests.swift b/bitchatTests/Protocols/PacketPayloadCapInteropTests.swift index d55256be..4e4b9cba 100644 --- a/bitchatTests/Protocols/PacketPayloadCapInteropTests.swift +++ b/bitchatTests/Protocols/PacketPayloadCapInteropTests.swift @@ -35,6 +35,22 @@ struct PacketPayloadCapInteropTests { #expect(BinaryProtocol.decode(try inflatedFrame(type: .message)) == nil) } + @Test func privateMessageOver255UTF8BytesDoesNotEncode() { + let within = String(repeating: "é", count: 127) + #expect(within.utf8.count == 254) + #expect(PrivateMessagePacket.contentFitsOnWire(within)) + #expect(PrivateMessagePacket(messageID: "m", content: within).encode() != nil) + + let over = String(repeating: "é", count: 128) + #expect(over.utf8.count == 256) + #expect(PrivateMessagePacket.contentFitsOnWire(over) == false) + #expect(PrivateMessagePacket(messageID: "m", content: over).encode() == nil) + + let ascii = String(repeating: "x", count: PrivateMessagePacket.maxContentUTF8Bytes) + #expect(PrivateMessagePacket(messageID: "m", content: ascii).encode() != nil) + #expect(PrivateMessagePacket(messageID: "m", content: ascii + "y").encode() == nil) + } + @Test func androidAndIOSSizedFragmentsStillDecode() throws { // Every byte value once, then zeros: the inner packet stays // uncompressed (its bytes are 100% unique) while the zero-filled From b00939b03d4eee2552397eb42267e7951f9ebd36 Mon Sep 17 00:00:00 2001 From: Taksh Date: Sat, 7 Nov 2026 17:03:24 +0530 Subject: [PATCH 2/4] Reject oversized private messages before routing Mark oversized mesh and geohash DMs as failed before handing them to a transport. Keep the private payment success fixture within the wire limit. --- bitchat/Services/NostrTransport.swift | 17 ----------- .../ChatPrivateConversationCoordinator.swift | 15 ++++++++-- ...eConversationCoordinatorContextTests.swift | 24 ++++++++++++++++ bitchatTests/CommandProcessorTests.swift | 28 ++++++------------- 4 files changed, 45 insertions(+), 39 deletions(-) diff --git a/bitchat/Services/NostrTransport.swift b/bitchat/Services/NostrTransport.swift index 1f5dead9..10f51219 100644 --- a/bitchat/Services/NostrTransport.swift +++ b/bitchat/Services/NostrTransport.swift @@ -260,7 +260,6 @@ final class NostrTransport: Transport, @unchecked Sendable { 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) - reportPrivateMessageSendFailure(messageID) return } sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: senderIdentity) @@ -319,7 +318,6 @@ extension NostrTransport { SecureLogger.debug("GeoDM: send 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) - reportPrivateMessageSendFailure(messageID) return } sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true) @@ -330,21 +328,6 @@ extension NostrTransport { // MARK: - Private Helpers extension NostrTransport { - /// A private message that cannot be embedded never leaves, so the bubble - /// must leave "sending". Same reason string the mesh path uses. - @MainActor - fileprivate func reportPrivateMessageSendFailure(_ messageID: String) { - let event = TransportEvent.messageDeliveryStatusUpdated( - messageID: messageID, - status: .failed(reason: String(localized: "content.delivery.reason.send_error", comment: "Failure reason for a generic send error")) - ) - if let eventDelegate { - eventDelegate.didReceiveTransportEvent(event) - } else { - delegate?.receiveTransportEvent(event) - } - } - /// Converts npub bech32 string to hex pubkey @MainActor private func npubToHex(_ npub: String) -> String? { diff --git a/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift b/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift index 0db255f0..529021dd 100644 --- a/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift +++ b/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift @@ -355,6 +355,7 @@ final class ChatPrivateConversationCoordinator { ?? "anon" let messageID = UUID().uuidString + let status = initialDeliveryStatus(for: content) let message = BitchatMessage( id: messageID, sender: context.nickname, @@ -366,11 +367,12 @@ final class ChatPrivateConversationCoordinator { recipientNickname: recipientNickname, senderPeerID: context.myPeerID, mentions: nil, - deliveryStatus: .sending + deliveryStatus: status ) context.appendPrivateMessage(message, to: peerID) context.notifyUIChanged() + guard status == .sending else { return } // Always hand the message to the router — it owns delivery. A live // link sends now; an unreachable peer gets the retained-outbox path @@ -393,6 +395,13 @@ final class ChatPrivateConversationCoordinator { // acks, or failed when the outbox TTL expires. } + private func initialDeliveryStatus(for content: String) -> DeliveryStatus { + guard PrivateMessagePacket.contentFitsOnWire(content) else { + return .failed(reason: String(localized: "content.delivery.reason.send_error", comment: "Failure reason for a generic send error")) + } + return .sending + } + func sendGeohashDM(_ content: String, to peerID: PeerID) { guard case .location(let channel) = context.activeChannel else { // The failure happened inside a geoDM thread — surface it there, @@ -406,6 +415,7 @@ final class ChatPrivateConversationCoordinator { } let messageID = UUID().uuidString + let status = initialDeliveryStatus(for: content) let message = BitchatMessage( id: messageID, sender: context.nickname, @@ -415,11 +425,12 @@ final class ChatPrivateConversationCoordinator { isPrivate: true, recipientNickname: context.nickname, senderPeerID: context.myPeerID, - deliveryStatus: .sending + deliveryStatus: status ) context.appendPrivateMessage(message, to: peerID) context.notifyUIChanged() + guard status == .sending else { return } guard let recipientHex = context.nostrKeyMapping[peerID] else { context.setPrivateDeliveryStatus( diff --git a/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift b/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift index 66d32d46..15aa73d1 100644 --- a/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift +++ b/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift @@ -1233,4 +1233,28 @@ struct ChatPrivateConversationCoordinatorContextTests { #expect(context.routedPrivateMessages.map(\.content) == ["hello?"]) #expect(context.privateChats[peerID]?.first?.deliveryStatus == .sending) } + + @Test(arguments: [false, true]) @MainActor + func oversizedPrivateMessageFailsWithoutRouting(isGeohash: Bool) { + let context = MockChatPrivateConversationContext() + let coordinator = ChatPrivateConversationCoordinator(context: context) + let peerID: PeerID + if isGeohash { + let pubkey = String(repeating: "a", count: 64) + peerID = PeerID(str: "nostr_" + String(pubkey.prefix(16))) + context.activeChannel = .location(GeohashChannel(level: .region, geohash: "0000")) + context.nostrKeyMapping[peerID] = pubkey + } else { + // An unreachable mesh peer would normally cause the router to retain the message. + peerID = PeerID(str: "abcd1234abcd1234") + } + + let content = String(repeating: "é", count: 128) + coordinator.sendPrivateMessage(content, to: peerID) + + #expect(context.privateChats[peerID]?.map(\.content) == [content]) + #expect(context.privateChats[peerID]?.first?.deliveryStatus == .failed(reason: "send error")) + #expect(context.routedPrivateMessages.isEmpty) + #expect(context.geoPrivateMessages.isEmpty) + } } diff --git a/bitchatTests/CommandProcessorTests.swift b/bitchatTests/CommandProcessorTests.swift index 2ea4db20..97ce6da0 100644 --- a/bitchatTests/CommandProcessorTests.swift +++ b/bitchatTests/CommandProcessorTests.swift @@ -410,16 +410,18 @@ struct CommandProcessorTests { let peerID = PeerID(str: "abcd1234abcd1234") context.selectedPrivateChatPeer = peerID let processor = makePayProcessor(context: context) + let token = Self.cashuV3Token(mint: "https://mint.example.com", amounts: [16]) + #expect(token.utf8.count <= PrivateMessagePacket.maxContentUTF8Bytes) // cashu: URI form must be normalized to the bare token before sending - switch processor.process("/pay cashu:\(Self.validV3Token)") { + switch processor.process("/pay cashu:\(token)") { case .success(let message): - #expect(message?.contains("21 sat") == true) + #expect(message?.contains("16 sat") == true) default: Issue.record("Expected success result") } #expect(context.sentPrivateMessages.count == 1) - #expect(context.sentPrivateMessages.first?.content == Self.validV3Token) + #expect(context.sentPrivateMessages.first?.content == token) #expect(context.sentPrivateMessages.first?.peerID == peerID) #expect(context.sentPublicMessages.isEmpty) } @@ -504,27 +506,13 @@ struct CommandProcessorTests { } /// 21-sat single-mint V3 token (proofs of 1+4+16). - private static let validV3Token: String = { - let json: [String: Any] = [ - "token": [[ - "mint": "https://mint.example.com", - "proofs": [1, 4, 16].map { ["amount": $0, "id": "009a1f293253e41e", "secret": "s", "C": "02c"] } - ]], - "unit": "sat" - ] - let data = try! JSONSerialization.data(withJSONObject: json) - let b64 = data.base64EncodedString() - .replacingOccurrences(of: "+", with: "-") - .replacingOccurrences(of: "/", with: "_") - .replacingOccurrences(of: "=", with: "") - return "cashuA" + b64 - }() + private static let validV3Token = cashuV3Token(mint: "https://mint.example.com") - private static func cashuV3Token(mint: String) -> String { + private static func cashuV3Token(mint: String, amounts: [Int] = [1, 4, 16]) -> String { let json: [String: Any] = [ "token": [[ "mint": mint, - "proofs": [1, 4, 16].map { ["amount": $0, "id": "009a1f293253e41e", "secret": "s", "C": "02c"] } + "proofs": amounts.map { ["amount": $0, "id": "009a1f293253e41e", "secret": "s", "C": "02c"] } ]], "unit": "sat" ] From 8a388eaf419f63a8fd29344d32598482c3dc4002 Mon Sep 17 00:00:00 2001 From: Taksh Date: Sat, 7 Nov 2026 17:10:39 +0530 Subject: [PATCH 3/4] Check oversized DM failure independently of localization Assert the delivery state so the regression test passes with or without the app's localized strings available to the test runner. --- .../ChatPrivateConversationCoordinatorContextTests.swift | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift b/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift index 15aa73d1..b31a06d1 100644 --- a/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift +++ b/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift @@ -1253,7 +1253,10 @@ struct ChatPrivateConversationCoordinatorContextTests { coordinator.sendPrivateMessage(content, to: peerID) #expect(context.privateChats[peerID]?.map(\.content) == [content]) - #expect(context.privateChats[peerID]?.first?.deliveryStatus == .failed(reason: "send error")) + guard case .failed? = context.privateChats[peerID]?.first?.deliveryStatus else { + Issue.record("Expected oversized content to fail delivery") + return + } #expect(context.routedPrivateMessages.isEmpty) #expect(context.geoPrivateMessages.isEmpty) } From 3eb2df004edf7668a7d3a54d467e1fc580084603 Mon Sep 17 00:00:00 2001 From: Taksh Date: Fri, 13 Nov 2026 15:50:11 +0530 Subject: [PATCH 4/4] Explain oversized private-message failures --- bitchat/Localizable.xcstrings | 186 ++++++++++++++++++ bitchat/Services/CommandProcessor.swift | 2 +- .../ChatPrivateConversationCoordinator.swift | 2 +- ...eConversationCoordinatorContextTests.swift | 17 +- bitchatTests/CommandProcessorTests.swift | 8 +- 5 files changed, 206 insertions(+), 9 deletions(-) diff --git a/bitchat/Localizable.xcstrings b/bitchat/Localizable.xcstrings index 601d5b6a..80728504 100644 --- a/bitchat/Localizable.xcstrings +++ b/bitchat/Localizable.xcstrings @@ -52221,6 +52221,192 @@ } } }, + "content.delivery.reason.too_long" : { + "comment" : "Failure reason when a private message exceeds the wire size limit", + "extractionState" : "manual", + "localizations" : { + "ar" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "الرسالة طويلة جدًا" + } + }, + "bn" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "বার্তাটি খুব দীর্ঘ" + } + }, + "de" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "nachricht zu lang" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "message too long" + } + }, + "es" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "mensaje demasiado largo" + } + }, + "fa" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "پیام بیش از حد طولانی است" + } + }, + "fil" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "masyadong mahaba ang mensahe" + } + }, + "fr" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "message trop long" + } + }, + "he" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "ההודעה ארוכה מדי" + } + }, + "hi" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "संदेश बहुत लंबा है" + } + }, + "id" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "pesan terlalu panjang" + } + }, + "it" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "messaggio troppo lungo" + } + }, + "ja" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "メッセージが長すぎます" + } + }, + "ko" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "메시지가 너무 깁니다" + } + }, + "ms" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "mesej terlalu panjang" + } + }, + "ne" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "सन्देश धेरै लामो छ" + } + }, + "nl" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "bericht te lang" + } + }, + "pl" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "wiadomość jest za długa" + } + }, + "pt" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "mensagem demasiado longa" + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "mensagem muito longa" + } + }, + "ru" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "сообщение слишком длинное" + } + }, + "sv" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "meddelandet är för långt" + } + }, + "ta" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "செய்தி மிகவும் நீளமாக உள்ளது" + } + }, + "th" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "ข้อความยาวเกินไป" + } + }, + "tr" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "mesaj çok uzun" + } + }, + "uk" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "повідомлення надто довге" + } + }, + "ur" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "پیغام بہت لمبا ہے" + } + }, + "vi" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "tin nhắn quá dài" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "消息过长" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "訊息過長" + } + } + } + }, "content.delivery.reason.unknown_recipient" : { "extractionState" : "manual", "localizations" : { diff --git a/bitchat/Services/CommandProcessor.swift b/bitchat/Services/CommandProcessor.swift index 11aa5e4e..8af2deb7 100644 --- a/bitchat/Services/CommandProcessor.swift +++ b/bitchat/Services/CommandProcessor.swift @@ -531,7 +531,7 @@ final class CommandProcessor { if let peerID = contextProvider?.selectedPrivateChatPeer { guard PrivateMessagePacket.contentFitsOnWire(token) else { - return .error(message: String(localized: "content.delivery.reason.send_error", defaultValue: "send error", comment: "Failure reason for a generic send error")) + return .error(message: String(localized: "content.delivery.reason.too_long", defaultValue: "message too long", comment: "Failure reason when a private message exceeds the wire size limit")) } contextProvider?.sendPrivateMessage(token, to: peerID) return .success(message: String(format: String(localized: "command.pay.sent_private", defaultValue: "sent %@ — cashu is a bearer token; whoever redeems it first gets the funds", comment: "Confirmation after sending a cashu token in a private chat; placeholder is the amount summary"), locale: .current, summary)) diff --git a/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift b/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift index 529021dd..d42f6e10 100644 --- a/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift +++ b/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift @@ -397,7 +397,7 @@ final class ChatPrivateConversationCoordinator { private func initialDeliveryStatus(for content: String) -> DeliveryStatus { guard PrivateMessagePacket.contentFitsOnWire(content) else { - return .failed(reason: String(localized: "content.delivery.reason.send_error", comment: "Failure reason for a generic send error")) + return .failed(reason: String(localized: "content.delivery.reason.too_long", defaultValue: "message too long", comment: "Failure reason when a private message exceeds the wire size limit")) } return .sending } diff --git a/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift b/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift index b31a06d1..80f613bc 100644 --- a/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift +++ b/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift @@ -1253,11 +1253,20 @@ struct ChatPrivateConversationCoordinatorContextTests { coordinator.sendPrivateMessage(content, to: peerID) #expect(context.privateChats[peerID]?.map(\.content) == [content]) - guard case .failed? = context.privateChats[peerID]?.first?.deliveryStatus else { - Issue.record("Expected oversized content to fail delivery") - return - } + #expect(context.privateChats[peerID]?.first?.deliveryStatus == .failed( + reason: String(localized: "content.delivery.reason.too_long", defaultValue: "message too long") + )) #expect(context.routedPrivateMessages.isEmpty) #expect(context.geoPrivateMessages.isEmpty) + + // The multibyte UTF-8 boundary still sends: 127 × 2 + 1 = 255 bytes. + let boundaryContent = String(repeating: "é", count: 127) + "a" + #expect(boundaryContent.utf8.count == PrivateMessagePacket.maxContentUTF8Bytes) + coordinator.sendPrivateMessage(boundaryContent, to: peerID) + + #expect(context.privateChats[peerID]?.map(\.content) == [content, boundaryContent]) + #expect(context.privateChats[peerID]?.last?.deliveryStatus == (isGeohash ? .sent : .sending)) + #expect(context.routedPrivateMessages.map(\.content) == (isGeohash ? [] : [boundaryContent])) + #expect(context.geoPrivateMessages.map(\.content) == (isGeohash ? [boundaryContent] : [])) } } diff --git a/bitchatTests/CommandProcessorTests.swift b/bitchatTests/CommandProcessorTests.swift index 97ce6da0..6f20ccb6 100644 --- a/bitchatTests/CommandProcessorTests.swift +++ b/bitchatTests/CommandProcessorTests.swift @@ -489,16 +489,18 @@ struct CommandProcessorTests { } @MainActor - @Test func payRefusesAPrivateTokenThatDoesNotFitTheWire() { + @Test(arguments: [false, true]) func payRefusesAPrivateTokenThatDoesNotFitTheWire(isGeohash: Bool) { let context = MockCommandContextProvider() - context.selectedPrivateChatPeer = PeerID(str: "abcd1234abcd1234") + context.selectedPrivateChatPeer = isGeohash + ? PeerID(nostr_: String(repeating: "a", count: 64)) + : PeerID(str: "abcd1234abcd1234") let processor = makePayProcessor(context: context) let token = Self.cashuV3Token(mint: "https://mint.example.com/" + String(repeating: "a", count: 240)) #expect(token.utf8.count > PrivateMessagePacket.maxContentUTF8Bytes) switch processor.process("/pay \(token)") { case .error(let message): - #expect(message == "send error") + #expect(message == String(localized: "content.delivery.reason.too_long", defaultValue: "message too long")) default: Issue.record("Expected the oversized token to be refused") }