mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-24 21:45:20 +00:00
* Quality pass on the 1.7.0 batch: fix confirmed bugs, bump to 1.7.1 Post-merge review of PRs #1400–#1417 (push-to-talk, mesh bridging, DM store-and-forward, empty-mesh liveliness, geo-notes). Fixes the confirmed, well-scoped findings; deeper architectural/security items are tracked separately. - PTT hot-mic leak: releasing the mic during VoiceCaptureSession.start()'s 150ms retry pause left the mic live and streaming for up to 120s, because cancel() no-op'd once `completed` was set. Bail after the sleep if the hold was released, and make cancel() always tear down a late-started capture. - Bridge courier depositDrop reported success and burned the dedup slot before the drop was actually published (evicted/compose-fail = lying 📦 "carried" with no retry). Only consume publishedDropKeys on durable accept; add BoundedIDSet.remove() to release evicted/failed slots (uses the dead dedupKey). - Blocked senders resurfaced via archived "heard here earlier" echoes, the one path that bypassed the live block filter — filter at seed time. - A late optimistic .sent clobbered the router's .carried state; extend ConversationStore.shouldSkipStatusUpdate to a full precedence guard (sending < sent < carried < delivered < read). - Read receipts were permanently burned when the router dropped them (marked sent then dropped). sendReadReceipt/routeReadReceipt now return Bool; only record as sent on a successful route, else retry on the next read scan. - MessageRouter.cleanupExpiredMessages() had no production caller, so DMs to a peer that never reconnects sat on .sending until relaunch — run it in the 120s bridge sweep. - Sightings tally now rolls over at midnight while idle; wave notification action localized across all 29 locales; bridged anon#tag uses suffix(4) like everything else; makeThrowawayIdentity delegates to NostrIdentity.generate(); .swiftlint.yml excludes .claude worktrees. - Add regression tests: carried→sent no-downgrade, carried→delivered upgrade, evicted pending drop stays retryable. - Bump MARKETING_VERSION to 1.7.1. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * Fix CI: adjust delivery-status benchmark and drop now-dead addSystemMessage The stricter no-downgrade guard (delivered/carried never regress to sent) broke two things the earlier commit didn't catch locally (perf tests are skipped in the default run, and Periphery runs only in CI): - PerformanceBaselineTests delivery benchmarks alternated sent <-> delivered assuming both directions apply; the delivered -> sent half is now correctly skipped, so the pass measured 0 updates. Alternate two delivered timestamps instead — every update is real, no downgrade. - Routing the geoDM "not in a location channel" error into the thread removed the only caller of ChatPrivateConversationContext.addSystemMessage, leaving it (and its mock) dead per Periphery. Drop the protocol requirement, the mock impl, and the now-vacuous systemMessages.isEmpty assertions (the invariant is compile-time enforced: the context can no longer emit a public system line). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * Address review findings: read-receipt dedup, carried-vs-sending, block-time echo purge - Read receipts: claim the receipt in sentReadReceipts synchronously before spawning the routing task (chat open runs two read scans in one MainActor stretch, so the async insert let every unread message route twice), and release the claim when the route fails so the retry-on-failed-route behavior is preserved. - Delivery status: extend the no-downgrade guard so the `.sending` stamp a pre-handshake resend emits can no longer clobber carried/delivered/read (the 📦 indicator survived `.sent` but not `.sending`). - Archived echoes: blocking a peer now purges their carried public messages from the gossip archive at block time (UnifiedPeerService and /block), while the fingerprint-to-peerID mapping is still known — the seed-time filter can't resolve offline non-favorite strangers and stays only as defense-in-depth. New Transport hook (default no-op) + GossipSyncManager.removePublicMessages with immediate persist. - Bridge courier: an envelope that can't encode within the drop size caps fails identically on every attempt; consume the dedup slot so the 120s retry sweep stops re-running Noise sealing on it. - MeshSightingsTracker: cache the day-key DateFormatter instead of building one per call. Tests: double-markAsRead dedup + failed-route retry, carried→sending no-downgrade matrix, block-time purge (manager + service wiring), oversize-drop slot consumption. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Also skip the sent→sending downgrade in the delivery-status guard Codex review follow-up: sendPrivateMessage without an established Noise session emits `.sending` asynchronously, so it can land after the message already reached `.sent` and visibly walk "Sent" back to "Sending...". Treat `.sending` as weaker than `.sent` too — the status was already truthful. `.failed` → `.sending` stays allowed so a retry after a real failure remains visible. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Retain Codable properties in Periphery scan (same fix as #1421) The noiseKey assign-only false positive fired persistently on this branch (twice, including a rerun) despite the baselined USR. Byte-identical to the fix on fix/announce-replay-link-steal so the branches merge cleanly in either order. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
370 lines
13 KiB
Swift
370 lines
13 KiB
Swift
//
|
|
// BitchatMessage.swift
|
|
// bitchat
|
|
//
|
|
// This is free and unencumbered software released into the public domain.
|
|
// For more information, see <https://unlicense.org>
|
|
//
|
|
|
|
import class Foundation.DateFormatter
|
|
|
|
import struct Foundation.AttributedString
|
|
import struct Foundation.Data
|
|
import struct Foundation.Date
|
|
import struct Foundation.TimeInterval
|
|
import struct Foundation.UUID
|
|
|
|
/// Represents a user-visible message in the BitChat system.
|
|
/// Handles both broadcast messages and private encrypted messages,
|
|
/// with support for mentions, replies, and delivery tracking.
|
|
/// - Note: This is the primary data model for chat messages
|
|
public final class BitchatMessage: Codable {
|
|
public let id: String
|
|
public let sender: String
|
|
public let content: String
|
|
public let timestamp: Date
|
|
public let isRelay: Bool
|
|
public let originalSender: String?
|
|
public let isPrivate: Bool
|
|
public let recipientNickname: String?
|
|
public let senderPeerID: PeerID?
|
|
public let mentions: [String]? // Array of mentioned nicknames
|
|
public var deliveryStatus: DeliveryStatus? // Delivery tracking
|
|
/// True when this message reached us across a mesh bridge (signed by its
|
|
/// author for an internet rendezvous) rather than over local radio.
|
|
public let isBridged: Bool
|
|
|
|
// Cached formatted text (not included in Codable)
|
|
private var _cachedFormattedText: [String: AttributedString] = [:]
|
|
|
|
public func getCachedFormattedText(isDark: Bool, isSelf: Bool, variant: String = "") -> AttributedString? {
|
|
return _cachedFormattedText["\(variant)\(isDark)-\(isSelf)"]
|
|
}
|
|
|
|
public func setCachedFormattedText(_ text: AttributedString, isDark: Bool, isSelf: Bool, variant: String = "") {
|
|
_cachedFormattedText["\(variant)\(isDark)-\(isSelf)"] = text
|
|
}
|
|
|
|
// Codable implementation
|
|
enum CodingKeys: String, CodingKey {
|
|
case id, sender, content, timestamp, isRelay, originalSender
|
|
case isPrivate, recipientNickname, senderPeerID, mentions, deliveryStatus
|
|
case isBridged
|
|
}
|
|
|
|
public init(from decoder: any Decoder) throws {
|
|
let container = try decoder.container(keyedBy: CodingKeys.self)
|
|
id = try container.decode(String.self, forKey: .id)
|
|
sender = try container.decode(String.self, forKey: .sender)
|
|
content = try container.decode(String.self, forKey: .content)
|
|
timestamp = try container.decode(Date.self, forKey: .timestamp)
|
|
isRelay = try container.decode(Bool.self, forKey: .isRelay)
|
|
originalSender = try container.decodeIfPresent(String.self, forKey: .originalSender)
|
|
isPrivate = try container.decode(Bool.self, forKey: .isPrivate)
|
|
recipientNickname = try container.decodeIfPresent(String.self, forKey: .recipientNickname)
|
|
senderPeerID = try container.decodeIfPresent(PeerID.self, forKey: .senderPeerID)
|
|
mentions = try container.decodeIfPresent([String].self, forKey: .mentions)
|
|
deliveryStatus = try container.decodeIfPresent(DeliveryStatus.self, forKey: .deliveryStatus)
|
|
// Absent in archives written before bridging existed.
|
|
isBridged = try container.decodeIfPresent(Bool.self, forKey: .isBridged) ?? false
|
|
}
|
|
|
|
public init(
|
|
id: String? = nil,
|
|
sender: String,
|
|
content: String,
|
|
timestamp: Date,
|
|
isRelay: Bool,
|
|
originalSender: String? = nil,
|
|
isPrivate: Bool = false,
|
|
recipientNickname: String? = nil,
|
|
senderPeerID: PeerID? = nil,
|
|
mentions: [String]? = nil,
|
|
deliveryStatus: DeliveryStatus? = nil,
|
|
isBridged: Bool = false
|
|
) {
|
|
self.id = id ?? UUID().uuidString
|
|
self.sender = sender
|
|
self.content = content
|
|
self.timestamp = timestamp
|
|
self.isRelay = isRelay
|
|
self.originalSender = originalSender
|
|
self.isPrivate = isPrivate
|
|
self.recipientNickname = recipientNickname
|
|
self.senderPeerID = senderPeerID
|
|
self.mentions = mentions
|
|
self.deliveryStatus = deliveryStatus ?? (isPrivate ? .sending : nil)
|
|
self.isBridged = isBridged
|
|
}
|
|
}
|
|
|
|
// MARK: - Equatable Conformance
|
|
|
|
extension BitchatMessage: Equatable {
|
|
public static func == (lhs: BitchatMessage, rhs: BitchatMessage) -> Bool {
|
|
return lhs.id == rhs.id &&
|
|
lhs.sender == rhs.sender &&
|
|
lhs.content == rhs.content &&
|
|
lhs.timestamp == rhs.timestamp &&
|
|
lhs.isRelay == rhs.isRelay &&
|
|
lhs.originalSender == rhs.originalSender &&
|
|
lhs.isPrivate == rhs.isPrivate &&
|
|
lhs.recipientNickname == rhs.recipientNickname &&
|
|
lhs.senderPeerID == rhs.senderPeerID &&
|
|
lhs.mentions == rhs.mentions &&
|
|
lhs.deliveryStatus == rhs.deliveryStatus &&
|
|
lhs.isBridged == rhs.isBridged
|
|
}
|
|
}
|
|
|
|
// MARK: - Binary encoding
|
|
|
|
extension BitchatMessage {
|
|
func toBinaryPayload() -> Data? {
|
|
var data = Data()
|
|
|
|
// Message format:
|
|
// - Flags: 1 byte (bit 0: isRelay, bit 1: isPrivate, bit 2: hasOriginalSender, bit 3: hasRecipientNickname, bit 4: hasSenderPeerID, bit 5: hasMentions)
|
|
// - Timestamp: 8 bytes (seconds since epoch)
|
|
// - ID length: 1 byte
|
|
// - ID: variable
|
|
// - Sender length: 1 byte
|
|
// - Sender: variable
|
|
// - Content length: 2 bytes
|
|
// - Content: variable
|
|
// Optional fields based on flags:
|
|
// - Original sender length + data
|
|
// - Recipient nickname length + data
|
|
// - Sender peer ID length + data
|
|
// - Mentions array
|
|
|
|
var flags: UInt8 = 0
|
|
if isRelay { flags |= 0x01 }
|
|
if isPrivate { flags |= 0x02 }
|
|
if originalSender != nil { flags |= 0x04 }
|
|
if recipientNickname != nil { flags |= 0x08 }
|
|
if senderPeerID != nil { flags |= 0x10 }
|
|
if mentions != nil && !mentions!.isEmpty { flags |= 0x20 }
|
|
if isBridged { flags |= 0x40 }
|
|
|
|
data.append(flags)
|
|
|
|
// Timestamp (in milliseconds)
|
|
let timestampMillis = UInt64(timestamp.timeIntervalSince1970 * 1000)
|
|
// Encode as 8 bytes, big-endian
|
|
for i in (0..<8).reversed() {
|
|
data.append(UInt8((timestampMillis >> (i * 8)) & 0xFF))
|
|
}
|
|
|
|
// ID
|
|
if let idData = id.data(using: .utf8) {
|
|
data.append(UInt8(min(idData.count, 255)))
|
|
data.append(idData.prefix(255))
|
|
} else {
|
|
data.append(0)
|
|
}
|
|
|
|
// Sender
|
|
if let senderData = sender.data(using: .utf8) {
|
|
data.append(UInt8(min(senderData.count, 255)))
|
|
data.append(senderData.prefix(255))
|
|
} else {
|
|
data.append(0)
|
|
}
|
|
|
|
// Content
|
|
if let contentData = content.data(using: .utf8) {
|
|
let length = UInt16(min(contentData.count, 65535))
|
|
// Encode length as 2 bytes, big-endian
|
|
data.append(UInt8((length >> 8) & 0xFF))
|
|
data.append(UInt8(length & 0xFF))
|
|
data.append(contentData.prefix(Int(length)))
|
|
} else {
|
|
data.append(contentsOf: [0, 0])
|
|
}
|
|
|
|
// Optional fields
|
|
if let originalSender = originalSender, let origData = originalSender.data(using: .utf8) {
|
|
data.append(UInt8(min(origData.count, 255)))
|
|
data.append(origData.prefix(255))
|
|
}
|
|
|
|
if let recipientNickname = recipientNickname, let recipData = recipientNickname.data(using: .utf8) {
|
|
data.append(UInt8(min(recipData.count, 255)))
|
|
data.append(recipData.prefix(255))
|
|
}
|
|
|
|
if let peerData = senderPeerID?.id.data(using: .utf8) {
|
|
data.append(UInt8(min(peerData.count, 255)))
|
|
data.append(peerData.prefix(255))
|
|
}
|
|
|
|
// Mentions array
|
|
if let mentions = mentions {
|
|
data.append(UInt8(min(mentions.count, 255))) // Number of mentions
|
|
for mention in mentions.prefix(255) {
|
|
if let mentionData = mention.data(using: .utf8) {
|
|
data.append(UInt8(min(mentionData.count, 255)))
|
|
data.append(mentionData.prefix(255))
|
|
} else {
|
|
data.append(0)
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
return data
|
|
}
|
|
|
|
convenience init?(_ data: Data) {
|
|
// Create an immutable copy to prevent threading issues
|
|
let dataCopy = Data(data)
|
|
|
|
|
|
guard dataCopy.count >= 13 else {
|
|
return nil
|
|
}
|
|
|
|
var offset = 0
|
|
|
|
// Flags
|
|
guard offset < dataCopy.count else {
|
|
return nil
|
|
}
|
|
let flags = dataCopy[offset]; offset += 1
|
|
let isRelay = (flags & 0x01) != 0
|
|
let isPrivate = (flags & 0x02) != 0
|
|
let hasOriginalSender = (flags & 0x04) != 0
|
|
let hasRecipientNickname = (flags & 0x08) != 0
|
|
let hasSenderPeerID = (flags & 0x10) != 0
|
|
let hasMentions = (flags & 0x20) != 0
|
|
let isBridged = (flags & 0x40) != 0
|
|
|
|
// Timestamp
|
|
guard offset + 8 <= dataCopy.count else {
|
|
return nil
|
|
}
|
|
let timestampData = dataCopy[offset..<offset+8]
|
|
let timestampMillis = timestampData.reduce(0) { result, byte in
|
|
(result << 8) | UInt64(byte)
|
|
}
|
|
offset += 8
|
|
let timestamp = Date(timeIntervalSince1970: TimeInterval(timestampMillis) / 1000.0)
|
|
|
|
// ID
|
|
guard offset < dataCopy.count else {
|
|
return nil
|
|
}
|
|
let idLength = Int(dataCopy[offset]); offset += 1
|
|
guard offset + idLength <= dataCopy.count else {
|
|
return nil
|
|
}
|
|
let id = String(data: dataCopy[offset..<offset+idLength], encoding: .utf8) ?? UUID().uuidString
|
|
offset += idLength
|
|
|
|
// Sender
|
|
guard offset < dataCopy.count else {
|
|
return nil
|
|
}
|
|
let senderLength = Int(dataCopy[offset]); offset += 1
|
|
guard offset + senderLength <= dataCopy.count else {
|
|
return nil
|
|
}
|
|
let sender = String(data: dataCopy[offset..<offset+senderLength], encoding: .utf8) ?? "unknown"
|
|
offset += senderLength
|
|
|
|
// Content
|
|
guard offset + 2 <= dataCopy.count else {
|
|
return nil
|
|
}
|
|
let contentLengthData = dataCopy[offset..<offset+2]
|
|
let contentLength = Int(contentLengthData.reduce(0) { result, byte in
|
|
(result << 8) | UInt16(byte)
|
|
})
|
|
offset += 2
|
|
guard offset + contentLength <= dataCopy.count else {
|
|
return nil
|
|
}
|
|
|
|
let content = String(data: dataCopy[offset..<offset+contentLength], encoding: .utf8) ?? ""
|
|
offset += contentLength
|
|
|
|
// Optional fields
|
|
var originalSender: String?
|
|
if hasOriginalSender && offset < dataCopy.count {
|
|
let length = Int(dataCopy[offset]); offset += 1
|
|
if offset + length <= dataCopy.count {
|
|
originalSender = String(data: dataCopy[offset..<offset+length], encoding: .utf8)
|
|
offset += length
|
|
}
|
|
}
|
|
|
|
var recipientNickname: String?
|
|
if hasRecipientNickname && offset < dataCopy.count {
|
|
let length = Int(dataCopy[offset]); offset += 1
|
|
if offset + length <= dataCopy.count {
|
|
recipientNickname = String(data: dataCopy[offset..<offset+length], encoding: .utf8)
|
|
offset += length
|
|
}
|
|
}
|
|
|
|
var senderPeerID: PeerID?
|
|
if hasSenderPeerID && offset < dataCopy.count {
|
|
let length = Int(dataCopy[offset]); offset += 1
|
|
if offset + length <= dataCopy.count {
|
|
senderPeerID = PeerID(data: dataCopy[offset..<offset+length])
|
|
offset += length
|
|
}
|
|
}
|
|
|
|
// Mentions array
|
|
var mentions: [String]?
|
|
if hasMentions && offset < dataCopy.count {
|
|
let mentionCount = Int(dataCopy[offset]); offset += 1
|
|
if mentionCount > 0 {
|
|
mentions = []
|
|
for _ in 0..<mentionCount {
|
|
if offset < dataCopy.count {
|
|
let length = Int(dataCopy[offset]); offset += 1
|
|
if offset + length <= dataCopy.count {
|
|
if let mention = String(data: dataCopy[offset..<offset+length], encoding: .utf8) {
|
|
mentions?.append(mention)
|
|
}
|
|
offset += length
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
self.init(
|
|
id: id,
|
|
sender: sender,
|
|
content: content,
|
|
timestamp: timestamp,
|
|
isRelay: isRelay,
|
|
originalSender: originalSender,
|
|
isPrivate: isPrivate,
|
|
recipientNickname: recipientNickname,
|
|
senderPeerID: senderPeerID,
|
|
mentions: mentions,
|
|
isBridged: isBridged
|
|
)
|
|
}
|
|
}
|
|
|
|
// MARK: - Helpers
|
|
|
|
extension BitchatMessage {
|
|
|
|
private static let timestampFormatter: DateFormatter = {
|
|
let formatter = DateFormatter()
|
|
formatter.dateFormat = "HH:mm:ss"
|
|
return formatter
|
|
}()
|
|
|
|
public var formattedTimestamp: String {
|
|
Self.timestampFormatter.string(from: timestamp)
|
|
}
|
|
}
|