Tier 3: architectural consolidations across media storage, ViewModels, BLE, Noise, Gateway/Bridge, and Nostr (#1906)

* Redesign private-media disk storage and receipt ledger around UUID names and atomic snapshot

* Consolidate ViewModel shared contexts, Combine mirrors, and PrivateChatManager

* Fold BLE micro-files and split BLEService by domain

* Merge SecureNoiseSession into NoiseSession and consolidate NoiseSessionManager slots

* Extract shared CarrierRelayEngine, add Transport defaults, and split NostrRelayManager

* Share outgoing voice-note path helper and trim unused NostrRelayManager imports

* Remove extra trailing newline in NostrRelayManager.swift

* Protect pending UI media deliveries from quota eviction and remove unused QueuedUplink wrappers

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
This commit is contained in:
jackandjack authored and GitHub committed 2026-11-26 22:01:30 -10:00
1 parent ef84fdcdd1
commit 6edbcaf108
62 files changed
+4599 -6025

No files matched your search

+15 -53
View File
@@ -163,63 +163,25 @@ final class AppChromeModel: ObservableObject {
}
.store(in: &cancellables)
chatViewModel.$nickname
.removeDuplicates()
.dropFirst()
.receive(on: DispatchQueue.main)
.sink { [weak self] nickname in
guard let self, self.nickname != nickname else { return }
self.nickname = nickname
}
.store(in: &cancellables)
mirror(chatViewModel.$nickname, to: \.nickname)
mirror(chatViewModel.$showBluetoothAlert, to: \.showBluetoothAlert)
mirror(chatViewModel.$bluetoothAlertMessage, to: \.bluetoothAlertMessage)
mirror(chatViewModel.$bluetoothState, to: \.bluetoothState)
mirror(chatViewModel.$torBlocked, to: \.torBlocked)
mirror(chatViewModel.$panicRecoveryBlocked, to: \.panicWipeBlocked)
}
chatViewModel.$showBluetoothAlert
private func mirror<Value: Equatable>(
_ publisher: Published<Value>.Publisher,
to keyPath: ReferenceWritableKeyPath<AppChromeModel, Value>
) {
publisher
.removeDuplicates()
.dropFirst()
.receive(on: DispatchQueue.main)
.sink { [weak self] showAlert in
guard let self, self.showBluetoothAlert != showAlert else { return }
self.showBluetoothAlert = showAlert
}
.store(in: &cancellables)
chatViewModel.$bluetoothAlertMessage
.removeDuplicates()
.dropFirst()
.receive(on: DispatchQueue.main)
.sink { [weak self] message in
guard let self, self.bluetoothAlertMessage != message else { return }
self.bluetoothAlertMessage = message
}
.store(in: &cancellables)
chatViewModel.$bluetoothState
.removeDuplicates()
.dropFirst()
.receive(on: DispatchQueue.main)
.sink { [weak self] state in
guard let self, self.bluetoothState != state else { return }
self.bluetoothState = state
}
.store(in: &cancellables)
chatViewModel.$torBlocked
.removeDuplicates()
.dropFirst()
.receive(on: DispatchQueue.main)
.sink { [weak self] blocked in
guard let self, self.torBlocked != blocked else { return }
self.torBlocked = blocked
}
.store(in: &cancellables)
chatViewModel.$panicRecoveryBlocked
.removeDuplicates()
.dropFirst()
.receive(on: DispatchQueue.main)
.sink { [weak self] blocked in
guard let self, self.panicWipeBlocked != blocked else { return }
self.panicWipeBlocked = blocked
.sink { [weak self] value in
guard let self, self[keyPath: keyPath] != value else { return }
self[keyPath: keyPath] = value
}
.store(in: &cancellables)
}
+1 -1
View File
@@ -182,7 +182,7 @@ final class AppRuntime: ObservableObject {
/// best-effort, nothing at launch depends on their results.
private func performMediaMaintenance() {
Task.detached(priority: .utility) {
let store = BLEIncomingFileStore()
let store = BLEIncomingFileStore.shared
store.expireAgedMedia()
store.migrateFileProtectionIfNeeded()
}
+10 -13
View File
@@ -155,22 +155,19 @@ final class ComposerAutocompleteModel: ObservableObject {
}
private func bind() {
chatViewModel.$showAutocomplete
.removeDuplicates()
.dropFirst()
.receive(on: DispatchQueue.main)
.assign(to: &$showAutocomplete)
mirror(chatViewModel.$showAutocomplete, to: &$showAutocomplete)
mirror(chatViewModel.$autocompleteSuggestions, to: &$autocompleteSuggestions)
mirror(chatViewModel.$selectedAutocompleteIndex, to: &$selectedAutocompleteIndex)
}
chatViewModel.$autocompleteSuggestions
private func mirror<Value: Equatable>(
_ publisher: Published<Value>.Publisher,
to target: inout Published<Value>.Publisher
) {
publisher
.removeDuplicates()
.dropFirst()
.receive(on: DispatchQueue.main)
.assign(to: &$autocompleteSuggestions)
chatViewModel.$selectedAutocompleteIndex
.removeDuplicates()
.dropFirst()
.receive(on: DispatchQueue.main)
.assign(to: &$selectedAutocompleteIndex)
.assign(to: &target)
}
}
@@ -235,16 +235,8 @@ final class PTTLiveVoiceSession: VoiceCaptureSession {
}
private static func makeOutputURL(burstID: Data) throws -> URL {
let base = try FileManager.default.url(
for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
try VoiceRecorder.makeOutgoingVoiceNoteURL(
fileName: "voice_\(burstID.hexEncodedString()).m4a"
)
let directory = base
.appendingPathComponent("files", isDirectory: true)
.appendingPathComponent("voicenotes/outgoing", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: BLEIncomingFileStore.mediaProtectionAttributes)
return directory.appendingPathComponent("voice_\(burstID.hexEncodedString()).m4a")
}
}
+29 -8
View File
@@ -291,20 +291,41 @@ actor VoiceRecorder {
#endif
}
private func makeOutputURL() throws -> URL {
private static let fileNameDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd_HHmmss"
let fileName = "voice_\(formatter.string(from: Date()))_\(UUID().uuidString).m4a"
return formatter
}()
let baseDirectory = try outputDirectory
?? applicationFilesDirectory().appendingPathComponent("voicenotes/outgoing", isDirectory: true)
try FileManager.default.createDirectory(at: baseDirectory, withIntermediateDirectories: true, attributes: BLEIncomingFileStore.mediaProtectionAttributes)
nonisolated static func makeOutgoingVoiceNoteURL(
fileName: String,
outputDirectory: URL? = nil
) throws -> URL {
let baseDirectory: URL
if let outputDirectory {
baseDirectory = outputDirectory
} else {
let appSupport = try FileManager.default.url(
for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
baseDirectory = appSupport
.appendingPathComponent("files", isDirectory: true)
.appendingPathComponent("voicenotes/outgoing", isDirectory: true)
}
try FileManager.default.createDirectory(
at: baseDirectory,
withIntermediateDirectories: true,
attributes: BLEIncomingFileStore.mediaProtectionAttributes
)
return baseDirectory.appendingPathComponent(fileName)
}
private func applicationFilesDirectory() throws -> URL {
try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("files", isDirectory: true)
private func makeOutputURL() throws -> URL {
let fileName = "voice_\(Self.fileNameDateFormatter.string(from: Date()))_\(UUID().uuidString).m4a"
return try Self.makeOutgoingVoiceNoteURL(fileName: fileName, outputDirectory: outputDirectory)
}
/// Fire-and-forget: the coordinator hops the blocking deactivation IPC
+116 -27
View File
@@ -39,14 +39,19 @@ class NoiseSession {
private var handshakeState: NoiseHandshakeState?
private var sendCipher: NoiseCipherState?
private var receiveCipher: NoiseCipherState?
// Lifecycle & security limits (confined to sessionQueue)
private var messageCount: UInt64 = 0
private var sessionStartTime = Date()
private var lastActivityTime = Date()
// Keys
private let localStaticKey: Curve25519.KeyAgreement.PrivateKey
private var remoteStaticPublicKey: Curve25519.KeyAgreement.PublicKey?
// Thread safety
private let sessionQueue = DispatchQueue(label: "chat.bitchat.noise.session", attributes: .concurrent)
init(
peerID: PeerID,
role: NoiseRole,
@@ -60,15 +65,15 @@ class NoiseSession {
self.localStaticKey = localStaticKey
self.remoteStaticPublicKey = remoteStaticKey
}
// MARK: - Handshake
func startHandshake() throws -> Data {
return try sessionQueue.sync(flags: .barrier) {
guard case .uninitialized = state else {
throw NoiseSessionError.invalidState
}
// For XX pattern, we don't need remote static key upfront
handshakeState = NoiseHandshakeState(
role: role,
@@ -77,9 +82,9 @@ class NoiseSession {
localStaticKey: localStaticKey,
remoteStaticKey: nil
)
state = .handshaking
// Only initiator writes the first message
if role == .initiator {
guard let handshake = handshakeState else {
@@ -93,11 +98,11 @@ class NoiseSession {
}
}
}
func processHandshakeMessage(_ message: Data) throws -> Data? {
return try sessionQueue.sync(flags: .barrier) {
SecureLogger.debug("NoiseSession[\(peerID)]: Processing handshake message, current state: \(state), role: \(role)")
// Initialize handshake state if needed (for responders)
if state == .uninitialized && role == .responder {
handshakeState = NoiseHandshakeState(
@@ -110,15 +115,15 @@ class NoiseSession {
state = .handshaking
SecureLogger.debug("NoiseSession[\(peerID)]: Initialized handshake state for responder")
}
guard case .handshaking = state, let handshake = handshakeState else {
throw NoiseSessionError.invalidState
}
// Process incoming message
_ = try handshake.readMessage(message)
SecureLogger.debug("NoiseSession[\(peerID)]: Read handshake message, checking if complete")
// Check if handshake is complete
if handshake.isHandshakeComplete() {
try completeHandshake(handshake)
@@ -127,12 +132,12 @@ class NoiseSession {
// Generate response
let response = try handshake.writeMessage()
SecureLogger.debug("NoiseSession[\(peerID)]: Generated handshake response of size \(response.count)")
// Check if handshake is complete after writing
if handshake.isHandshakeComplete() {
try completeHandshake(handshake)
}
return response
}
}
@@ -148,37 +153,96 @@ class NoiseSession {
SecureLogger.debug("NoiseSession[\(peerID)]: Handshake complete, transitioning to established")
SecureLogger.info(.handshakeCompleted(peerID: peerID.id))
}
// MARK: - Transport
func encrypt(_ plaintext: Data) throws -> Data {
return try sessionQueue.sync(flags: .barrier) {
let now = Date()
if now.timeIntervalSince(sessionStartTime) > NoiseSecurityConstants.sessionTimeout {
throw NoiseSecurityError.sessionExpired
}
if messageCount >= NoiseSecurityConstants.maxMessagesPerSession {
throw NoiseSecurityError.sessionExhausted
}
// Ordinary Noise messages keep the protocol ceiling. Finalized media
// is the sole typed-payload extension and remains under the framed-file
// cap enforced again at the service and file-decoder layers.
let isPrivateFile = NoisePayloadType.isPrivateFile(rawValue: plaintext.first)
&& NoiseSecurityValidator.validatePrivateFileMessageSize(plaintext)
guard NoiseSecurityValidator.validateMessageSize(plaintext) || isPrivateFile else {
throw NoiseSecurityError.messageTooLarge
}
guard case .established = state, let cipher = sendCipher else {
throw NoiseSessionError.notEstablished
}
return try cipher.encrypt(plaintext: plaintext)
let encrypted = try cipher.encrypt(plaintext: plaintext)
messageCount += 1
lastActivityTime = now
return encrypted
}
}
func decrypt(_ ciphertext: Data) throws -> Data {
return try sessionQueue.sync(flags: .barrier) {
let now = Date()
if now.timeIntervalSince(sessionStartTime) > NoiseSecurityConstants.sessionTimeout {
throw NoiseSecurityError.sessionExpired
}
// The payload type is encrypted, so a large candidate can only be
// bounded here; `NoiseEncryptionService.decrypt` authenticates it and
// then requires the resulting type to be `.privateFile`.
guard NoiseSecurityValidator.validateCiphertextSize(ciphertext)
|| NoiseSecurityValidator.validatePrivateFileCiphertextSize(ciphertext) else {
throw NoiseSecurityError.messageTooLarge
}
guard case .established = state, let cipher = receiveCipher else {
throw NoiseSessionError.notEstablished
}
return try cipher.decrypt(ciphertext: ciphertext)
let decrypted = try cipher.decrypt(ciphertext: ciphertext)
lastActivityTime = now
return decrypted
}
}
func needsRenegotiation() -> Bool {
sessionQueue.sync {
let messageThreshold = UInt64(Double(NoiseSecurityConstants.maxMessagesPerSession) * 0.9)
if messageCount >= messageThreshold {
return true
}
let now = Date()
if now.timeIntervalSince(lastActivityTime) > NoiseSecurityConstants.sessionTimeout {
return true
}
// A session that never goes idle keeps refreshing lastActivityTime forever,
// so check sessionStartTime at 90% of sessionTimeout to give the periodic
// rekey check room to rotate keys before encrypt/decrypt start throwing
// sessionExpired.
if now.timeIntervalSince(sessionStartTime) > NoiseSecurityConstants.sessionTimeout * 0.9 {
return true
}
return false
}
}
// MARK: - State Management
func getState() -> NoiseSessionState {
return sessionQueue.sync {
return state
}
}
func isEstablished() -> Bool {
return sessionQueue.sync {
if case .established = state {
@@ -187,19 +251,23 @@ class NoiseSession {
return false
}
}
func getRemoteStaticPublicKey() -> Curve25519.KeyAgreement.PublicKey? {
return sessionQueue.sync {
return remoteStaticPublicKey
}
}
func reset() {
sessionQueue.sync(flags: .barrier) {
let wasEstablished = state == .established
state = .uninitialized
handshakeState = nil
messageCount = 0
let now = Date()
sessionStartTime = now
lastActivityTime = now
// Clear sensitive cipher states
sendCipher?.clearSensitiveData()
receiveCipher?.clearSensitiveData()
@@ -211,4 +279,25 @@ class NoiseSession {
}
}
}
// MARK: - Testing Support
#if DEBUG
func setLastActivityTimeForTesting(_ date: Date) {
sessionQueue.sync(flags: .barrier) {
lastActivityTime = date
}
}
func setMessageCountForTesting(_ count: UInt64) {
sessionQueue.sync(flags: .barrier) {
messageCount = count
}
}
func setSessionStartTimeForTesting(_ date: Date) {
sessionQueue.sync(flags: .barrier) {
sessionStartTime = date
}
}
#endif
}
File diff suppressed because it is too large. Load diff
-133
View File
@@ -1,133 +0,0 @@
//
// SecureNoiseSession.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
final class SecureNoiseSession: NoiseSession {
private let stateLock = NSLock()
private var _messageCount: UInt64 = 0
private var _sessionStartTime = Date()
private var _lastActivityTime = Date()
override func encrypt(_ plaintext: Data) throws -> Data {
let now = Date()
stateLock.lock()
let startTime = _sessionStartTime
let count = _messageCount
stateLock.unlock()
// Check session age
if now.timeIntervalSince(startTime) > NoiseSecurityConstants.sessionTimeout {
throw NoiseSecurityError.sessionExpired
}
// Check message count
if count >= NoiseSecurityConstants.maxMessagesPerSession {
throw NoiseSecurityError.sessionExhausted
}
// Ordinary Noise messages keep the protocol ceiling. Finalized media
// is the sole typed-payload extension and remains under the framed-file
// cap enforced again at the service and file-decoder layers.
let isPrivateFile = NoisePayloadType.isPrivateFile(rawValue: plaintext.first)
&& NoiseSecurityValidator.validatePrivateFileMessageSize(plaintext)
guard NoiseSecurityValidator.validateMessageSize(plaintext) || isPrivateFile else {
throw NoiseSecurityError.messageTooLarge
}
let encrypted = try super.encrypt(plaintext)
stateLock.lock()
_messageCount += 1
_lastActivityTime = Date()
stateLock.unlock()
return encrypted
}
override func decrypt(_ ciphertext: Data) throws -> Data {
let now = Date()
stateLock.lock()
let startTime = _sessionStartTime
stateLock.unlock()
// Check session age
if now.timeIntervalSince(startTime) > NoiseSecurityConstants.sessionTimeout {
throw NoiseSecurityError.sessionExpired
}
// The payload type is encrypted, so a large candidate can only be
// bounded here; `NoiseEncryptionService.decrypt` authenticates it and
// then requires the resulting type to be `.privateFile`.
guard NoiseSecurityValidator.validateCiphertextSize(ciphertext)
|| NoiseSecurityValidator.validatePrivateFileCiphertextSize(ciphertext) else {
throw NoiseSecurityError.messageTooLarge
}
let decrypted = try super.decrypt(ciphertext)
stateLock.lock()
_lastActivityTime = Date()
stateLock.unlock()
return decrypted
}
func needsRenegotiation() -> Bool {
let now = Date()
stateLock.lock()
let count = _messageCount
let lastActivity = _lastActivityTime
let startTime = _sessionStartTime
stateLock.unlock()
// Check if we've used more than 90% of message limit
let messageThreshold = UInt64(Double(NoiseSecurityConstants.maxMessagesPerSession) * 0.9)
if count >= messageThreshold {
return true
}
// Check if last activity exceeded sessionTimeout
if now.timeIntervalSince(lastActivity) > NoiseSecurityConstants.sessionTimeout {
return true
}
// A session that never goes idle (a long-lived conversation with
// steady traffic) keeps refreshing lastActivityTime forever, so the
// check above never fires -- only sessionStartTime tracks how close
// encrypt/decrypt are to the hard sessionExpired cutoff above. Firing
// at 90% of sessionTimeout leaves the rekey timer's polling interval
// (checked every 60s, see NoiseEncryptionService.rekeyCheckInterval)
// room to complete a full handshake well before the old session
// starts throwing sessionExpired on every call.
if now.timeIntervalSince(startTime) > NoiseSecurityConstants.sessionTimeout * 0.9 {
return true
}
return false
}
// MARK: - Testing Support
#if DEBUG
func setLastActivityTimeForTesting(_ date: Date) {
stateLock.lock()
_lastActivityTime = date
stateLock.unlock()
}
func setMessageCountForTesting(_ count: UInt64) {
stateLock.lock()
_messageCount = count
stateLock.unlock()
}
func setSessionStartTimeForTesting(_ date: Date) {
stateLock.lock()
_sessionStartTime = date
stateLock.unlock()
}
#endif
}
+125
View File
@@ -0,0 +1,125 @@
import Combine
import Foundation
import Tor
protocol NostrRelayConnectionProtocol: AnyObject {
func resume()
func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?)
func send(_ message: URLSessionWebSocketTask.Message, completionHandler: @escaping (Error?) -> Void)
func receive(completionHandler: @escaping (Result<URLSessionWebSocketTask.Message, Error>) -> Void)
func sendPing(pongReceiveHandler: @escaping (Error?) -> Void)
}
protocol NostrRelaySessionProtocol {
func webSocketTask(with url: URL) -> NostrRelayConnectionProtocol
}
private final class URLSessionWebSocketTaskAdapter: NostrRelayConnectionProtocol {
private let base: URLSessionWebSocketTask
init(base: URLSessionWebSocketTask) {
self.base = base
}
func resume() {
base.resume()
}
func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
base.cancel(with: closeCode, reason: reason)
}
func send(_ message: URLSessionWebSocketTask.Message, completionHandler: @escaping (Error?) -> Void) {
base.send(message, completionHandler: completionHandler)
}
func receive(completionHandler: @escaping (Result<URLSessionWebSocketTask.Message, Error>) -> Void) {
base.receive(completionHandler: completionHandler)
}
func sendPing(pongReceiveHandler: @escaping (Error?) -> Void) {
base.sendPing(pongReceiveHandler: pongReceiveHandler)
}
}
private struct URLSessionAdapter: NostrRelaySessionProtocol {
let base: URLSession
func webSocketTask(with url: URL) -> NostrRelayConnectionProtocol {
let task = base.webSocketTask(with: url)
// Byte bound per inbound frame; without it the per-relay buffer cap
// (nostrInboundPerRelayBufferCap) bounds FRAMES but not BYTES, and a
// hostile relay could pile up cap × 1 MiB (URLSession default) per
// connection. See TransportConfig.nostrInboundMaxFrameBytes for the
// sizing rationale. Oversized frames fail the receive with an error.
task.maximumMessageSize = TransportConfig.nostrInboundMaxFrameBytes
return URLSessionWebSocketTaskAdapter(base: task)
}
}
struct NostrRelayManagerDependencies {
var activationAllowed: () -> Bool
var userTorEnabled: () -> Bool
var hasMutualFavorites: () -> Bool
var hasLocationPermission: () -> Bool
var mutualFavoritesPublisher: AnyPublisher<Set<Data>, Never>
var locationPermissionPublisher: AnyPublisher<LocationChannelManager.PermissionState, Never>
var torEnforced: () -> Bool
var torIsReady: () -> Bool
var torIsForeground: () -> Bool
var awaitTorReady: (@escaping (Bool) -> Void) -> Void
var makeSession: () -> NostrRelaySessionProtocol
var scheduleAfter: @Sendable (TimeInterval, @escaping @Sendable () -> Void) -> Void
var now: () -> Date
/// Uniform random value in [0, 1) used to jitter reconnect backoff.
/// Injectable so tests can pin or sweep the jitter deterministically.
var jitterUnit: () -> Double
/// Where relay-settings changes are observed. Injectable so a test can use
/// its own center instead of racing the process-wide one.
var notificationCenter: NotificationCenter = .default
/// Relays added by hand, merged with the built-in set. Injectable so tests
/// do not have to write to shared preferences.
var customRelays: () -> [String] = { NostrRelaySettings.customRelays() }
/// Whether a location channel is currently open. Mirrors the third arm of
/// `NetworkActivationService`'s gate: teleporting into a geohash needs no
/// location permission, and without this the relays would stay filtered out
/// for someone who denied location and has no mutual favorites.
var isInLocationChannel: () -> Bool = { false }
var selectedChannelPublisher: AnyPublisher<ChannelID, Never> = Empty().eraseToAnyPublisher()
}
extension NostrRelayManagerDependencies {
@MainActor
static func live() -> Self {
Self(
activationAllowed: { NetworkActivationService.shared.activationAllowed },
userTorEnabled: { NetworkActivationService.shared.userTorEnabled },
hasMutualFavorites: { !FavoritesPersistenceService.shared.mutualFavorites.isEmpty },
hasLocationPermission: { LocationChannelManager.shared.permissionState == .authorized },
mutualFavoritesPublisher: FavoritesPersistenceService.shared.$mutualFavorites.eraseToAnyPublisher(),
locationPermissionPublisher: LocationChannelManager.shared.$permissionState.eraseToAnyPublisher(),
torEnforced: { TorManager.shared.torEnforced },
torIsReady: { TorManager.shared.isReady },
torIsForeground: { TorManager.shared.isForeground() },
awaitTorReady: { completion in
Task.detached {
let ready = await TorManager.shared.awaitReady()
await MainActor.run {
completion(ready)
}
}
},
makeSession: { URLSessionAdapter(base: TorURLSession.shared.session) },
scheduleAfter: { delay, action in
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: action)
},
now: Date.init,
jitterUnit: { Double.random(in: 0..<1) },
isInLocationChannel: {
if case .location = LocationChannelManager.shared.selectedChannel { return true }
return false
},
selectedChannelPublisher: LocationChannelManager.shared.$selectedChannel.eraseToAnyPublisher()
)
}
}
+228
View File
@@ -0,0 +1,228 @@
import Foundation
/// A single raw socket frame awaiting off-main parse + Schnorr verification.
struct InboundFrame: Sendable {
let message: URLSessionWebSocketTask.Message
}
/// Lock-guarded registry of per-relay inbound streams.
///
/// The raw WebSocket receive callback is not main-actor isolated, so it needs a
/// `Sendable` path to route a frame to the correct relay's stream without a
/// per-frame hop onto the main actor. Pipeline lifecycle (start/finish) is
/// driven from the main actor; frame delivery (`yield`) can come from any
/// thread. All access is serialized by a single lock — contention is negligible
/// because the guarded critical section is only a dictionary lookup + yield.
final class InboundFrameRouter: @unchecked Sendable {
/// Full cryptographic identity of a Nostr event being verified.
/// Including every field covered by the NIP-01 event ID + signature ensures
/// a forged/tampered copy can never coalesce onto — or poison — a genuine copy.
private struct VerificationFingerprint: Hashable {
let id: String
let pubkey: String
let createdAt: Int
let kind: Int
let tags: [[String]]
let content: String
let sig: String?
init(event: NostrEvent) {
self.id = event.id
self.pubkey = event.pubkey
self.createdAt = event.created_at
self.kind = event.kind
self.tags = event.tags
self.content = event.content
self.sig = event.sig
}
static func == (lhs: VerificationFingerprint, rhs: VerificationFingerprint) -> Bool {
lhs.id == rhs.id &&
lhs.pubkey == rhs.pubkey &&
lhs.createdAt == rhs.createdAt &&
lhs.kind == rhs.kind &&
lhs.sig == rhs.sig &&
lhs.content == rhs.content &&
lhs.tags == rhs.tags
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(pubkey)
hasher.combine(createdAt)
hasher.combine(kind)
hasher.combine(sig)
hasher.combine(content)
hasher.combine(tags)
}
}
private let lock = NSLock()
private var continuations: [String: AsyncStream<InboundFrame>.Continuation] = [:]
private var tasks: [String: Task<Void, Never>] = [:]
private var activeConnections: [String: ObjectIdentifier] = [:]
private var inFlightVerifications: [VerificationFingerprint: [CheckedContinuation<Bool, Never>]] = [:]
/// Start a relay's stream + consumer if one does not already exist.
/// Returns true when a new pipeline was created. The bounded
/// `.bufferingNewest` policy makes a single relay shed its OWN oldest
/// frames under a flood, never other relays' frames. Buffered memory per
/// relay is bounded (not eliminated) at the frame cap times the per-frame
/// byte cap (`maximumMessageSize`) — see TransportConfig.
func startPipeline(
for relayUrl: String,
connectionID: ObjectIdentifier,
makeConsumer: (AsyncStream<InboundFrame>) -> Task<Void, Never>
) -> Bool {
lock.lock()
defer { lock.unlock() }
activeConnections[relayUrl] = connectionID
if continuations[relayUrl] != nil { return false }
let (stream, continuation) = AsyncStream<InboundFrame>.makeStream(
bufferingPolicy: .bufferingNewest(TransportConfig.nostrInboundPerRelayBufferCap)
)
continuations[relayUrl] = continuation
tasks[relayUrl] = makeConsumer(stream)
return true
}
/// Route a frame to a relay's stream if `connectionID` is still the active
/// socket for `relayUrl`. Returns whether the caller should re-arm receive.
@discardableResult
func yield(_ frame: InboundFrame, to relayUrl: String, from connectionID: ObjectIdentifier) -> Bool {
lock.lock()
guard activeConnections[relayUrl] == connectionID,
let continuation = continuations[relayUrl] else {
lock.unlock()
return false
}
lock.unlock()
continuation.yield(frame)
return true
}
/// Verifies `event.isValidSignature()` while coalescing simultaneous fan-in
/// deliveries of byte-identical events across multiple relay pipelines.
func verifySignatureCoalesced(_ event: NostrEvent) async -> Bool {
let fingerprint = VerificationFingerprint(event: event)
let isOwner: Bool = {
lock.lock()
defer { lock.unlock() }
if inFlightVerifications[fingerprint] != nil {
return false
}
inFlightVerifications[fingerprint] = []
return true
}()
if isOwner {
let valid = event.isValidSignature()
let waiters: [CheckedContinuation<Bool, Never>] = {
lock.lock()
defer { lock.unlock() }
return inFlightVerifications.removeValue(forKey: fingerprint) ?? []
}()
for waiter in waiters {
waiter.resume(returning: valid)
}
return valid
}
return await withCheckedContinuation { continuation in
lock.lock()
if var waiters = inFlightVerifications[fingerprint] {
waiters.append(continuation)
inFlightVerifications[fingerprint] = waiters
lock.unlock()
} else {
lock.unlock()
continuation.resume(returning: event.isValidSignature())
}
}
}
/// Finish a relay's stream. The consumer drains any already-buffered frames
/// before exiting, so in-flight verified events are still delivered.
func finishPipeline(for relayUrl: String) {
lock.lock()
activeConnections.removeValue(forKey: relayUrl)
let continuation = continuations.removeValue(forKey: relayUrl)
tasks.removeValue(forKey: relayUrl)
lock.unlock()
continuation?.finish()
}
func finishAll() {
lock.lock()
let allContinuations = continuations
activeConnections.removeAll()
continuations.removeAll()
tasks.removeAll()
lock.unlock()
for continuation in allContinuations.values {
continuation.finish()
}
}
}
enum ParsedInbound {
case event(subId: String, event: NostrEvent)
case ok(eventId: String, success: Bool, reason: String)
case eose(subscriptionId: String)
init?(_ message: URLSessionWebSocketTask.Message) {
guard let data = message.dataWithinInboundLimit,
let array = try? JSONSerialization.jsonObject(with: data) as? [Any],
array.count >= 2,
let type = array[0] as? String else {
return nil
}
switch type {
case "EVENT":
if array.count >= 3,
let subId = array[1] as? String,
let eventDict = array[2] as? [String: Any],
let event = try? NostrEvent(from: eventDict) {
self = .event(subId: subId, event: event)
return
}
return nil
case "EOSE":
if let subId = array[1] as? String {
self = .eose(subscriptionId: subId)
return
}
return nil
case "OK":
if array.count >= 3,
let eventId = array[1] as? String,
let success = array[2] as? Bool {
let reason = array.count >= 4 ? (array[3] as? String ?? "no reason given") : "no reason given"
self = .ok(eventId: eventId, success: success, reason: reason)
return
}
return nil
default:
return nil
}
}
}
private extension URLSessionWebSocketTask.Message {
/// Prefer rejecting oversized frames before UTF-8/Data materialization
/// where we can (string length), and always before JSON parse.
var dataWithinInboundLimit: Data? {
let maxBytes = TransportConfig.nostrMaxInboundMessageBytes
switch self {
case .string(let text):
guard text.utf8.count <= maxBytes else { return nil }
return text.data(using: .utf8)
case .data(let data):
guard data.count <= maxBytes else { return nil }
return data
@unknown default:
return nil
}
}
}
-490
View File
@@ -1,130 +1,6 @@
import BitLogger
import Foundation
import Network
import Combine
import Tor
protocol NostrRelayConnectionProtocol: AnyObject {
func resume()
func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?)
func send(_ message: URLSessionWebSocketTask.Message, completionHandler: @escaping (Error?) -> Void)
func receive(completionHandler: @escaping (Result<URLSessionWebSocketTask.Message, Error>) -> Void)
func sendPing(pongReceiveHandler: @escaping (Error?) -> Void)
}
protocol NostrRelaySessionProtocol {
func webSocketTask(with url: URL) -> NostrRelayConnectionProtocol
}
private final class URLSessionWebSocketTaskAdapter: NostrRelayConnectionProtocol {
private let base: URLSessionWebSocketTask
init(base: URLSessionWebSocketTask) {
self.base = base
}
func resume() {
base.resume()
}
func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
base.cancel(with: closeCode, reason: reason)
}
func send(_ message: URLSessionWebSocketTask.Message, completionHandler: @escaping (Error?) -> Void) {
base.send(message, completionHandler: completionHandler)
}
func receive(completionHandler: @escaping (Result<URLSessionWebSocketTask.Message, Error>) -> Void) {
base.receive(completionHandler: completionHandler)
}
func sendPing(pongReceiveHandler: @escaping (Error?) -> Void) {
base.sendPing(pongReceiveHandler: pongReceiveHandler)
}
}
private struct URLSessionAdapter: NostrRelaySessionProtocol {
let base: URLSession
func webSocketTask(with url: URL) -> NostrRelayConnectionProtocol {
let task = base.webSocketTask(with: url)
// Byte bound per inbound frame; without it the per-relay buffer cap
// (nostrInboundPerRelayBufferCap) bounds FRAMES but not BYTES, and a
// hostile relay could pile up cap × 1 MiB (URLSession default) per
// connection. See TransportConfig.nostrInboundMaxFrameBytes for the
// sizing rationale. Oversized frames fail the receive with an error.
task.maximumMessageSize = TransportConfig.nostrInboundMaxFrameBytes
return URLSessionWebSocketTaskAdapter(base: task)
}
}
struct NostrRelayManagerDependencies {
var activationAllowed: () -> Bool
var userTorEnabled: () -> Bool
var hasMutualFavorites: () -> Bool
var hasLocationPermission: () -> Bool
var mutualFavoritesPublisher: AnyPublisher<Set<Data>, Never>
var locationPermissionPublisher: AnyPublisher<LocationChannelManager.PermissionState, Never>
var torEnforced: () -> Bool
var torIsReady: () -> Bool
var torIsForeground: () -> Bool
var awaitTorReady: (@escaping (Bool) -> Void) -> Void
var makeSession: () -> NostrRelaySessionProtocol
var scheduleAfter: @Sendable (TimeInterval, @escaping @Sendable () -> Void) -> Void
var now: () -> Date
/// Uniform random value in [0, 1) used to jitter reconnect backoff.
/// Injectable so tests can pin or sweep the jitter deterministically.
var jitterUnit: () -> Double
/// Where relay-settings changes are observed. Injectable so a test can use
/// its own center instead of racing the process-wide one.
var notificationCenter: NotificationCenter = .default
/// Relays added by hand, merged with the built-in set. Injectable so tests
/// do not have to write to shared preferences.
var customRelays: () -> [String] = { NostrRelaySettings.customRelays() }
/// Whether a location channel is currently open. Mirrors the third arm of
/// `NetworkActivationService`'s gate: teleporting into a geohash needs no
/// location permission, and without this the relays would stay filtered out
/// for someone who denied location and has no mutual favorites.
var isInLocationChannel: () -> Bool = { false }
var selectedChannelPublisher: AnyPublisher<ChannelID, Never> = Empty().eraseToAnyPublisher()
}
private extension NostrRelayManagerDependencies {
@MainActor
static func live() -> Self {
Self(
activationAllowed: { NetworkActivationService.shared.activationAllowed },
userTorEnabled: { NetworkActivationService.shared.userTorEnabled },
hasMutualFavorites: { !FavoritesPersistenceService.shared.mutualFavorites.isEmpty },
hasLocationPermission: { LocationChannelManager.shared.permissionState == .authorized },
mutualFavoritesPublisher: FavoritesPersistenceService.shared.$mutualFavorites.eraseToAnyPublisher(),
locationPermissionPublisher: LocationChannelManager.shared.$permissionState.eraseToAnyPublisher(),
torEnforced: { TorManager.shared.torEnforced },
torIsReady: { TorManager.shared.isReady },
torIsForeground: { TorManager.shared.isForeground() },
awaitTorReady: { completion in
Task.detached {
let ready = await TorManager.shared.awaitReady()
await MainActor.run {
completion(ready)
}
}
},
makeSession: { URLSessionAdapter(base: TorURLSession.shared.session) },
scheduleAfter: { delay, action in
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: action)
},
now: Date.init,
jitterUnit: { Double.random(in: 0..<1) },
isInLocationChannel: {
if case .location = LocationChannelManager.shared.selectedChannel { return true }
return false
},
selectedChannelPublisher: LocationChannelManager.shared.$selectedChannel.eraseToAnyPublisher()
)
}
}
/// Manages WebSocket connections to Nostr relays
@MainActor
@@ -1744,369 +1620,3 @@ final class NostrRelayManager: ObservableObject {
return false
}
}
// MARK: - Off-main inbound parsing helpers (file scope, non-isolated)
/// A single raw socket frame awaiting off-main parse + Schnorr verification.
private struct InboundFrame: Sendable {
let message: URLSessionWebSocketTask.Message
}
/// Lock-guarded registry of per-relay inbound streams.
///
/// The raw WebSocket receive callback is not main-actor isolated, so it needs a
/// `Sendable` path to route a frame to the correct relay's stream without a
/// per-frame hop onto the main actor. Pipeline lifecycle (start/finish) is
/// driven from the main actor; frame delivery (`yield`) can come from any
/// thread. All access is serialized by a single lock — contention is negligible
/// because the guarded critical section is only a dictionary lookup + yield.
private final class InboundFrameRouter: @unchecked Sendable {
/// Full cryptographic identity of a Nostr event being verified.
/// Including every field covered by the NIP-01 event ID + signature ensures
/// a forged/tampered copy can never coalesce onto — or poison — a genuine copy.
private struct VerificationFingerprint: Hashable {
let id: String
let pubkey: String
let createdAt: Int
let kind: Int
let tags: [[String]]
let content: String
let sig: String?
init(event: NostrEvent) {
self.id = event.id
self.pubkey = event.pubkey
self.createdAt = event.created_at
self.kind = event.kind
self.tags = event.tags
self.content = event.content
self.sig = event.sig
}
static func == (lhs: VerificationFingerprint, rhs: VerificationFingerprint) -> Bool {
lhs.id == rhs.id &&
lhs.pubkey == rhs.pubkey &&
lhs.createdAt == rhs.createdAt &&
lhs.kind == rhs.kind &&
lhs.sig == rhs.sig &&
lhs.content == rhs.content &&
lhs.tags == rhs.tags
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(pubkey)
hasher.combine(createdAt)
hasher.combine(kind)
hasher.combine(sig)
hasher.combine(content)
hasher.combine(tags)
}
}
private let lock = NSLock()
private var continuations: [String: AsyncStream<InboundFrame>.Continuation] = [:]
private var tasks: [String: Task<Void, Never>] = [:]
private var activeConnections: [String: ObjectIdentifier] = [:]
private var inFlightVerifications: [VerificationFingerprint: [CheckedContinuation<Bool, Never>]] = [:]
/// Start a relay's stream + consumer if one does not already exist.
/// Returns true when a new pipeline was created. The bounded
/// `.bufferingNewest` policy makes a single relay shed its OWN oldest
/// frames under a flood, never other relays' frames. Buffered memory per
/// relay is bounded (not eliminated) at the frame cap times the per-frame
/// byte cap (`maximumMessageSize`) — see TransportConfig.
func startPipeline(
for relayUrl: String,
connectionID: ObjectIdentifier,
makeConsumer: (AsyncStream<InboundFrame>) -> Task<Void, Never>
) -> Bool {
lock.lock()
defer { lock.unlock() }
activeConnections[relayUrl] = connectionID
if continuations[relayUrl] != nil { return false }
let (stream, continuation) = AsyncStream<InboundFrame>.makeStream(
bufferingPolicy: .bufferingNewest(TransportConfig.nostrInboundPerRelayBufferCap)
)
continuations[relayUrl] = continuation
tasks[relayUrl] = makeConsumer(stream)
return true
}
/// Route a frame to a relay's stream if `connectionID` is still the active
/// socket for `relayUrl`. Returns whether the caller should re-arm receive.
@discardableResult
func yield(_ frame: InboundFrame, to relayUrl: String, from connectionID: ObjectIdentifier) -> Bool {
lock.lock()
guard activeConnections[relayUrl] == connectionID,
let continuation = continuations[relayUrl] else {
lock.unlock()
return false
}
lock.unlock()
continuation.yield(frame)
return true
}
/// Verifies `event.isValidSignature()` while coalescing simultaneous fan-in
/// deliveries of byte-identical events across multiple relay pipelines.
func verifySignatureCoalesced(_ event: NostrEvent) async -> Bool {
let fingerprint = VerificationFingerprint(event: event)
let isOwner: Bool = {
lock.lock()
defer { lock.unlock() }
if inFlightVerifications[fingerprint] != nil {
return false
}
inFlightVerifications[fingerprint] = []
return true
}()
if isOwner {
let valid = event.isValidSignature()
let waiters: [CheckedContinuation<Bool, Never>] = {
lock.lock()
defer { lock.unlock() }
return inFlightVerifications.removeValue(forKey: fingerprint) ?? []
}()
for waiter in waiters {
waiter.resume(returning: valid)
}
return valid
}
return await withCheckedContinuation { continuation in
lock.lock()
if var waiters = inFlightVerifications[fingerprint] {
waiters.append(continuation)
inFlightVerifications[fingerprint] = waiters
lock.unlock()
} else {
lock.unlock()
continuation.resume(returning: event.isValidSignature())
}
}
}
/// Finish a relay's stream. The consumer drains any already-buffered frames
/// before exiting, so in-flight verified events are still delivered.
func finishPipeline(for relayUrl: String) {
lock.lock()
activeConnections.removeValue(forKey: relayUrl)
let continuation = continuations.removeValue(forKey: relayUrl)
tasks.removeValue(forKey: relayUrl)
lock.unlock()
continuation?.finish()
}
func finishAll() {
lock.lock()
let allContinuations = continuations
activeConnections.removeAll()
continuations.removeAll()
tasks.removeAll()
lock.unlock()
for continuation in allContinuations.values {
continuation.finish()
}
}
}
private enum ParsedInbound {
case event(subId: String, event: NostrEvent)
case ok(eventId: String, success: Bool, reason: String)
case eose(subscriptionId: String)
init?(_ message: URLSessionWebSocketTask.Message) {
guard let data = message.dataWithinInboundLimit,
let array = try? JSONSerialization.jsonObject(with: data) as? [Any],
array.count >= 2,
let type = array[0] as? String else {
return nil
}
switch type {
case "EVENT":
if array.count >= 3,
let subId = array[1] as? String,
let eventDict = array[2] as? [String: Any],
let event = try? NostrEvent(from: eventDict) {
self = .event(subId: subId, event: event)
return
}
return nil
case "EOSE":
if let subId = array[1] as? String {
self = .eose(subscriptionId: subId)
return
}
return nil
case "OK":
if array.count >= 3,
let eventId = array[1] as? String,
let success = array[2] as? Bool {
let reason = array.count >= 4 ? (array[3] as? String ?? "no reason given") : "no reason given"
self = .ok(eventId: eventId, success: success, reason: reason)
return
}
return nil
default:
return nil
}
}
}
private extension URLSessionWebSocketTask.Message {
/// Prefer rejecting oversized frames before UTF-8/Data materialization
/// where we can (string length), and always before JSON parse.
var dataWithinInboundLimit: Data? {
let maxBytes = TransportConfig.nostrMaxInboundMessageBytes
switch self {
case .string(let text):
guard text.utf8.count <= maxBytes else { return nil }
return text.data(using: .utf8)
case .data(let data):
guard data.count <= maxBytes else { return nil }
return data
@unknown default:
return nil
}
}
}
// MARK: - Nostr Protocol Types
enum NostrRequest: Encodable {
case event(NostrEvent)
case subscribe(id: String, filters: [NostrFilter])
case close(id: String)
func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
switch self {
case .event(let event):
try container.encode("EVENT")
try container.encode(event)
case .subscribe(let id, let filters):
try container.encode("REQ")
try container.encode(id)
for filter in filters {
try container.encode(filter)
}
case .close(let id):
try container.encode("CLOSE")
try container.encode(id)
}
}
}
struct NostrFilter: Encodable {
var ids: [String]?
var authors: [String]?
var kinds: [Int]?
var since: Int?
var until: Int?
var limit: Int?
// Tag filters - stored internally but encoded specially
fileprivate var tagFilters: [String: [String]]?
init() {
// Default initializer
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: DynamicCodingKey.self)
// Encode standard fields
if let ids = ids { try container.encode(ids, forKey: DynamicCodingKey(stringValue: "ids")) }
if let authors = authors { try container.encode(authors, forKey: DynamicCodingKey(stringValue: "authors")) }
if let kinds = kinds { try container.encode(kinds, forKey: DynamicCodingKey(stringValue: "kinds")) }
if let since = since { try container.encode(since, forKey: DynamicCodingKey(stringValue: "since")) }
if let until = until { try container.encode(until, forKey: DynamicCodingKey(stringValue: "until")) }
if let limit = limit { try container.encode(limit, forKey: DynamicCodingKey(stringValue: "limit")) }
// Encode tag filters with # prefix
if let tagFilters = tagFilters {
for (tag, values) in tagFilters {
try container.encode(values, forKey: DynamicCodingKey(stringValue: "#\(tag)"))
}
}
}
// For NIP-17 gift wraps
static func giftWrapsFor(pubkey: String, since: Date? = nil) -> NostrFilter {
var filter = NostrFilter()
filter.kinds = [1059] // Gift wrap kind
filter.since = since?.timeIntervalSince1970.toInt()
filter.tagFilters = ["p": [pubkey]]
filter.limit = TransportConfig.nostrRelayDefaultFetchLimit // reasonable limit
return filter
}
// For location channels: geohash-scoped ephemeral events (kind 20000) and presence (kind 20001)
static func geohashEphemeral(_ geohash: String, since: Date? = nil, limit: Int = 1000) -> NostrFilter {
var filter = NostrFilter()
filter.kinds = [20000, 20001]
filter.since = since?.timeIntervalSince1970.toInt()
filter.tagFilters = ["g": [geohash]]
filter.limit = limit
return filter
}
// For location notes with neighbors: subscribe to multiple geohashes (center + neighbors)
static func geohashNotes(_ geohashes: [String], since: Date? = nil, limit: Int = 200) -> NostrFilter {
var filter = NostrFilter()
filter.kinds = [1]
filter.since = since?.timeIntervalSince1970.toInt()
filter.tagFilters = ["g": geohashes]
filter.limit = limit
return filter
}
// For the mesh bridge: rendezvous messages (kind 20000) and presence
// (kind 20001) tagged `#r` with one or more cells (own + neighbors).
static func bridgeRendezvous(_ cells: [String], since: Date? = nil, limit: Int = 200) -> NostrFilter {
var filter = NostrFilter()
filter.kinds = [20000, 20001]
filter.since = since?.timeIntervalSince1970.toInt()
filter.tagFilters = ["r": cells]
filter.limit = limit
return filter
}
// For courier drops: sealed envelopes (kind 1401) parked under rotating
// recipient tags (`#x`, hex). Callers pass every candidate tag (adjacent
// UTC days x recipients) in one filter.
static func courierDrops(recipientTagsHex: [String], since: Date? = nil, limit: Int = 100) -> NostrFilter {
var filter = NostrFilter()
filter.kinds = [NostrProtocol.EventKind.courierDrop.rawValue]
filter.since = since?.timeIntervalSince1970.toInt()
filter.tagFilters = ["x": recipientTagsHex]
filter.limit = limit
return filter
}
}
// Dynamic coding key for tag filters
private struct DynamicCodingKey: CodingKey {
var stringValue: String
var intValue: Int? { nil }
init(stringValue: String) {
self.stringValue = stringValue
}
init?(intValue: Int) {
return nil
}
}
private extension TimeInterval {
func toInt() -> Int {
return Int(self)
}
}
+136
View File
@@ -0,0 +1,136 @@
import Foundation
enum NostrRequest: Encodable {
case event(NostrEvent)
case subscribe(id: String, filters: [NostrFilter])
case close(id: String)
func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
switch self {
case .event(let event):
try container.encode("EVENT")
try container.encode(event)
case .subscribe(let id, let filters):
try container.encode("REQ")
try container.encode(id)
for filter in filters {
try container.encode(filter)
}
case .close(let id):
try container.encode("CLOSE")
try container.encode(id)
}
}
}
struct NostrFilter: Encodable {
var ids: [String]?
var authors: [String]?
var kinds: [Int]?
var since: Int?
var until: Int?
var limit: Int?
// Tag filters - stored internally but encoded specially
fileprivate var tagFilters: [String: [String]]?
init() {
// Default initializer
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: DynamicCodingKey.self)
// Encode standard fields
if let ids = ids { try container.encode(ids, forKey: DynamicCodingKey(stringValue: "ids")) }
if let authors = authors { try container.encode(authors, forKey: DynamicCodingKey(stringValue: "authors")) }
if let kinds = kinds { try container.encode(kinds, forKey: DynamicCodingKey(stringValue: "kinds")) }
if let since = since { try container.encode(since, forKey: DynamicCodingKey(stringValue: "since")) }
if let until = until { try container.encode(until, forKey: DynamicCodingKey(stringValue: "until")) }
if let limit = limit { try container.encode(limit, forKey: DynamicCodingKey(stringValue: "limit")) }
// Encode tag filters with # prefix
if let tagFilters = tagFilters {
for (tag, values) in tagFilters {
try container.encode(values, forKey: DynamicCodingKey(stringValue: "#\(tag)"))
}
}
}
// For NIP-17 gift wraps
static func giftWrapsFor(pubkey: String, since: Date? = nil) -> NostrFilter {
var filter = NostrFilter()
filter.kinds = [1059] // Gift wrap kind
filter.since = since?.timeIntervalSince1970.toInt()
filter.tagFilters = ["p": [pubkey]]
filter.limit = TransportConfig.nostrRelayDefaultFetchLimit // reasonable limit
return filter
}
// For location channels: geohash-scoped ephemeral events (kind 20000) and presence (kind 20001)
static func geohashEphemeral(_ geohash: String, since: Date? = nil, limit: Int = 1000) -> NostrFilter {
var filter = NostrFilter()
filter.kinds = [20000, 20001]
filter.since = since?.timeIntervalSince1970.toInt()
filter.tagFilters = ["g": [geohash]]
filter.limit = limit
return filter
}
// For location notes with neighbors: subscribe to multiple geohashes (center + neighbors)
static func geohashNotes(_ geohashes: [String], since: Date? = nil, limit: Int = 200) -> NostrFilter {
var filter = NostrFilter()
filter.kinds = [1]
filter.since = since?.timeIntervalSince1970.toInt()
filter.tagFilters = ["g": geohashes]
filter.limit = limit
return filter
}
// For the mesh bridge: rendezvous messages (kind 20000) and presence
// (kind 20001) tagged `#r` with one or more cells (own + neighbors).
static func bridgeRendezvous(_ cells: [String], since: Date? = nil, limit: Int = 200) -> NostrFilter {
var filter = NostrFilter()
filter.kinds = [20000, 20001]
filter.since = since?.timeIntervalSince1970.toInt()
filter.tagFilters = ["r": cells]
filter.limit = limit
return filter
}
// For courier drops: sealed envelopes (kind 1401) parked under rotating
// recipient tags (`#x`, hex). Callers pass every candidate tag (adjacent
// UTC days x recipients) in one filter.
static func courierDrops(recipientTagsHex: [String], since: Date? = nil, limit: Int = 100) -> NostrFilter {
var filter = NostrFilter()
filter.kinds = [NostrProtocol.EventKind.courierDrop.rawValue]
filter.since = since?.timeIntervalSince1970.toInt()
filter.tagFilters = ["x": recipientTagsHex]
filter.limit = limit
return filter
}
}
// Dynamic coding key for tag filters
private struct DynamicCodingKey: CodingKey {
var stringValue: String
var intValue: Int? { nil }
init(stringValue: String) {
self.stringValue = stringValue
}
init?(intValue: Int) {
return nil
}
}
private extension TimeInterval {
func toInt() -> Int {
return Int(self)
}
}
@@ -40,9 +40,10 @@ struct BLEFileTransferHandlerEnvironment {
let commitPrivateMediaFile: (_ messageID: String, _ storedURL: URL) -> Bool
/// Rolls back a saved payload when its durable receipt commit fails.
let removeIncomingFile: (_ storedURL: URL) -> Void
/// Releases the allocator's save-to-UI ownership guard after synchronous
/// conversation insertion has completed.
let finishIncomingFileDelivery: (_ storedURL: URL) -> Void
/// Protects an incoming file from quota eviction while UI delivery is pending.
let beginPendingDelivery: (_ storedURL: URL) -> Void
/// Releases quota-eviction protection once UI delivery finalizes.
let finishPendingDelivery: (_ storedURL: URL) -> Void
/// Checks the authenticated sender before any private-media disk work.
let isPrivateMediaSenderBlocked: (PeerID) -> Bool
/// Updates the registry last-seen timestamp for the peer (async barrier write).
@@ -298,6 +299,7 @@ final class BLEFileTransferHandler {
"📁 Restored durable private media duplicate id=\(messageID.prefix(12))… from \(peerID.id.prefix(8))… -> \(existingFile.lastPathComponent)",
category: .session
)
env.beginPendingDelivery(existingFile)
deliverStableMessage(
message,
messageID: messageID,
@@ -346,10 +348,15 @@ final class BLEFileTransferHandler {
return false
}
// Protect the saved payload from quota eviction until its async UI
// delivery finalizes (or commit rollback removes it).
env.beginPendingDelivery(destination)
if let messageID,
!env.commitPrivateMediaFile(messageID, destination) {
// A payload without its durable ID mapping cannot safely suppress
// a retry after relaunch. Roll it back and withhold UI/ACK.
env.finishPendingDelivery(destination)
env.removeIncomingFile(destination)
return false
}
@@ -385,16 +392,11 @@ final class BLEFileTransferHandler {
{ true },
{},
{ outcome in
env.finishPendingDelivery(destination)
if outcome == .rejected {
// Raw media has no durable receipt that can redeliver
// it later. Do not leave a newly saved, UI-unowned file
// available for a stale fallback path to misidentify.
// it later; roll back the unowned file on disk.
env.removeIncomingFile(destination)
} else {
// Plain delegates are invoked without synchronous
// insertion confirmation. Preserve the payload for
// that supported delivery path.
env.finishIncomingFileDelivery(destination)
}
}
)
@@ -423,7 +425,7 @@ final class BLEFileTransferHandler {
env.acknowledgePrivateMedia(messageID, peerID)
},
{ _ in
env.finishIncomingFileDelivery(expectedURL)
env.finishPendingDelivery(expectedURL)
}
)
}
+128 -354
View File
@@ -38,7 +38,7 @@ struct PanicRecoveryOperations {
}
static func live(
fileStore: BLEIncomingFileStore = BLEIncomingFileStore(),
fileStore: BLEIncomingFileStore = .shared,
defaults: UserDefaults = .standard
) -> PanicRecoveryOperations {
let defaultsKey = "bitchat.panicResetPending"
@@ -94,6 +94,11 @@ struct PanicRecoveryOperations {
}
struct BLEIncomingFileStore: @unchecked Sendable {
/// Shared production store so `BLEService`, `PanicRecoveryOperations`,
/// `ChatLiveVoiceCoordinator`, and startup maintenance operate on a single
/// receipt cache and directory cache.
static let shared = BLEIncomingFileStore()
enum PanicRecoveryError: Error {
case externalMarkerCommitFailed
case markerWriteFailed(Error)
@@ -103,32 +108,45 @@ struct BLEIncomingFileStore: @unchecked Sendable {
)
}
struct PrivateMediaDeletionReservation: Sendable {
fileprivate let id: UUID
}
private final class PayloadCoordination: @unchecked Sendable {
let lock = NSLock()
var pendingDeliveryPaths: Set<String> = []
var deletionReservations: [UUID: Set<String>] = [:]
}
/// Separate leaf lock for resolved media directory caching so callers
/// holding or not holding `payloadCoordination.lock` can both query
/// `filesDirectory()` without lock ordering cycles.
private final class DirectoryCache: @unchecked Sendable {
let lock = NSLock()
var filesRoot: URL?
var incomingDirectoryPaths: Set<String> = []
var createdSubdirectories: Set<String> = []
var pendingDeliveryCounts: [String: Int] = [:]
func invalidate() {
lock.lock()
filesRoot = nil
incomingDirectoryPaths.removeAll(keepingCapacity: false)
createdSubdirectories.removeAll(keepingCapacity: false)
pendingDeliveryCounts.removeAll(keepingCapacity: false)
lock.unlock()
}
func beginPendingDelivery(path: String) {
lock.lock()
pendingDeliveryCounts[path, default: 0] += 1
lock.unlock()
}
func finishPendingDelivery(path: String) {
lock.lock()
if let count = pendingDeliveryCounts[path] {
if count <= 1 {
pendingDeliveryCounts.removeValue(forKey: path)
} else {
pendingDeliveryCounts[path] = count - 1
}
}
lock.unlock()
}
func pendingDeliveryPathsSnapshot() -> Set<String> {
lock.lock()
defer { lock.unlock() }
return Set(pendingDeliveryCounts.keys)
}
}
private static let defaultQuotaBytes: Int64 = 100 * 1024 * 1024
@@ -137,12 +155,8 @@ struct BLEIncomingFileStore: @unchecked Sendable {
static let defaultMediaRetention: TimeInterval = 7 * 24 * 60 * 60
/// Kept outside `files/` so deleting the media tree cannot erase the
/// fail-closed startup decision before the full panic has committed.
private static let panicRecoveryPendingMarkerFileName =
".panic-recovery-pending"
/// Compatibility with a short-lived development build that used the
/// media-specific name for the same full-transaction latch.
private static let legacyPanicRecoveryPendingMarkerFileName =
".panic-media-wipe-pending"
private static let panicRecoveryPendingMarkerFileName = ".panic-recovery-pending"
private static let legacyPanicRecoveryPendingMarkerFileName = ".panic-media-wipe-pending"
private static let mediaSubdirectories = [
"voicenotes/incoming",
"voicenotes/outgoing",
@@ -171,12 +185,6 @@ struct BLEIncomingFileStore: @unchecked Sendable {
/// orphans a previous session left behind.
static let liveCapturePrefix = "voice_live_"
/// Media payloads follow the same at-rest posture as the app's other
/// persistence layers (courier, outbox, receipt index): protected until
/// first unlock, so the launch-time retention sweep can still run after
/// a reboot. Applied to the media directories so recordings that save
/// as they go (live captures, `AVAudioRecorder`) inherit it, and stated
/// explicitly at the payload write site like every other store.
static var mediaProtectionAttributes: [FileAttributeKey: Any]? {
#if os(iOS)
return [.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication]
@@ -193,7 +201,6 @@ struct BLEIncomingFileStore: @unchecked Sendable {
private let panicMarkerWriter: (Data, URL) throws -> Void
private let quotaBytes: Int64
private let privateMediaReceipts: BLEPrivateMediaReceiptStore
private let payloadCoordination: PayloadCoordination
private let directoryCache: DirectoryCache
init(
@@ -215,35 +222,16 @@ struct BLEIncomingFileStore: @unchecked Sendable {
baseDirectory: baseDirectory,
now: dateProvider
)
self.payloadCoordination = PayloadCoordination()
self.directoryCache = DirectoryCache()
}
/// Panic-wipe every managed incoming and outgoing media artifact before
/// returning. Recreating the directory tree keeps later capture/receive
/// paths usable without allowing a detached cleanup task to race them.
///
/// Marker persistence and deletion are deliberately separate error
/// domains: even when both durable marker channels fail, deletion is
/// still attempted before this method reports the marker failure.
func panicWipe(
hasDurablePendingMarker: Bool = false
) throws {
// The receipt index caches tombstones as well as accepted payloads,
// while payload coordination retains save/delete reservations. Always
// invalidate both on return, including partial-failure paths, so no
// pre-panic receiver decision survives after identity reset.
func panicWipe(hasDurablePendingMarker: Bool = false) throws {
defer {
privateMediaReceipts.resetForPanic()
directoryCache.invalidate()
payloadCoordination.lock.lock()
payloadCoordination.pendingDeliveryPaths.removeAll(
keepingCapacity: false
)
payloadCoordination.deletionReservations.removeAll(
keepingCapacity: false
)
payloadCoordination.lock.unlock()
}
let markerError: Error?
@@ -266,10 +254,7 @@ struct BLEIncomingFileStore: @unchecked Sendable {
}
for subdirectory in Self.mediaSubdirectories {
try fileManager.createDirectory(
at: filesDirectory.appendingPathComponent(
subdirectory,
isDirectory: true
),
at: filesDirectory.appendingPathComponent(subdirectory, isDirectory: true),
withIntermediateDirectories: true,
attributes: Self.mediaProtectionAttributes
)
@@ -318,6 +303,9 @@ struct BLEIncomingFileStore: @unchecked Sendable {
try ensureSubdirectory(subdirectory)
}
/// Writes an incoming payload to a globally unique `<uuid>_<sanitizedName>`
/// file so distinct transfers, retries, and post-eviction arrivals never
/// collide on a shared basename.
func save(
data: Data,
preferredName: String?,
@@ -325,9 +313,6 @@ struct BLEIncomingFileStore: @unchecked Sendable {
fallbackExtension: String?,
defaultPrefix: String
) -> URL? {
payloadCoordination.lock.lock()
defer { payloadCoordination.lock.unlock() }
do {
let base = try ensureSubdirectory(subdirectory)
let sanitized = sanitizedFileName(
@@ -335,30 +320,12 @@ struct BLEIncomingFileStore: @unchecked Sendable {
defaultName: "\(defaultPrefix)_\(Self.timestampString(from: dateProvider()))",
fallbackExtension: fallbackExtension
)
let reservedPaths = privateMediaReceipts.reservedPayloadPaths()
let deletionPaths = payloadCoordination
.deletionReservations.values.reduce(into: Set<String>()) {
$0.formUnion($1)
}
let allocationReservations = deletionPaths.union(
payloadCoordination.pendingDeliveryPaths
)
let destination = uniqueFileURL(
in: base,
fileName: sanitized,
reservedPaths: (reservedPaths ?? []).union(
allocationReservations
),
forceRandomizedName: reservedPaths == nil
)
let destination = uniqueFileURL(in: base, sanitizedName: sanitized)
var options: Data.WritingOptions = [.atomic]
#if os(iOS)
options.insert(.completeFileProtectionUntilFirstUserAuthentication)
#endif
try data.write(to: destination, options: options)
payloadCoordination.pendingDeliveryPaths.insert(
destination.standardizedFileURL.path
)
return destination
} catch {
SecureLogger.error("❌ Failed to persist incoming media: \(error)", category: .session)
@@ -366,119 +333,50 @@ struct BLEIncomingFileStore: @unchecked Sendable {
}
}
/// Drops THIS instance's in-memory receipt index after a panic wipe.
///
/// `panicWipe` already resets the receipt store it runs on, but the
/// production wipe runs on the `PanicRecoveryOperations.live()` file
/// store while receipt lookups are served by `BLEService`'s own
/// `incomingFileStore`. The service's panic path must invalidate its own
/// cache explicitly or pre-panic decisions survive in memory.
func resetPrivateMediaReceiptsForPanic() {
privateMediaReceipts.resetForPanic()
}
func privateMediaReceiptState(
messageID: String
) -> BLEPrivateMediaReceiptState {
/// Marks an incoming file as awaiting asynchronous UI delivery so quota
/// eviction and age-based retention cannot unlink it before the UI receives
/// the message. Ref-counted per standardized path.
func beginPendingDelivery(at url: URL) {
directoryCache.beginPendingDelivery(path: url.standardizedFileURL.path)
}
func finishPendingDelivery(at url: URL) {
directoryCache.finishPendingDelivery(path: url.standardizedFileURL.path)
}
func privateMediaReceiptState(messageID: String) -> BLEPrivateMediaReceiptState {
privateMediaReceipts.state(for: messageID)
}
func commitPrivateMediaFile(
messageID: String,
storedURL: URL
) -> Bool {
privateMediaReceipts.commitAccepted(
messageID: messageID,
storedURL: storedURL
)
}
/// Reserves every receipt/UI path before the asynchronous deletion
/// barrier. Allocation and reservation share one lock, so either an
/// in-flight raw arrival is observed and deletion fails closed, or the
/// arrival is forced onto a different filename.
func reservePrivateMediaDeletion(
messageIDs: [String],
payloadRelativePaths: [String: String]
) -> PrivateMediaDeletionReservation? {
payloadCoordination.lock.lock()
defer { payloadCoordination.lock.unlock() }
guard let paths = privateMediaReceipts
.prospectiveDeletionPayloadPaths(
messageIDs: messageIDs,
payloadRelativePaths: payloadRelativePaths
),
paths.isDisjoint(
with: payloadCoordination.pendingDeliveryPaths
) else {
return nil
}
let reservation = PrivateMediaDeletionReservation(id: UUID())
payloadCoordination.deletionReservations[reservation.id] = paths
return reservation
func commitPrivateMediaFile(messageID: String, storedURL: URL) -> Bool {
privateMediaReceipts.commitAccepted(messageID: messageID, storedURL: storedURL)
}
func commitPrivateMediaDeletion(
reservation: PrivateMediaDeletionReservation,
messageIDs: [String],
payloadRelativePaths: [String: String],
protectedPayloadRelativePaths: Set<String>
payloadRelativePaths: [String: String]
) -> Bool {
payloadCoordination.lock.lock()
defer {
payloadCoordination.deletionReservations.removeValue(
forKey: reservation.id
)
payloadCoordination.lock.unlock()
}
guard payloadCoordination.deletionReservations[reservation.id] != nil
else {
return false
}
return privateMediaReceipts.recordDeleted(
privateMediaReceipts.recordDeleted(
messageIDs: messageIDs,
payloadRelativePaths: payloadRelativePaths,
protectedPayloadRelativePaths: protectedPayloadRelativePaths
payloadRelativePaths: payloadRelativePaths
)
}
/// Explicit deletion of a LEGACY (non-stable-ID) incoming payload.
///
/// Legacy media has no durable receipt, so the only safe unlink is one
/// that can prove no other owner may hold the basename: the path must
/// not be pending delivery, must not belong to an in-flight deletion
/// reservation, and must not be owned by a stable receipt or journal
/// entry. When any of those hold — or receipt state cannot be read —
/// the file stays for bounded quota cleanup (the fail-safe fallback).
/// Returns true only when the payload was verifiably unlinked.
/// Explicit deletion of a legacy (non-stable-ID) incoming payload.
/// Deletes only regular files directly inside an incoming media directory
/// that are not owned by any stable receipt.
@discardableResult
func removeLegacyIncomingFile(relativePath: String) -> Bool {
payloadCoordination.lock.lock()
defer { payloadCoordination.lock.unlock() }
guard let payload = incomingPayloadURL(
relativePath: relativePath
) else {
return false
}
let standardizedPath = payload.standardizedFileURL.path
let reservedByDeletion = payloadCoordination.deletionReservations
.values.contains { $0.contains(standardizedPath) }
guard !reservedByDeletion,
!payloadCoordination.pendingDeliveryPaths.contains(
standardizedPath
),
let receiptOwnedPaths =
privateMediaReceipts.reservedPayloadPaths(),
!receiptOwnedPaths.contains(standardizedPath) else {
guard let payload = incomingPayloadURL(relativePath: relativePath),
privateMediaReceipts.isPayloadOwned(relativePath: relativePath) == false else {
return false
}
guard fileManager.fileExists(atPath: payload.path),
(try? payload.resourceValues(
forKeys: [.isRegularFileKey]
).isRegularFile) == true else {
(try? payload.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true else {
return false
}
do {
@@ -493,42 +391,9 @@ struct BLEIncomingFileStore: @unchecked Sendable {
}
}
/// Resolves a `files/`-relative path iff it lands directly inside one of
/// the incoming media directories. Anything else is not a deletable
/// incoming payload.
private func incomingPayloadURL(relativePath: String) -> URL? {
guard !relativePath.isEmpty,
let resolved = try? resolvedFilesRootAndIncomingPaths() else {
return nil
}
let candidate = resolved.filesRoot
.appendingPathComponent(relativePath, isDirectory: false)
.standardizedFileURL
let parentPath = candidate.deletingLastPathComponent().path
guard resolved.incomingPaths.contains(parentPath) else {
return nil
}
return candidate
}
/// Releases the short window between disk save and synchronous
/// conversation insertion. Before this callback, a deletion transaction
/// may not infer ownership from a stale bubble that names the same path.
func finishIncomingFileDelivery(at storedURL: URL) {
payloadCoordination.lock.lock()
defer { payloadCoordination.lock.unlock() }
payloadCoordination.pendingDeliveryPaths.remove(
storedURL.standardizedFileURL.path
)
}
/// Best-effort rollback for a payload whose durable receipt commit failed.
/// Best-effort rollback for a payload whose durable receipt commit failed
/// or whose raw delivery was rejected.
func removeIncomingFile(at storedURL: URL) {
payloadCoordination.lock.lock()
defer { payloadCoordination.lock.unlock() }
payloadCoordination.pendingDeliveryPaths.remove(
storedURL.standardizedFileURL.path
)
guard isURLInsideFilesDirectory(storedURL) else { return }
do {
try fileManager.removeItem(at: storedURL)
@@ -541,29 +406,21 @@ struct BLEIncomingFileStore: @unchecked Sendable {
}
/// Frees least-recently-modified incoming files until `reservingBytes`
/// fits under the quota. Files named `voice_live_*` (in-flight live
/// captures) are never evicted regardless of who triggers enforcement —
/// a finalized transfer can arrive at quota while a burst is still
/// streaming — but they still count toward usage.
/// fits under the quota. In-flight `voice_live_*` captures are never evicted
/// but still count toward usage.
func enforceQuota(reservingBytes: Int) {
payloadCoordination.lock.lock()
defer { payloadCoordination.lock.unlock() }
do {
let base = try filesDirectory()
let incomingDirs = [
base.appendingPathComponent("voicenotes/incoming", isDirectory: true),
base.appendingPathComponent("images/incoming", isDirectory: true),
base.appendingPathComponent("files/incoming", isDirectory: true)
]
var allFiles: [(url: URL, size: Int64, modified: Date)] = []
for dir in incomingDirs where fileManager.fileExists(atPath: dir.path) {
guard let contents = try? fileManager.contentsOfDirectory(
at: dir,
includingPropertiesForKeys: [.fileSizeKey, .contentModificationDateKey],
options: [.skipsHiddenFiles]
) else { continue }
for subdirectory in Self.incomingSubdirectories {
let dir = base.appendingPathComponent(subdirectory, isDirectory: true)
guard fileManager.fileExists(atPath: dir.path),
let contents = try? fileManager.contentsOfDirectory(
at: dir,
includingPropertiesForKeys: [.fileSizeKey, .contentModificationDateKey],
options: [.skipsHiddenFiles]
) else { continue }
for fileURL in contents {
guard let attrs = try? fileURL.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]),
@@ -578,22 +435,12 @@ struct BLEIncomingFileStore: @unchecked Sendable {
guard currentUsage > targetUsage else { return }
let needToFree = currentUsage - targetUsage
let activeDeletionPaths = payloadCoordination
.deletionReservations.values.reduce(into: Set<String>()) {
$0.formUnion($1)
}
let protectedPaths = activeDeletionPaths.union(
payloadCoordination.pendingDeliveryPaths
)
let protectedPaths = directoryCache.pendingDeliveryPathsSnapshot()
var freedSpace: Int64 = 0
for file in allFiles.sorted(by: { $0.modified < $1.modified }) {
guard freedSpace < needToFree else { break }
guard !file.url.lastPathComponent.hasPrefix(Self.liveCapturePrefix) else { continue }
guard !protectedPaths.contains(
file.url.standardizedFileURL.path
) else {
continue
}
guard !file.url.lastPathComponent.hasPrefix(Self.liveCapturePrefix),
!protectedPaths.contains(file.url.standardizedFileURL.path) else { continue }
do {
try fileManager.removeItem(at: file.url)
freedSpace += file.size
@@ -612,54 +459,34 @@ struct BLEIncomingFileStore: @unchecked Sendable {
}
/// Deletes managed media older than `retention`, across both incoming and
/// outgoing directories, and reports how many files went away.
///
/// The quota sweep above only bounds *size*, and only for incoming files,
/// so a received photo or a sent voice note could sit on disk unbounded in
/// time — long outliving the conversation it belonged to, which is what a
/// seized device gives up. This bounds media by age instead, on the same
/// principle as the courier envelope and gossip archive lifetimes.
///
/// Honors the same exclusions as quota eviction: in-flight live captures
/// and files reserved by an in-progress delivery or deletion are left
/// alone regardless of age.
/// outgoing directories, skipping in-flight live captures.
@discardableResult
func expireAgedMedia(retention: TimeInterval = Self.defaultMediaRetention) -> Int {
guard retention > 0 else { return 0 }
payloadCoordination.lock.lock()
defer { payloadCoordination.lock.unlock() }
let cutoff = dateProvider().addingTimeInterval(-retention)
let activeDeletionPaths = payloadCoordination
.deletionReservations.values.reduce(into: Set<String>()) {
$0.formUnion($1)
}
let protectedPaths = activeDeletionPaths.union(
payloadCoordination.pendingDeliveryPaths
)
let protectedPaths = directoryCache.pendingDeliveryPathsSnapshot()
var removed = 0
do {
let base = try filesDirectory()
for subdirectory in Self.mediaSubdirectories {
let dir = base.appendingPathComponent(subdirectory, isDirectory: true)
guard fileManager.fileExists(atPath: dir.path) else { continue }
guard let contents = try? fileManager.contentsOfDirectory(
at: dir,
includingPropertiesForKeys: [.contentModificationDateKey],
options: [.skipsHiddenFiles]
) else { continue }
guard fileManager.fileExists(atPath: dir.path),
let contents = try? fileManager.contentsOfDirectory(
at: dir,
includingPropertiesForKeys: [.contentModificationDateKey],
options: [.skipsHiddenFiles]
) else { continue }
for fileURL in contents {
guard let modified = try? fileURL.resourceValues(
forKeys: [.contentModificationDateKey]
).contentModificationDate else { continue }
guard modified < cutoff else { continue }
guard !fileURL.lastPathComponent.hasPrefix(Self.liveCapturePrefix) else { continue }
guard !protectedPaths.contains(
fileURL.standardizedFileURL.path
) else { continue }
).contentModificationDate,
modified < cutoff,
!fileURL.lastPathComponent.hasPrefix(Self.liveCapturePrefix),
!protectedPaths.contains(fileURL.standardizedFileURL.path) else {
continue
}
do {
try fileManager.removeItem(at: fileURL)
@@ -673,10 +500,7 @@ struct BLEIncomingFileStore: @unchecked Sendable {
}
}
} catch {
SecureLogger.warning(
"⚠️ Could not expire aged media: \(error)",
category: .security
)
SecureLogger.warning("⚠️ Could not expire aged media: \(error)", category: .security)
return removed
}
@@ -689,17 +513,8 @@ struct BLEIncomingFileStore: @unchecked Sendable {
return removed
}
/// Stamps the media directories and any resident payloads with the
/// explicit protection class, covering files written by builds that
/// relied on the container default. Runs every launch: re-stamping an
/// equal class is a metadata no-op, and anything carrying a stronger
/// class is left alone, so repetition is cheap and can never downgrade.
/// In-flight live captures are skipped for symmetry with the retention
/// sweep; they receive the class at creation and need no repair.
/// Best-effort like the sweep it runs alongside; a file that cannot be
/// stamped is logged, not fatal, and the migration moves on to the next
/// item. Returns the number of items stamped so the launch path and
/// tests can observe coverage.
/// Stamps media directories and resident payloads with the explicit
/// protection class, leaving stronger classes untouched.
@discardableResult
func migrateFileProtectionIfNeeded() -> Int {
#if os(iOS)
@@ -727,13 +542,6 @@ struct BLEIncomingFileStore: @unchecked Sendable {
}
#if os(iOS)
/// Applies the class to one item, but only when the item currently sits
/// at the container default or weaker. The list names the classes that
/// are safe to replace; anything else, including classes added in later
/// iOS versions, is left alone. Only regular files are stamped when
/// `requireRegularFile` is set (and only real directories otherwise),
/// matching the caution the legacy-file removal path applies; symlinks
/// and other non-regular files are left untouched.
private func stampProtectionIfWeaker(
_ itemURL: URL,
requireRegularFile: Bool,
@@ -756,20 +564,31 @@ struct BLEIncomingFileStore: @unchecked Sendable {
try fileManager.setAttributes(attributes, ofItemAtPath: itemURL.path)
return 1
} catch let error as CocoaError where error.code == .fileNoSuchFile {
// Quota eviction or a deletion commit on another store instance
// can delete an item out from under this migration; that is not
// a failure.
return 0
} catch {
SecureLogger.warning(
"⚠️ Failed to migrate media file protection: \(error)",
category: .security
)
SecureLogger.warning("⚠️ Failed to migrate media file protection: \(error)", category: .security)
return 0
}
}
#endif
// MARK: - Helpers
private func incomingPayloadURL(relativePath: String) -> URL? {
guard !relativePath.isEmpty,
let resolved = try? resolvedFilesRootAndIncomingPaths() else {
return nil
}
let candidate = resolved.filesRoot
.appendingPathComponent(relativePath, isDirectory: false)
.standardizedFileURL
let parentPath = candidate.deletingLastPathComponent().path
guard resolved.incomingPaths.contains(parentPath) else {
return nil
}
return candidate
}
private func resolvedFilesRootAndIncomingPaths() throws -> (filesRoot: URL, incomingPaths: Set<String>) {
directoryCache.lock.lock()
if let cachedRoot = directoryCache.filesRoot {
@@ -823,23 +642,14 @@ struct BLEIncomingFileStore: @unchecked Sendable {
}
private func panicRecoveryPendingMarkerURL() throws -> URL {
try rootDirectory().appendingPathComponent(
Self.panicRecoveryPendingMarkerFileName,
isDirectory: false
)
try rootDirectory().appendingPathComponent(Self.panicRecoveryPendingMarkerFileName, isDirectory: false)
}
private func panicRecoveryMarkerURLs() throws -> [URL] {
let root = try rootDirectory()
return [
root.appendingPathComponent(
Self.panicRecoveryPendingMarkerFileName,
isDirectory: false
),
root.appendingPathComponent(
Self.legacyPanicRecoveryPendingMarkerFileName,
isDirectory: false
)
root.appendingPathComponent(Self.panicRecoveryPendingMarkerFileName, isDirectory: false),
root.appendingPathComponent(Self.legacyPanicRecoveryPendingMarkerFileName, isDirectory: false)
]
}
@@ -861,12 +671,14 @@ struct BLEIncomingFileStore: @unchecked Sendable {
if candidate.isEmpty { candidate = defaultName }
if candidate.hasPrefix(".") { candidate = "_" + candidate }
if candidate.count > 120 {
// Reserve room for the 37-character "<uuid>_" prefix within a 120-char cap.
let maxSanitizedLength = 80
if candidate.count > maxSanitizedLength {
let ext = (candidate as NSString).pathExtension
let base = (candidate as NSString).deletingPathExtension
candidate = ext.isEmpty
? String(candidate.prefix(120))
: String(base.prefix(max(10, 120 - ext.count - 1))) + "." + ext
? String(candidate.prefix(maxSanitizedLength))
: String(base.prefix(max(10, maxSanitizedLength - ext.count - 1))) + "." + ext
}
if let fallbackExtension, (candidate as NSString).pathExtension.isEmpty {
@@ -876,53 +688,15 @@ struct BLEIncomingFileStore: @unchecked Sendable {
return candidate.isEmpty ? defaultName : candidate
}
private func uniqueFileURL(
in directory: URL,
fileName: String,
reservedPaths: Set<String>,
forceRandomizedName: Bool
) -> URL {
private func uniqueFileURL(in directory: URL, sanitizedName: String) -> URL {
let directoryPath = directory.standardizedFileURL.path
func isInsideDirectory(_ url: URL) -> Bool {
url.standardizedFileURL.path.hasPrefix(directoryPath + "/")
let uniqueName = "\(UUID().uuidString)_\(sanitizedName)"
let candidate = directory.appendingPathComponent(uniqueName, isDirectory: false)
guard candidate.standardizedFileURL.path.hasPrefix(directoryPath + "/") else {
SecureLogger.warning("⚠️ Path traversal blocked: \(sanitizedName)", category: .security)
return directory.appendingPathComponent("blocked_\(UUID().uuidString)", isDirectory: false)
}
func isAvailable(_ url: URL) -> Bool {
!reservedPaths.contains(url.standardizedFileURL.path)
&& !fileManager.fileExists(atPath: url.path)
}
var candidate = directory.appendingPathComponent(fileName)
guard isInsideDirectory(candidate) else {
SecureLogger.warning("⚠️ Path traversal blocked: \(fileName)", category: .security)
return directory.appendingPathComponent("blocked_\(UUID().uuidString)")
}
let baseName = (fileName as NSString).deletingPathExtension
let ext = (fileName as NSString).pathExtension
if forceRandomizedName {
let suffix = UUID().uuidString
let randomizedName = ext.isEmpty
? "\(baseName)_\(suffix)"
: "\(baseName)_\(suffix).\(ext)"
return directory.appendingPathComponent(randomizedName)
}
if isAvailable(candidate) {
return candidate
}
for counter in 1..<100 {
let newName = ext.isEmpty ? "\(baseName) (\(counter))" : "\(baseName) (\(counter)).\(ext)"
candidate = directory.appendingPathComponent(newName)
guard isInsideDirectory(candidate) else {
return directory.appendingPathComponent("blocked_\(UUID().uuidString)")
}
if isAvailable(candidate) {
return candidate
}
}
return directory.appendingPathComponent("\(baseName)_\(UUID().uuidString).\(ext.isEmpty ? "dat" : ext)")
return candidate
}
private static func timestampString(from date: Date) -> String {
@@ -143,3 +143,83 @@ struct BLEIngressLinkRegistry {
packet.isRSR && packet.ttl == 0
}
}
// MARK: - Ingress Packet Guard
enum BLEIngressPacketGuard {
enum Rejection: Error, Equatable {
case selfLoopback(packetType: UInt8)
case directSenderMismatch(boundPeerID: PeerID, claimedSenderID: PeerID)
case invalidRSR(peerID: PeerID)
case timestampSkew(peerID: PeerID, skewMs: UInt64, maxSkewMs: UInt64)
}
static func evaluate(
packet: BitchatPacket,
claimedSenderID: PeerID,
boundPeerID: PeerID?,
localPeerID: PeerID,
directAnnounceTTL: UInt8,
nowMs: UInt64 = UInt64(Date().timeIntervalSince1970 * 1000),
maxTimestampSkewMs: UInt64 = TransportConfig.bleMaxTimestampSkewMs,
isValidSyncResponse: (PeerID) -> Bool
) -> Result<BLEIngressPacketContext, Rejection> {
let contextResult = BLEIngressLinkRegistry.packetContext(
for: packet,
claimedSenderID: claimedSenderID,
boundPeerID: boundPeerID,
localPeerID: localPeerID,
directAnnounceTTL: directAnnounceTTL
)
let context: BLEIngressPacketContext
switch contextResult {
case .success(let acceptedContext):
context = acceptedContext
case .failure(.selfLoopback(let packetType)):
return .failure(.selfLoopback(packetType: packetType))
case .failure(.directSenderMismatch(let boundPeerID, let claimedSenderID)):
return .failure(.directSenderMismatch(boundPeerID: boundPeerID, claimedSenderID: claimedSenderID))
}
switch validatePayload(
packet,
from: context.validationPeerID,
nowMs: nowMs,
maxTimestampSkewMs: maxTimestampSkewMs,
isValidSyncResponse: isValidSyncResponse
) {
case .success:
return .success(context)
case .failure(let rejection):
return .failure(rejection)
}
}
static func validatePayload(
_ packet: BitchatPacket,
from peerID: PeerID,
nowMs: UInt64 = UInt64(Date().timeIntervalSince1970 * 1000),
maxTimestampSkewMs: UInt64 = TransportConfig.bleMaxTimestampSkewMs,
isValidSyncResponse: (PeerID) -> Bool
) -> Result<Void, Rejection> {
let packetTime = packet.timestamp
if packet.isRSR {
guard isValidSyncResponse(peerID) else {
return .failure(.invalidRSR(peerID: peerID))
}
guard packetTime <= nowMs || packetTime - nowMs <= maxTimestampSkewMs else {
return .failure(.timestampSkew(peerID: peerID, skewMs: packetTime - nowMs, maxSkewMs: maxTimestampSkewMs))
}
return .success(())
}
let skew = packetTime > nowMs ? packetTime - nowMs : nowMs - packetTime
guard skew <= maxTimestampSkewMs else {
return .failure(.timestampSkew(peerID: peerID, skewMs: skew, maxSkewMs: maxTimestampSkewMs))
}
return .success(())
}
}
@@ -1,84 +0,0 @@
import BitFoundation
import Foundation
enum BLEIngressPacketGuard {
enum Rejection: Error, Equatable {
case selfLoopback(packetType: UInt8)
case directSenderMismatch(boundPeerID: PeerID, claimedSenderID: PeerID)
case invalidRSR(peerID: PeerID)
case timestampSkew(peerID: PeerID, skewMs: UInt64, maxSkewMs: UInt64)
}
static func evaluate(
packet: BitchatPacket,
claimedSenderID: PeerID,
boundPeerID: PeerID?,
localPeerID: PeerID,
directAnnounceTTL: UInt8,
nowMs: UInt64 = UInt64(Date().timeIntervalSince1970 * 1000),
maxTimestampSkewMs: UInt64 = TransportConfig.bleMaxTimestampSkewMs,
isValidSyncResponse: (PeerID) -> Bool
) -> Result<BLEIngressPacketContext, Rejection> {
let contextResult = BLEIngressLinkRegistry.packetContext(
for: packet,
claimedSenderID: claimedSenderID,
boundPeerID: boundPeerID,
localPeerID: localPeerID,
directAnnounceTTL: directAnnounceTTL
)
let context: BLEIngressPacketContext
switch contextResult {
case .success(let acceptedContext):
context = acceptedContext
case .failure(.selfLoopback(let packetType)):
return .failure(.selfLoopback(packetType: packetType))
case .failure(.directSenderMismatch(let boundPeerID, let claimedSenderID)):
return .failure(.directSenderMismatch(boundPeerID: boundPeerID, claimedSenderID: claimedSenderID))
}
switch validatePayload(
packet,
from: context.validationPeerID,
nowMs: nowMs,
maxTimestampSkewMs: maxTimestampSkewMs,
isValidSyncResponse: isValidSyncResponse
) {
case .success:
return .success(context)
case .failure(let rejection):
return .failure(rejection)
}
}
static func validatePayload(
_ packet: BitchatPacket,
from peerID: PeerID,
nowMs: UInt64 = UInt64(Date().timeIntervalSince1970 * 1000),
maxTimestampSkewMs: UInt64 = TransportConfig.bleMaxTimestampSkewMs,
isValidSyncResponse: (PeerID) -> Bool
) -> Result<Void, Rejection> {
let packetTime = packet.timestamp
if packet.isRSR {
guard isValidSyncResponse(peerID) else {
return .failure(.invalidRSR(peerID: peerID))
}
// Sync replies legitimately replay old packets, so only the past
// bound is waived. A far-future packet is never legitimate: it
// would outlive every gossip freshness window, drag requesters'
// since-cursors past all real history, and pin itself below live
// chat.
guard packetTime <= nowMs || packetTime - nowMs <= maxTimestampSkewMs else {
return .failure(.timestampSkew(peerID: peerID, skewMs: packetTime - nowMs, maxSkewMs: maxTimestampSkewMs))
}
return .success(())
}
let skew = packetTime > nowMs ? packetTime - nowMs : nowMs - packetTime
guard skew <= maxTimestampSkewMs else {
return .failure(.timestampSkew(peerID: peerID, skewMs: skew, maxSkewMs: maxTimestampSkewMs))
}
return .success(())
}
}
@@ -113,3 +113,45 @@ struct BLELinkAuthState {
return true
}
}
// MARK: - Reconnect Revalidation Policy
/// Bounds ordinary Noise revalidation to one attempt per physical-link epoch.
/// A live epoch may retry after the cooldown so a lost handshake cannot leave
/// the link permanently unauthenticated.
struct BLENoiseReconnectPolicy {
static let minimumRetryInterval: TimeInterval = 60
private var lastAttemptAt: [BLEIngressLinkID: Date] = [:]
mutating func shouldRevalidate(
on link: BLEIngressLinkID,
hasEstablishedSession: Bool,
isNoiseAuthenticatedLink: Bool,
hasAuthenticatedPeerLink: Bool,
now: Date
) -> Bool {
guard hasEstablishedSession,
!isNoiseAuthenticatedLink,
!hasAuthenticatedPeerLink else {
return false
}
if let previous = lastAttemptAt[link],
now.timeIntervalSince(previous) < Self.minimumRetryInterval {
return false
}
lastAttemptAt[link] = now
return true
}
/// Link identifiers can be stable across CoreBluetooth reconnects, so a
/// disconnect explicitly starts a new epoch and permits one fresh attempt.
mutating func endLinkEpoch(_ link: BLEIngressLinkID) {
lastAttemptAt.removeValue(forKey: link)
}
mutating func removeAll() {
lastAttemptAt.removeAll()
}
}
@@ -1,40 +0,0 @@
import Foundation
/// Bounds ordinary Noise revalidation to one attempt per physical-link epoch.
/// A live epoch may retry after the cooldown so a lost handshake cannot leave
/// the link permanently unauthenticated.
struct BLENoiseReconnectPolicy {
static let minimumRetryInterval: TimeInterval = 60
private var lastAttemptAt: [BLEIngressLinkID: Date] = [:]
mutating func shouldRevalidate(
on link: BLEIngressLinkID,
hasEstablishedSession: Bool,
isNoiseAuthenticatedLink: Bool,
hasAuthenticatedPeerLink: Bool,
now: Date
) -> Bool {
guard hasEstablishedSession,
!isNoiseAuthenticatedLink,
!hasAuthenticatedPeerLink else {
return false
}
if let previous = lastAttemptAt[link],
now.timeIntervalSince(previous) < Self.minimumRetryInterval {
return false
}
lastAttemptAt[link] = now
return true
}
/// Link identifiers can be stable across CoreBluetooth reconnects, so a
/// disconnect explicitly starts a new epoch and permits one fresh attempt.
mutating func endLinkEpoch(_ link: BLEIngressLinkID) {
lastAttemptAt.removeValue(forKey: link)
}
mutating func removeAll() {
lastAttemptAt.removeAll()
}
}
@@ -1,27 +0,0 @@
import Foundation
enum BLEPacketFreshnessPolicy {
static let defaultMaxAgeSeconds: TimeInterval = 900
static func isBroadcastRecipient(_ recipientID: Data?) -> Bool {
guard let recipientID else { return true }
return recipientID.count == 8 && recipientID.allSatisfy { $0 == 0xFF }
}
static func isStale(
timestampMilliseconds: UInt64,
now: Date,
maxAgeSeconds: TimeInterval = defaultMaxAgeSeconds
) -> Bool {
let nowMilliseconds = UInt64(now.timeIntervalSince1970 * 1000)
let maxAgeMilliseconds = UInt64(maxAgeSeconds * 1000)
guard nowMilliseconds >= maxAgeMilliseconds else { return false }
return timestampMilliseconds < nowMilliseconds - maxAgeMilliseconds
}
static func ageSeconds(timestampMilliseconds: UInt64, now: Date) -> Double {
let nowMilliseconds = UInt64(now.timeIntervalSince1970 * 1000)
guard nowMilliseconds >= timestampMilliseconds else { return 0 }
return Double(nowMilliseconds - timestampMilliseconds) / 1000.0
}
}
@@ -270,3 +270,72 @@ struct BLEPeerRegistry {
return changes
}
}
// MARK: - Lock-Backed Shared Registry Store
/// Lock-backed shared ownership of the peer registry, readable from any
/// queue or the main actor without hopping onto a transport queue.
final class BLEPeerRegistryStore: @unchecked Sendable {
private let lock = NSLock()
private var registry = BLEPeerRegistry()
func read<T>(_ body: (BLEPeerRegistry) -> T) -> T {
lock.withLock { body(registry) }
}
func mutate<T>(_ body: (inout BLEPeerRegistry) -> T) -> T {
lock.withLock { body(&registry) }
}
// MARK: - Single-question reads
var peerIDs: [PeerID] { read { $0.peerIDs } }
var connectedCount: Int { read { $0.connectedCount } }
var connectedPeerIDs: [PeerID] { read { $0.connectedPeerIDs } }
var connectedRoutingData: [Data] { read { $0.connectedRoutingData } }
var snapshotByID: [PeerID: BLEPeerInfo] { read { $0.snapshotByID } }
func info(for peerID: PeerID) -> BLEPeerInfo? {
read { $0.info(for: peerID) }
}
func isConnected(_ peerID: PeerID) -> Bool {
read { $0.isConnected(peerID) }
}
func isReachable(_ peerID: PeerID, now: Date) -> Bool {
read { $0.isReachable(peerID, now: now) }
}
func nickname(for peerID: PeerID, connectedOnly: Bool) -> String? {
read { $0.nickname(for: peerID, connectedOnly: connectedOnly) }
}
func fingerprint(for peerID: PeerID) -> String? {
read { $0.fingerprint(for: peerID) }
}
func capabilities(for peerID: PeerID) -> PeerCapabilities {
read { $0.capabilities(for: peerID) }
}
func advertisedBridgeGeohash() -> String? {
read { $0.advertisedBridgeGeohash() }
}
func displayNicknames(selfNickname: String) -> [PeerID: String] {
read { $0.displayNicknames(selfNickname: selfNickname) }
}
func transportSnapshots(selfNickname: String) -> [TransportPeerSnapshot] {
read { $0.transportSnapshots(selfNickname: selfNickname) }
}
func reachablePeers(advertising capability: PeerCapabilities, now: Date) -> [PeerID] {
read { registry in
registry.peers(advertising: capability)
.filter { registry.isReachable($0, now: now) }
}
}
}
@@ -1,83 +0,0 @@
import BitFoundation
import Foundation
/// Lock-backed shared ownership of the peer registry, readable from any
/// queue or the main actor without hopping onto a transport queue.
///
/// Mutations come only from the transport's own serial queues — the
/// engine, plus the bleQueue link-drop paths that mark a peer
/// disconnected — and the lock serializes them against each other and
/// against readers, so the main actor answers questions like
/// `isPeerConnected` without blocking behind in-flight transport work.
/// Every `BLEPeerRegistry` mutation is a single whole-transition method,
/// so a reader between two mutations always observes a valid pre- or
/// post-state, never a torn one.
///
/// Closures passed to `read`/`mutate` run under the (non-recursive) lock
/// and must not call back into the store.
final class BLEPeerRegistryStore: @unchecked Sendable {
private let lock = NSLock()
private var registry = BLEPeerRegistry()
/// One consistent view across multiple registry reads.
func read<T>(_ body: (BLEPeerRegistry) -> T) -> T {
lock.withLock { body(registry) }
}
func mutate<T>(_ body: (inout BLEPeerRegistry) -> T) -> T {
lock.withLock { body(&registry) }
}
// MARK: - Single-question reads
var peerIDs: [PeerID] { read { $0.peerIDs } }
var connectedCount: Int { read { $0.connectedCount } }
var connectedPeerIDs: [PeerID] { read { $0.connectedPeerIDs } }
var connectedRoutingData: [Data] { read { $0.connectedRoutingData } }
var snapshotByID: [PeerID: BLEPeerInfo] { read { $0.snapshotByID } }
func info(for peerID: PeerID) -> BLEPeerInfo? {
read { $0.info(for: peerID) }
}
func isConnected(_ peerID: PeerID) -> Bool {
read { $0.isConnected(peerID) }
}
func isReachable(_ peerID: PeerID, now: Date) -> Bool {
read { $0.isReachable(peerID, now: now) }
}
func nickname(for peerID: PeerID, connectedOnly: Bool) -> String? {
read { $0.nickname(for: peerID, connectedOnly: connectedOnly) }
}
func fingerprint(for peerID: PeerID) -> String? {
read { $0.fingerprint(for: peerID) }
}
func capabilities(for peerID: PeerID) -> PeerCapabilities {
read { $0.capabilities(for: peerID) }
}
func advertisedBridgeGeohash() -> String? {
read { $0.advertisedBridgeGeohash() }
}
func displayNicknames(selfNickname: String) -> [PeerID: String] {
read { $0.displayNicknames(selfNickname: selfNickname) }
}
func transportSnapshots(selfNickname: String) -> [TransportPeerSnapshot] {
read { $0.transportSnapshots(selfNickname: selfNickname) }
}
/// Peers advertising `capability` that are reachable now, in one
/// consistent view.
func reachablePeers(advertising capability: PeerCapabilities, now: Date) -> [PeerID] {
read { registry in
registry.peers(advertising: capability)
.filter { registry.isReachable($0, now: now) }
}
}
}
File diff suppressed because it is too large. Load diff
@@ -144,3 +144,50 @@ final class BLEPublicMessageHandler {
return true
}
}
// MARK: - Public Message Acceptance Policy
struct BLEPublicMessageAcceptance: Equatable {
let shouldTrackForSync: Bool
}
enum BLEPublicMessageRejection: Equatable {
case selfEcho
case staleBroadcast(ageSeconds: Double)
}
enum BLEPublicMessageDecision: Equatable {
case accept(BLEPublicMessageAcceptance)
case reject(BLEPublicMessageRejection)
}
enum BLEPublicMessagePolicy {
static func evaluate(
packet: BitchatPacket,
from peerID: PeerID,
localPeerID: PeerID,
now: Date
) -> BLEPublicMessageDecision {
if peerID == localPeerID && packet.ttl != 0 {
return .reject(.selfEcho)
}
let isBroadcast = BLEPacketFreshnessPolicy.isBroadcastRecipient(packet.recipientID)
if isBroadcast,
BLEPacketFreshnessPolicy.isStale(
timestampMilliseconds: packet.timestamp,
now: now,
maxAgeSeconds: TransportConfig.syncPublicMessageMaxAgeSeconds
) {
return .reject(.staleBroadcast(ageSeconds: BLEPacketFreshnessPolicy.ageSeconds(
timestampMilliseconds: packet.timestamp,
now: now
)))
}
return .accept(BLEPublicMessageAcceptance(
shouldTrackForSync: isBroadcast && packet.type == MessageType.message.rawValue
))
}
}
@@ -1,49 +0,0 @@
import BitFoundation
import Foundation
struct BLEPublicMessageAcceptance: Equatable {
let shouldTrackForSync: Bool
}
enum BLEPublicMessageRejection: Equatable {
case selfEcho
case staleBroadcast(ageSeconds: Double)
}
enum BLEPublicMessageDecision: Equatable {
case accept(BLEPublicMessageAcceptance)
case reject(BLEPublicMessageRejection)
}
enum BLEPublicMessagePolicy {
static func evaluate(
packet: BitchatPacket,
from peerID: PeerID,
localPeerID: PeerID,
now: Date
) -> BLEPublicMessageDecision {
if peerID == localPeerID && packet.ttl != 0 {
return .reject(.selfEcho)
}
let isBroadcast = BLEPacketFreshnessPolicy.isBroadcastRecipient(packet.recipientID)
// Acceptance window matches the gossip-sync serving window: a peer
// walking between partitions carries hours of public history, so the
// receive side must not drop what sync legitimately serves.
if isBroadcast,
BLEPacketFreshnessPolicy.isStale(
timestampMilliseconds: packet.timestamp,
now: now,
maxAgeSeconds: TransportConfig.syncPublicMessageMaxAgeSeconds
) {
return .reject(.staleBroadcast(ageSeconds: BLEPacketFreshnessPolicy.ageSeconds(
timestampMilliseconds: packet.timestamp,
now: now
)))
}
return .accept(BLEPublicMessageAcceptance(
shouldTrackForSync: isBroadcast && packet.type == MessageType.message.rawValue
))
}
}
@@ -473,3 +473,98 @@ private extension CBPeripheralState {
}
}
}
// MARK: - Scan Duty Policy
enum BLEScanDutyPlan: Equatable {
case continuous
case dutyCycle(onDuration: TimeInterval, offDuration: TimeInterval)
}
enum BLEScanDutyPolicy {
static func plan(
appIsActive: Bool,
connectedCount: Int,
hasRecentTraffic: Bool,
highDegreeThreshold: Int = TransportConfig.bleHighDegreeThreshold,
lowPowerMode: Bool = false
) -> BLEScanDutyPlan {
if lowPowerMode && appIsActive && !hasRecentTraffic {
if connectedCount >= highDegreeThreshold {
return .dutyCycle(onDuration: 2.0, offDuration: 20.0)
}
return .dutyCycle(
onDuration: TransportConfig.bleDutyOnDurationDense,
offDuration: TransportConfig.bleDutyOffDurationDense
)
}
let forceContinuousScan = connectedCount <= 2 || hasRecentTraffic
let shouldDutyCycle = appIsActive && connectedCount > 0 && !forceContinuousScan
guard shouldDutyCycle else {
return .continuous
}
if connectedCount >= highDegreeThreshold {
return .dutyCycle(
onDuration: TransportConfig.bleDutyOnDurationDense,
offDuration: TransportConfig.bleDutyOffDurationDense
)
}
return .dutyCycle(
onDuration: TransportConfig.bleDutyOnDuration,
offDuration: TransportConfig.bleDutyOffDuration
)
}
}
// MARK: - Recent Peripheral Cache
/// Remembers recently seen bitchat peripherals so pending background connects
/// can be armed when the app leaves the foreground.
final class BLERecentPeripheralCache<Peripheral> {
private struct Entry {
let peripheral: Peripheral
var lastSeen: Date
}
private var entries: [String: Entry] = [:]
private let capacity: Int
private let maxAge: TimeInterval
init(
capacity: Int = TransportConfig.bleRecentPeripheralCacheCap,
maxAge: TimeInterval = TransportConfig.bleRecentPeripheralMaxAgeSeconds
) {
self.capacity = capacity
self.maxAge = maxAge
}
var count: Int { entries.count }
func record(_ peripheral: Peripheral, peripheralID: String, at now: Date) {
entries[peripheralID] = Entry(peripheral: peripheral, lastSeen: now)
guard entries.count > capacity else { return }
if let stalest = entries.min(by: { $0.value.lastSeen < $1.value.lastSeen }) {
entries.removeValue(forKey: stalest.key)
}
}
func reconnectTargets(
now: Date,
limit: Int,
excluding: (String) -> Bool
) -> [(peripheralID: String, peripheral: Peripheral)] {
let cutoff = now.addingTimeInterval(-maxAge)
entries = entries.filter { $0.value.lastSeen >= cutoff }
guard limit > 0 else { return [] }
return entries
.filter { !excluding($0.key) }
.sorted { $0.value.lastSeen > $1.value.lastSeen }
.prefix(limit)
.map { (peripheralID: $0.key, peripheral: $0.value.peripheral) }
}
}
@@ -155,3 +155,32 @@ struct BLERecentTrafficTracker: Equatable {
lhs.packetTimestamps[lhs.head...].elementsEqual(rhs.packetTimestamps[rhs.head...])
}
}
// MARK: - Packet Freshness Policy
enum BLEPacketFreshnessPolicy {
static let defaultMaxAgeSeconds: TimeInterval = 900
static func isBroadcastRecipient(_ recipientID: Data?) -> Bool {
guard let recipientID else { return true }
return recipientID.count == 8 && recipientID.allSatisfy { $0 == 0xFF }
}
static func isStale(
timestampMilliseconds: UInt64,
now: Date,
maxAgeSeconds: TimeInterval = defaultMaxAgeSeconds
) -> Bool {
let nowMilliseconds = UInt64(now.timeIntervalSince1970 * 1000)
let maxAgeMilliseconds = UInt64(maxAgeSeconds * 1000)
guard nowMilliseconds >= maxAgeMilliseconds else { return false }
return timestampMilliseconds < nowMilliseconds - maxAgeMilliseconds
}
static func ageSeconds(timestampMilliseconds: UInt64, now: Date) -> Double {
let nowMilliseconds = UInt64(now.timeIntervalSince1970 * 1000)
guard nowMilliseconds >= timestampMilliseconds else { return 0 }
return Double(nowMilliseconds - timestampMilliseconds) / 1000.0
}
}
@@ -1,53 +0,0 @@
import Foundation
/// Remembers recently seen bitchat peripherals (fresh discoveries and dropped
/// links) so the service can arm pending background connections against them
/// when the app leaves the foreground. Generic over the peripheral type so
/// the eviction/expiry logic is testable without CoreBluetooth.
final class BLERecentPeripheralCache<Peripheral> {
private struct Entry {
let peripheral: Peripheral
var lastSeen: Date
}
private var entries: [String: Entry] = [:]
private let capacity: Int
private let maxAge: TimeInterval
init(
capacity: Int = TransportConfig.bleRecentPeripheralCacheCap,
maxAge: TimeInterval = TransportConfig.bleRecentPeripheralMaxAgeSeconds
) {
self.capacity = capacity
self.maxAge = maxAge
}
var count: Int { entries.count }
func record(_ peripheral: Peripheral, peripheralID: String, at now: Date) {
entries[peripheralID] = Entry(peripheral: peripheral, lastSeen: now)
guard entries.count > capacity else { return }
// Inserts overshoot capacity by at most one; evict the stalest entry
if let stalest = entries.min(by: { $0.value.lastSeen < $1.value.lastSeen }) {
entries.removeValue(forKey: stalest.key)
}
}
/// Most-recently-seen peripherals eligible for a pending background
/// connect, freshest first, capped at `limit`. Expired entries are
/// pruned as a side effect.
func reconnectTargets(
now: Date,
limit: Int,
excluding: (String) -> Bool
) -> [(peripheralID: String, peripheral: Peripheral)] {
let cutoff = now.addingTimeInterval(-maxAge)
entries = entries.filter { $0.value.lastSeen >= cutoff }
guard limit > 0 else { return [] }
return entries
.filter { !excluding($0.key) }
.sorted { $0.value.lastSeen > $1.value.lastSeen }
.prefix(limit)
.map { (peripheralID: $0.key, peripheral: $0.value.peripheral) }
}
}
@@ -1,101 +0,0 @@
import BitFoundation
import Foundation
struct BLERouteForwardingPlan {
let shouldSuppressFloodRelay: Bool
let forwardPacket: BitchatPacket?
let nextHop: PeerID?
static let allowFloodRelay = BLERouteForwardingPlan(
shouldSuppressFloodRelay: false,
forwardPacket: nil,
nextHop: nil
)
static let suppressFloodRelay = BLERouteForwardingPlan(
shouldSuppressFloodRelay: true,
forwardPacket: nil,
nextHop: nil
)
static func forward(_ packet: BitchatPacket, to nextHop: PeerID) -> BLERouteForwardingPlan {
BLERouteForwardingPlan(
shouldSuppressFloodRelay: true,
forwardPacket: packet,
nextHop: nextHop
)
}
}
struct BLERouteForwardingPolicy {
static func plan(
for packet: BitchatPacket,
localPeerID: PeerID,
localRoutingData: Data?,
routingPeer: (Data) -> PeerID?,
isPeerConnected: (PeerID) -> Bool
) -> BLERouteForwardingPlan {
// REQUEST_SYNC is link-local: never forward it, on the flood path or
// the source-routed path. A crafted request with a route and TTL
// headroom must not be able to fan a full-store replay out to the next
// hop. Suppressing here also short-circuits the flood relay.
if packet.type == MessageType.requestSync.rawValue {
return .suppressFloodRelay
}
if PeerID(hexData: packet.recipientID) == localPeerID {
return .suppressFloodRelay
}
guard let route = packet.route, !route.isEmpty else {
return .allowFloodRelay
}
guard packet.ttl > 1 else {
return .suppressFloodRelay
}
guard let localRoutingData else {
return .allowFloodRelay
}
guard let localIndex = route.firstIndex(of: localRoutingData) else {
return forward(packet, toRouteData: route[0], routingPeer: routingPeer, isPeerConnected: isPeerConnected)
}
if localIndex == route.count - 1 {
guard let destinationPeer = PeerID(hexData: packet.recipientID),
isPeerConnected(destinationPeer) else {
return .allowFloodRelay
}
return .forward(relayed(packet), to: destinationPeer)
}
return forward(
packet,
toRouteData: route[localIndex + 1],
routingPeer: routingPeer,
isPeerConnected: isPeerConnected
)
}
private static func forward(
_ packet: BitchatPacket,
toRouteData routeData: Data,
routingPeer: (Data) -> PeerID?,
isPeerConnected: (PeerID) -> Bool
) -> BLERouteForwardingPlan {
guard let nextPeer = routingPeer(routeData),
isPeerConnected(nextPeer) else {
return .allowFloodRelay
}
return .forward(relayed(packet), to: nextPeer)
}
private static func relayed(_ packet: BitchatPacket) -> BitchatPacket {
var relayPacket = packet
relayPacket.ttl = packet.ttl - 1
return relayPacket
}
}
@@ -1,50 +0,0 @@
import Foundation
enum BLEScanDutyPlan: Equatable {
case continuous
case dutyCycle(onDuration: TimeInterval, offDuration: TimeInterval)
}
enum BLEScanDutyPolicy {
static func plan(
appIsActive: Bool,
connectedCount: Int,
hasRecentTraffic: Bool,
highDegreeThreshold: Int = TransportConfig.bleHighDegreeThreshold,
lowPowerMode: Bool = false
) -> BLEScanDutyPlan {
// Under Low Power Mode, duty-cycle aggressively even with 0-2 peers
// whenever there is no active traffic burst so the BLE radio sleeps ~85-90% of the time.
if lowPowerMode && appIsActive && !hasRecentTraffic {
if connectedCount >= highDegreeThreshold {
return .dutyCycle(
onDuration: 2.0,
offDuration: 20.0
)
}
return .dutyCycle(
onDuration: TransportConfig.bleDutyOnDurationDense,
offDuration: TransportConfig.bleDutyOffDurationDense
)
}
let forceContinuousScan = connectedCount <= 2 || hasRecentTraffic
let shouldDutyCycle = appIsActive && connectedCount > 0 && !forceContinuousScan
guard shouldDutyCycle else {
return .continuous
}
if connectedCount >= highDegreeThreshold {
return .dutyCycle(
onDuration: TransportConfig.bleDutyOnDurationDense,
offDuration: TransportConfig.bleDutyOffDurationDense
)
}
return .dutyCycle(
onDuration: TransportConfig.bleDutyOnDuration,
offDuration: TransportConfig.bleDutyOffDuration
)
}
}
@@ -0,0 +1,571 @@
import BitFoundation
import BitLogger
import Foundation
// MARK: - Courier Store-and-Forward, Prekey Bundles & Gateway Carrier
extension BLEService {
// MARK: Courier Store-and-Forward
/// Seal `content` for the recipient and hand the envelope to the given
/// couriers for physical delivery. When a verified one-time prekey bundle
/// is cached for the recipient, sealing targets one of its prekeys
/// (forward secret, envelope v2); otherwise it falls back to their static
/// key (one-way Noise X, v1) exactly as before. Returns false when no
/// courier is connected, the payload cannot be built, or sealing fails;
/// link writes are queued asynchronously after the envelope is ready.
private func sealCourierEnvelope(
_ content: String,
messageID: String,
recipientNoiseKey: Data,
copies: UInt8
) -> CourierEnvelope? {
guard let typedPayload = BLENoisePayloadFactory.privateMessage(content: content, messageID: messageID) else {
return nil
}
do {
let now = Date()
let sealed: Data
let prekeyID: UInt32?
if let prekey = assignRecipientPrekey(messageID: messageID, recipientNoiseKey: recipientNoiseKey) {
sealed = try noiseService.sealPrekeyPayload(typedPayload, recipientPrekey: prekey)
prekeyID = prekey.id
} else {
sealed = try noiseService.sealCourierPayload(typedPayload, recipientStaticKey: recipientNoiseKey)
prekeyID = nil
}
return CourierEnvelope(
recipientTag: CourierEnvelope.recipientTag(
noiseStaticKey: recipientNoiseKey,
epochDay: CourierEnvelope.epochDay(for: now)
),
expiry: UInt64((now.timeIntervalSince1970 + CourierEnvelope.maxLifetimeSeconds) * 1000),
ciphertext: sealed,
copies: copies,
prekeyID: prekeyID
)
} catch {
SecureLogger.error("Failed to seal courier envelope: \(error)", category: .encryption)
return nil
}
}
func sendCourierMessage(_ content: String, messageID: String, recipientNoiseKey: Data, via couriers: [PeerID]) -> Bool {
let connected = couriers.filter { isPeerConnected($0) }
guard !connected.isEmpty,
let envelope = sealCourierEnvelope(
content,
messageID: messageID,
recipientNoiseKey: recipientNoiseKey,
copies: TransportConfig.courierInitialCopies
),
let payload = envelope.encode() else {
return false
}
messageQueue.async { [weak self] in
guard let self else { return }
for courier in connected {
SecureLogger.debug("📦 Depositing courier envelope with \(courier.id.prefix(8))… id=\(messageID.prefix(8))…", category: .session)
self.sendPacketDirected(self.makeCourierPacket(payload, to: courier), to: courier)
}
}
return true
}
// MARK: Courier over the bridge
/// Seals `content` into a courier envelope for relay parking (a bridge
/// courier drop). Same sealing rules as `sendCourierMessage` — prekey
/// (v2) when a verified bundle is cached, static Noise X (v1) otherwise —
/// but carry-only: a relay copy never sprays.
func sealBridgeCourierEnvelope(_ content: String, messageID: String, recipientNoiseKey: Data) -> CourierEnvelope? {
sealCourierEnvelope(content, messageID: messageID, recipientNoiseKey: recipientNoiseKey, copies: 1)
}
/// Opens a courier envelope that arrived as a bridge drop (relay fetch,
/// not a directed mesh packet). Returns false when the rotating tag does
/// not match our static key — a drop for someone else, or a stale tag.
/// The inner Noise X seal authenticates the sender; there is no packet
/// signature to check on this path.
@discardableResult
func openBridgedCourierEnvelope(_ envelope: CourierEnvelope) -> Bool {
guard !envelope.isExpired else { return false }
let myKey = noiseService.getStaticPublicKeyData()
guard CourierEnvelope.candidateTags(noiseStaticKey: myKey, around: Date()).contains(envelope.recipientTag) else {
return false
}
return openCourierEnvelope(envelope)
}
/// Hands a bridge-fetched envelope directly to the matching local peer
/// as a directed courier packet. Delivery-only by design: the recipient's
/// tag matched, so this never lands in a stranger's carry quota.
/// Returns true only if a current Noise-authenticated physical link
/// accepted the packet; a stale peer-level session, reachability record,
/// replay-rebound link, or process-local spool is not delivery.
@discardableResult
func deliverBridgedEnvelope(_ envelope: CourierEnvelope, to peerID: PeerID) -> Bool {
guard let payload = envelope.encode() else { return false }
let packet = makeCourierPacket(payload, to: peerID)
return onEngine {
// Engine slot: the auth-link check and the directed send see one
// consistent view of the identity domain.
guard hasCurrentNoiseAuthenticatedLink(to: peerID) else { return false }
return sendPacketDirected(
packet,
to: peerID,
requireDirectPeerLink: true,
requireNoiseAuthenticatedPeerLink: true
)
}
}
/// Verified reachable peers with known Noise keys — the set a bridge
/// gateway watches courier drops for.
func verifiedPeersWithNoiseKeys() -> [(peerID: PeerID, noiseKey: Data)] {
let now = Date()
return onEngine {
peerRegistry.snapshotByID.values.compactMap { info in
guard info.isVerifiedNickname,
let key = info.noisePublicKey,
peerRegistry.isReachable(info.peerID, now: now) else { return nil }
return (info.peerID, key)
}
}
}
/// The prekey to seal a courier message with, or nil to fall back to
/// static sealing. The real signal is a verified, unexpired bundle with a
/// spare prekey; the advertised `.prekeys` capability only acts as a veto
/// for peers we currently see on the mesh (a cached bundle can outlive a
/// peer's downgrade to a build that no longer holds the privates).
/// Re-deposits of the same message reuse its assigned prekey, so one
/// message consumes exactly one prekey ID regardless of courier count.
private func assignRecipientPrekey(messageID: String, recipientNoiseKey: Data) -> PrekeyBundle.Prekey? {
let shortID = PeerID(publicKey: recipientNoiseKey)
let knownOnMesh = peerRegistry.info(for: shortID) != nil
if knownOnMesh, !peerCapabilities(shortID).contains(.prekeys) {
return nil
}
return prekeyBundleStore.assignPrekey(messageID: messageID, recipientNoiseKey: recipientNoiseKey)
}
private func makeCourierPacket(_ payload: Data, to peerID: PeerID) -> BitchatPacket {
let packet = BitchatPacket(
type: MessageType.courierEnvelope.rawValue,
senderID: myPeerIDData,
recipientID: Data(hexString: peerID.id),
timestamp: UInt64(Date().timeIntervalSince1970 * 1000),
payload: payload,
signature: nil,
ttl: messageTTL
)
// Signed so a courier can authenticate the depositor before carrying
// mail under their quota. Handover to the recipient doesn't need the
// packet signature — the inner Noise X seal authenticates the sender.
return noiseService.signPacket(packet) ?? packet
}
/// Handles both courier roles for an incoming envelope addressed to us:
/// recipient (the rotating tag matches our static key → open and deliver)
/// or courier (a trusted peer is depositing mail for someone else → store).
func handleCourierEnvelope(_ packet: BitchatPacket, from peerID: PeerID) {
// Directed packets only; envelopes addressed elsewhere ride the
// generic relay path untouched.
guard packet.recipientID == myPeerIDData else { return }
guard let envelope = CourierEnvelope.decode(packet.payload), !envelope.isExpired else { return }
let myKey = noiseService.getStaticPublicKeyData()
if CourierEnvelope.candidateTags(noiseStaticKey: myKey, around: Date()).contains(envelope.recipientTag) {
openCourierEnvelope(envelope)
} else {
acceptCourierDeposit(envelope, from: peerID, packet: packet)
}
}
@discardableResult
private func openCourierEnvelope(_ envelope: CourierEnvelope) -> Bool {
do {
let typedPayload: Data
let senderStaticKey: Data
if let prekeyID = envelope.prekeyID {
// Envelope v2: sealed to one of our one-time prekeys. Opening
// consumes the prekey (48h redelivery grace), which shrinks our
// published bundle under a strictly newer generatedAt. Re-gossip
// so peers replace their cached copy and stop assigning the
// consumed ID before the grace lapses; force the broadcast when
// the batch also topped back up (low-water), otherwise let the
// rebroadcast throttle coalesce bursts.
let opened = try noiseService.openPrekeyPayload(envelope.ciphertext, prekeyID: prekeyID)
(typedPayload, senderStaticKey) = (opened.payload, opened.senderStaticKey)
if opened.consumedPrekey {
let replenished = noiseService.replenishPrekeysIfNeeded()
sendPrekeyBundle(force: replenished)
}
} else {
(typedPayload, senderStaticKey) = try noiseService.openCourierPayload(envelope.ciphertext)
}
guard let typeRaw = typedPayload.first,
let payloadType = NoisePayloadType(rawValue: typeRaw),
payloadType == .privateMessage else {
SecureLogger.warning("⚠️ Courier envelope carried unsupported payload type", category: .session)
return true // decrypted but deterministically unsupported
}
let payload = Data(typedPayload.dropFirst())
guard let innerMessageID = PrivateMessagePacket.decode(from: payload)?.messageID else {
SecureLogger.warning("⚠️ Courier envelope carried undecodable private message", category: .session)
return true // decrypted but deterministically malformed
}
// Redundant copies of one message arrive as distinct envelopes
// (fresh seal each: mesh couriers, bridge drops across relays),
// so dedup here on the inner message ID — before delivery, ack,
// and handshake work. A duplicate costs only the decrypt above
// and at most one ack ever goes out per message ID.
let firstOpen = onEngine {
openedCourierMessageIDs.insert(innerMessageID)
}
guard firstOpen else {
SecureLogger.debug("📦 Dropping duplicate courier envelope for message \(innerMessageID.prefix(8))…", category: .session)
return true
}
// Couriered mail arrives while the sender is absent, so the UI's
// block check can't resolve their fingerprint from a live session.
// Gate here, where the full static key is in hand.
guard !identityManager.isBlocked(fingerprint: senderStaticKey.sha256Fingerprint()) else {
SecureLogger.debug("🚫 Dropping courier envelope from blocked sender", category: .security)
return true
}
// A present sender resolves to their live mesh thread via the
// derived short ID. An absent sender — the usual courier case —
// uses the full noise-key ID so the message lands on the stable
// favorite conversation instead of an unresolvable short-ID
// thread labeled "Unknown".
let shortID = PeerID(publicKey: senderStaticKey)
let isKnownOnMesh = peerRegistry.info(for: shortID) != nil
let senderPeerID = isKnownOnMesh ? shortID : PeerID(hexData: senderStaticKey)
SecureLogger.debug("📦 Opened courier envelope from \(senderPeerID.id.prefix(8))…", category: .session)
notifyUI { [weak self] in
self?.deliverTransportEvent(.noisePayloadReceived(
peerID: senderPeerID,
type: payloadType,
payload: payload,
timestamp: Date()
))
}
return true
} catch {
// Tag collision or stale key: not addressed to us after all.
SecureLogger.debug("📦 Courier envelope failed to open: \(error)", category: .encryption)
return false
}
}
private func acceptCourierDeposit(_ envelope: CourierEnvelope, from peerID: PeerID, packet: BitchatPacket) {
// A deposit must come from its depositor over the direct link: the
// claimed sender has to be the ingress peer, and the packet signature
// has to verify against that peer's announced signing key. Otherwise
// an untrusted sender could route an envelope through any trusted
// neighbor and have us carry it under the neighbor's quota.
guard PeerID(hexData: packet.senderID) == peerID else {
SecureLogger.debug("📦 Courier deposit rejected: relayed envelope claims sender \(PeerID(hexData: packet.senderID).id.prefix(8))… but arrived from \(peerID.id.prefix(8))…", category: .security)
return
}
let depositorInfo = peerRegistry.info(for: peerID)
guard let depositorKey = depositorInfo?.noisePublicKey else {
SecureLogger.debug("📦 Courier deposit from unknown peer \(peerID.id.prefix(8))… rejected", category: .session)
return
}
guard let signingKey = depositorInfo?.signingPublicKey,
noiseService.verifyPacketSignature(packet, publicKey: signingKey) else {
SecureLogger.debug("📦 Courier deposit from \(peerID.id.prefix(8))… rejected (missing/invalid signature)", category: .security)
return
}
let isVerifiedPeer = depositorInfo?.isVerifiedNickname ?? false
let store = courierStore
let policy = courierDepositPolicy
notifyUI { [weak self] in
guard let self else { return }
guard let tier = policy(depositorKey, isVerifiedPeer) else {
SecureLogger.debug("📦 Courier deposit from \(peerID.id.prefix(8))… rejected (neither favorite nor verified)", category: .session)
return
}
self.messageQueue.async {
if store.deposit(envelope, from: depositorKey, tier: tier) {
SecureLogger.debug("📦 Carrying courier envelope deposited by \(peerID.id.prefix(8))… (\(tier.rawValue))", category: .session)
}
}
}
}
/// Hand over any carried envelopes addressed to a peer we just heard from.
func deliverCourierMail(to peerID: PeerID, noiseKey: Data) {
let accepted = courierStore.handoverEnvelopes(for: noiseKey) { [weak self] envelope in
guard let self,
let payload = envelope.encode(),
self.sendPacketDirected(
self.makeCourierPacket(payload, to: peerID),
to: peerID,
requireDirectPeerLink: true,
requireNoiseAuthenticatedPeerLink: true
) else {
return false
}
return true
}
if accepted > 0 {
SecureLogger.debug("📦 Handed over \(accepted) courier envelope(s) to \(peerID.id.prefix(8))…", category: .session)
}
}
/// Speculative handover toward a recipient heard only via a relayed
/// announce: the envelope floods the mesh as a directed packet (relays
/// treat it like a directed DM). Non-destructive — the carried copy stays
/// until a direct handover or expiry, throttled per envelope so repeated
/// announces don't re-flood.
func deliverCourierMailRemotely(to peerID: PeerID, noiseKey: Data) {
let envelopes = courierStore.envelopesForRemoteHandover(
recipientNoiseKey: noiseKey,
cooldown: TransportConfig.courierRemoteHandoverCooldownSeconds
)
guard !envelopes.isEmpty else { return }
SecureLogger.debug("📦 Remote handover: flooding \(envelopes.count) envelope(s) toward \(peerID.id.prefix(8))…", category: .session)
for envelope in envelopes {
guard let payload = envelope.encode() else { continue }
broadcastPacket(makeCourierPacket(payload, to: peerID))
}
}
/// Spray-and-wait: split copy budgets with another courier we just
/// encountered, so carried mail diffuses through a moving crowd instead
/// of riding a single carrier. Only favorites and verified peers qualify,
/// mirroring the deposit policy they would apply to us.
func sprayCourierMail(to peerID: PeerID, noiseKey: Data, isVerifiedPeer: Bool) {
let store = courierStore
let sendSpray: () -> Void = { [weak self] in
guard let self else { return }
let accepted = store.transferSprayCopies(to: noiseKey) { envelope in
guard let payload = envelope.encode(),
self.sendPacketDirected(
self.makeCourierPacket(payload, to: peerID),
to: peerID,
requireDirectPeerLink: true,
requireNoiseAuthenticatedPeerLink: true
) else {
return false
}
return true
}
if accepted > 0 {
SecureLogger.debug("📦 Sprayed \(accepted) envelope copy(ies) to courier \(peerID.id.prefix(8))…", category: .session)
}
}
let policy = courierDepositPolicy
notifyUI { [weak self] in
guard let self else { return }
// Same trust gate as deposits: don't hand mail to a peer who
// would reject it from us.
guard policy(noiseKey, isVerifiedPeer) != nil else { return }
self.messageQueue.async {
sendSpray()
}
}
}
// MARK: One-Time Prekey Bundles
/// Broadcasts our signed prekey bundle and tracks it for gossip sync.
/// Unforced sends (piggybacked on announces) are throttled — gossip does
/// the spreading, the broadcast just keeps our own gossip entry fresh.
/// Forced sends (bundle changed after consumption) go immediately.
func sendPrekeyBundle(force: Bool = false) {
let now = Date()
let shouldSend: Bool = onEngine {
if !force,
let last = lastPrekeyBundleSentAt,
now.timeIntervalSince(last) < TransportConfig.prekeyBundleRebroadcastSeconds {
return false
}
lastPrekeyBundleSentAt = now
return true
}
guard shouldSend else { return }
guard let bundle = noiseService.currentPrekeyBundle(),
let payload = bundle.encode() else {
SecureLogger.error("❌ Failed to build prekey bundle", category: .security)
return
}
guard let signedPacket = buildSignedBroadcastPacket(
type: .prekeyBundle,
payload: payload,
timestamp: now,
logLabel: "prekey bundle packet"
) else { return }
if DispatchQueue.getSpecific(key: messageQueueKey) != nil {
broadcastPacket(signedPacket)
} else {
messageQueue.async { [weak self] in
self?.broadcastPacket(signedPacket)
}
}
gossipSyncManager?.onPublicPacketSeen(signedPacket)
}
/// Ingests a gossiped prekey bundle. Attribution is layered: the outer
/// packet must originate from the bundle owner (fabricated sender IDs, used
/// to multiply cache/gossip entries, are rejected), and BOTH the inner
/// bundle signature and the outer packet signature must verify against the
/// owner's announce-bound signing key. Verifying the outer packet — whose
/// signed bytes cover senderID and timestamp — stops a valid bundle from
/// being replayed under a fresh timestamp or spoofed sender to pass
/// freshness or poison attribution. Only after that does the packet enter
/// our own gossip store, so we never help spread a bundle we couldn't
/// attribute.
@discardableResult
func handlePrekeyBundle(_ packet: BitchatPacket, from peerID: PeerID) -> Bool {
guard let bundle = PrekeyBundle.decode(packet.payload) else {
SecureLogger.debug("🔑 Ignoring malformed prekey bundle from \(peerID.id.prefix(8))…", category: .security)
return false
}
// Our own bundle is tracked at send time; a copy echoing back adds nothing.
guard bundle.noiseStaticPublicKey != noiseService.getStaticPublicKeyData() else { return false }
let owner = PeerID(publicKey: bundle.noiseStaticPublicKey)
// The owner's genuine bundle (direct or relayed) always carries the
// owner's senderID + outer signature; gossip resends preserve both. A
// packet whose senderID isn't the owner can't be authenticated here.
guard PeerID(hexData: packet.senderID) == owner else {
SecureLogger.debug("🔑 Ignoring prekey bundle whose sender ≠ owner \(owner.id.prefix(8))…", category: .security)
return false
}
guard let signingKey = announceBoundSigningKey(forNoiseKey: bundle.noiseStaticPublicKey, owner: owner) else {
// No binding yet: retain the latest bundle per owner, bounded, and
// retry once the verified announce lands (engine-confined on messageQueue).
if pendingPrekeyBundles[owner] != nil
|| pendingPrekeyBundles.count < Self.pendingPrekeyBundleCap {
pendingPrekeyBundles[owner] = packet
}
SecureLogger.debug("🔑 Deferring prekey bundle without a bound signing key (owner \(owner.id.prefix(8))…)", category: .security)
return false
}
return ingestVerifiedPrekeyBundle(bundle, packet: packet, owner: owner, signingKey: signingKey)
}
/// Verify a bundle's inner + outer signatures against the owner's bound
/// signing key and, on success, cache it and let it enter our gossip store.
@discardableResult
private func ingestVerifiedPrekeyBundle(_ bundle: PrekeyBundle, packet: BitchatPacket, owner: PeerID, signingKey: Data) -> Bool {
guard noiseService.verifyPrekeyBundleSignature(bundle, signingPublicKey: signingKey),
noiseService.verifyPacketSignature(packet, publicKey: signingKey) else {
SecureLogger.debug("🔑 Ignoring prekey bundle without verifiable signature (owner \(owner.id.prefix(8))…)", category: .security)
return false
}
if prekeyBundleStore.ingest(bundle) {
SecureLogger.debug("🔑 Cached prekey bundle for \(owner.id.prefix(8))… (\(bundle.prekeys.count) prekeys)", category: .security)
}
gossipSyncManager?.onPublicPacketSeen(packet)
return true
}
/// Re-attempt any prekey bundle that arrived before this owner's announce
/// bound a signing key. Called from handleAnnounce on messageQueue.
func drainPendingPrekeyBundles(for owner: PeerID) {
guard let packet = pendingPrekeyBundles.removeValue(forKey: owner),
let bundle = PrekeyBundle.decode(packet.payload),
let signingKey = announceBoundSigningKey(forNoiseKey: bundle.noiseStaticPublicKey, owner: owner) else { return }
ingestVerifiedPrekeyBundle(bundle, packet: packet, owner: owner, signingKey: signingKey)
}
/// Ed25519 signing key bound to a Noise static key by a verified
/// announce: from the live registry when the owner is on the mesh, else
/// from identities persisted for offline verification.
private func announceBoundSigningKey(forNoiseKey noiseKey: Data, owner: PeerID? = nil) -> Data? {
let shortID = owner ?? PeerID(publicKey: noiseKey)
if let info = peerRegistry.info(for: shortID),
info.noisePublicKey == noiseKey,
let signingKey = info.signingPublicKey {
return signingKey
}
for candidate in identityManager.getCryptoIdentitiesByPeerIDPrefix(shortID)
where candidate.publicKey == noiseKey {
if let signingKey = candidate.signingPublicKey {
return signingKey
}
}
return nil
}
// MARK: Gateway carrier (nostrCarrier)
/// Sign and send an encoded `toGateway` carrier payload directed at a
/// gateway peer. The packet is signed so the gateway can key its uplink
/// quotas to an authenticated depositor; the carried Nostr event has its
/// own Schnorr signature for content authenticity. Returns false when
/// the gateway is not reachable or signing fails.
func sendNostrCarrier(_ payload: Data, to gatewayPeer: PeerID) -> Bool {
guard isPeerReachable(gatewayPeer) else { return false }
let packet = BitchatPacket(
type: MessageType.nostrCarrier.rawValue,
senderID: myPeerIDData,
recipientID: Data(hexString: gatewayPeer.id),
timestamp: UInt64(Date().timeIntervalSince1970 * 1000),
payload: payload,
signature: nil,
ttl: messageTTL
)
guard let signed = noiseService.signPacket(packet) else { return false }
messageQueue.async { [weak self] in
// broadcastPacket applies a known route when one exists and
// otherwise floods the directed packet like a DM, so a gateway
// that is reachable but multi-hop still gets the deposit.
self?.broadcastPacket(signed)
}
return true
}
/// Broadcast an encoded `fromGateway` carrier payload on the mesh with
/// the default TTL. Unsigned at the packet layer — receivers verify the
/// carried event's own Schnorr signature.
func broadcastNostrCarrier(_ payload: Data) {
let packet = BitchatPacket(
type: MessageType.nostrCarrier.rawValue,
senderID: myPeerIDData,
recipientID: nil,
timestamp: UInt64(Date().timeIntervalSince1970 * 1000),
payload: payload,
signature: nil,
ttl: messageTTL
)
messageQueue.async { [weak self] in
self?.broadcastPacket(packet)
}
}
/// Transport-level handling for a received nostrCarrier packet; policy
/// (verification of the carried event, quotas, loop prevention) lives in
/// `GatewayService` behind `onNostrCarrierPacket`.
func handleNostrCarrier(_ packet: BitchatPacket, from _: PeerID) {
let senderID = PeerID(hexData: packet.senderID)
let directedToUs: Bool
if let recipientID = packet.recipientID {
// Carriers addressed elsewhere ride the generic relay path untouched.
guard recipientID == myPeerIDData else { return }
// Uplink deposit: quotas are keyed by the depositor, so the
// packet signature must verify against the sender's announced
// signing key. Unlike courier deposits the depositor may be
// multi-hop away, so ingress-link identity is not required.
let signingKey = peerRegistry.info(for: senderID)?.signingPublicKey
guard let signingKey,
noiseService.verifyPacketSignature(packet, publicKey: signingKey) else {
SecureLogger.debug("🌐 nostrCarrier uplink from \(senderID.id.prefix(8))… rejected (missing/invalid packet signature)", category: .security)
return
}
directedToUs = true
} else {
directedToUs = false
}
let payload = packet.payload
notifyUI { [weak self] in
self?.onNostrCarrierPacket?(payload, senderID, directedToUs)
}
}
}
@@ -0,0 +1,195 @@
import BitFoundation
import BitLogger
import Foundation
// MARK: - Mesh Diagnostics (/ping, /trace, topology map)
extension BLEService {
/// Sends a directed unencrypted ping probe (8-byte nonce + origin TTL).
/// The completion fires exactly once on the main actor: with RTT/hops
/// when the matching pong returns, or nil after the timeout window.
func sendMeshPing(to peerID: PeerID, completion: @escaping @MainActor (MeshPingResult?) -> Void) {
guard let generation = capturePanicLifecycleGeneration() else {
return
}
messageQueue.async { [weak self] in
guard let self,
self.isCurrentPanicLifecycleGeneration(generation),
let recipientData = peerID.toShort().routingData,
let payload = MeshPingPayload(
nonce: Data((0..<MeshPingPayload.nonceLength).map { _ in UInt8.random(in: .min ... .max) }),
originTTL: self.messageTTL
) else {
self?.notifyUI { [weak self] in
guard let self,
self.isCurrentPanicLifecycleGeneration(generation) else {
return
}
completion(nil)
}
return
}
let nonce = payload.nonce
let packet = BitchatPacket(
type: MessageType.ping.rawValue,
senderID: self.myPeerIDData,
recipientID: recipientData,
timestamp: UInt64(Date().timeIntervalSince1970 * 1000),
payload: payload.encode(),
signature: nil,
ttl: self.messageTTL
)
let timeout = DispatchWorkItem { [weak self] in
guard let self else { return }
let expired = onEngine {
self.meshPings.expire(nonce: nonce)
}
guard let expired else { return }
self.notifyUI { [weak self] in
guard let self,
self.isCurrentPanicLifecycleGeneration(
expired.lifecycleGeneration
) else {
return
}
expired.completion(nil)
}
}
onEngine {
self.meshPings.register(
BLEMeshPingProbe(
peerID: PeerID(hexData: recipientData),
sentAt: Date(),
lifecycleGeneration: generation,
completion: completion,
timeout: timeout
),
nonce: nonce
)
}
self.engineScheduler.schedule(
after: TransportConfig.meshPingTimeoutSeconds,
execute: timeout
)
self.broadcastPacket(packet)
}
}
/// Answers a ping addressed to us with a pong echoing its nonce; pings
/// addressed elsewhere are left to the generic directed-relay path.
///
/// `linkPeerID` is the directly connected peer that delivered the packet
/// (the ingress link), NOT the packet's claimed sender: pings are
/// unsigned, so `packet.senderID` is attacker-controlled, and keying the
/// response budget on it would let one connected peer rotate forged
/// sender IDs to emit unbounded pongs. The budget is per physical link;
/// the pong still goes to the claimed sender (that's the protocol).
func handleMeshPing(_ packet: BitchatPacket, fromLink linkPeerID: PeerID) {
guard packet.recipientID == myPeerIDData else { return }
guard let ping = MeshPingPayload.decode(packet.payload) else {
SecureLogger.debug("⚠️ Malformed ping via \(linkPeerID.id.prefix(8))…", category: .session)
return
}
let allowed = onEngine {
meshPings.shouldRespond(toLink: linkPeerID, now: Date())
}
guard allowed else {
if logRateLimiter.shouldLog(key: "ping-limit:\(linkPeerID.id)") {
SecureLogger.warning("🚫 Rate-limiting pings via link \(linkPeerID.id.prefix(8))…", category: .security)
}
return
}
guard let pong = MeshPingPayload(nonce: ping.nonce, originTTL: messageTTL) else { return }
let reply = BitchatPacket(
type: MessageType.pong.rawValue,
senderID: myPeerIDData,
recipientID: packet.senderID,
timestamp: UInt64(Date().timeIntervalSince1970 * 1000),
payload: pong.encode(),
signature: nil,
ttl: messageTTL
)
broadcastPacket(reply)
}
/// Resolves a pong against its outstanding probe. The unguessable echoed
/// nonce plus the sender check bind the reply to the probed peer; hops
/// come from the pong's TTL decrements on the return path.
func handleMeshPong(_ packet: BitchatPacket, from peerID: PeerID) {
guard packet.recipientID == myPeerIDData else { return }
guard let pong = MeshPingPayload.decode(packet.payload) else { return }
let pending = onEngine {
meshPings.resolve(nonce: pong.nonce, from: peerID)
}
guard let pending else { return }
pending.timeout.cancel()
let rttMs = Int((Date().timeIntervalSince(pending.sentAt) * 1000).rounded())
let result = MeshPingResult(
rttMs: max(0, rttMs),
hops: MeshPingPayload.hopCount(originTTL: pong.originTTL, receivedTTL: packet.ttl)
)
notifyUI { [weak self] in
guard let self,
self.isCurrentPanicLifecycleGeneration(
pending.lifecycleGeneration
) else {
return
}
pending.completion(result)
}
}
/// Estimated intermediate hops toward `peerID`, BFS over gossiped
/// bidirectionally-confirmed neighbor claims ([] = direct, nil = none).
func computeMeshPath(to peerID: PeerID) -> [PeerID]? {
refreshLocalTopology()
if let route = computeRoute(to: peerID) {
return route.compactMap { PeerID(routingData: $0) }
}
// Confirmed claims can lag a brand-new link (the peer's next announce
// hasn't arrived yet); a live direct connection is still a known path.
return isPeerConnected(peerID) ? [] : nil
}
/// Mesh graph for the topology map. Edges are advisory: announces cap
/// neighbor lists at 10, so an edge claimed by either endpoint counts.
func currentMeshTopology() -> MeshTopologySnapshot? {
refreshLocalTopology()
let claims = meshTopology.adjacencySnapshot()
var nodes = Set<PeerID>()
var edges = Set<MeshTopologyEdge>()
for (source, neighbors) in claims {
guard let sourcePeer = PeerID(routingData: source) else { continue }
nodes.insert(sourcePeer)
for neighborData in neighbors {
guard let neighborPeer = PeerID(routingData: neighborData),
neighborPeer != sourcePeer else { continue }
nodes.insert(neighborPeer)
edges.insert(MeshTopologyEdge(sourcePeer, neighborPeer))
}
}
nodes.insert(myPeerID)
return MeshTopologySnapshot(
localPeerID: myPeerID,
nodes: nodes.sorted(),
edges: edges.sorted { ($0.a, $0.b) < ($1.a, $1.b) }
)
}
func forwardAlongRouteIfNeeded(_ packet: BitchatPacket) -> Bool {
let myRoutingData = routingData(for: myPeerID) ?? (myPeerIDData.isEmpty ? nil : myPeerIDData)
let plan = BLERouteForwardingPolicy.plan(
for: packet,
localPeerID: myPeerID,
localRoutingData: myRoutingData,
routingPeer: routingPeer(from:),
isPeerConnected: isPeerConnected(_:)
)
if let forwardPacket = plan.forwardPacket, let nextHop = plan.nextHop {
sendPacketDirected(forwardPacket, to: nextHop)
}
return plan.shouldSuppressFloodRelay
}
}
@@ -0,0 +1,500 @@
import BitFoundation
import BitLogger
import Foundation
// MARK: - Link Auth & Noise Session Coordination
extension BLEService {
func links(to peerID: PeerID?) -> Set<BLEIngressLinkID> {
linkBindings.links(to: peerID)
}
/// Marks the exact physical ingress link that completed a fresh Noise
/// handshake. An old session keyed only by peer ID is insufficient: a
/// replayed announce can rebind an attacker's link to that ID.
/// Engine-confined.
func markNoiseAuthenticatedIngressLink(for packet: BitchatPacket, peerID: PeerID) {
guard let link = ingressLinks.link(for: packet) else { return }
guard linkBindings.boundPeer(for: link) == peerID else { return }
linkAuth.markAuthenticated(link, owner: peerID)
}
func isNoiseAuthenticatedIngressLink(for packet: BitchatPacket, peerID: PeerID) -> Bool {
guard let link = ingressLinks.link(for: packet) else { return false }
return linkAuth.isAuthenticated(link, for: peerID) && linkBindings.boundPeer(for: link) == peerID
}
func hasCurrentNoiseAuthenticatedLink(to peerID: PeerID) -> Bool {
!currentNoiseAuthenticatedLinks(to: peerID).isEmpty
}
func currentNoiseAuthenticatedLinks(to peerID: PeerID) -> Set<BLEIngressLinkID> {
Set(linkAuth.links(ownedBy: peerID).filter { link in
linkBindings.boundPeer(for: link) == peerID
})
}
/// A peer-level session can outlive the physical link that established it.
/// Revalidate a fresh direct link with an ordinary XX exchange, retiring
/// cached sending keys atomically before message 1 can leave.
///
/// Takes the already-resolved ingress link. Engine-confined: it runs
/// inside the rebind's engine slot, so no observer can see the new
/// binding while a cached peer-level sender is still considered
/// established.
func refreshNoiseSessionForVerifiedDirectLink(
link: BLEIngressLinkID,
peerID: PeerID
) {
let hasEstablishedSession = noiseService.hasEstablishedSession(with: peerID)
let authenticatedPeerLinks = currentNoiseAuthenticatedLinks(to: peerID)
let shouldRevalidate: Bool
if linkBindings.boundPeer(for: link) == peerID {
shouldRevalidate = linkAuth.shouldRevalidate(
on: link,
for: peerID,
hasEstablishedSession: hasEstablishedSession,
hasAuthenticatedPeerLink: !authenticatedPeerLinks.isEmpty,
now: Date()
)
} else {
shouldRevalidate = false
}
guard shouldRevalidate else { return }
SecureLogger.info(
"🔄 Revalidating cached Noise session on fresh direct link to \(peerID.id.prefix(8))…",
category: .session
)
initiateNoiseReconnectHandshake(with: peerID)
}
func configureNoiseServiceCallbacks(for service: NoiseEncryptionService) {
let (peerAuthHandlers, handshakeRequiredHandler): ([(PeerID, String) -> Void], ((PeerID) -> Void)?) = {
externalNoiseCallbacksLock.lock()
defer { externalNoiseCallbacksLock.unlock() }
return (externalPeerAuthenticatedHandlers, externalHandshakeRequiredHandler)
}()
for handler in peerAuthHandlers {
service.addOnPeerAuthenticatedHandler(handler)
}
if let handshakeRequiredHandler {
service.onHandshakeRequired = handshakeRequiredHandler
}
service.onPeerAuthenticatedWithGeneration = { [weak self] peerID, fingerprint, generation in
SecureLogger.debug("🔐 Noise session authenticated with \(peerID.id.prefix(8))…, fingerprint: \(fingerprint.prefix(16))…")
// Authentication can be reported while an initiator is still
// returning XX message 3. Serialize generation-bound state and
// every post-handshake drain behind the handshake packet handler.
self?.messageQueue.async { [weak self] in
self?.handleNoisePeerAuthenticated(
peerID: peerID,
fingerprint: fingerprint,
sessionGeneration: generation
)
}
}
service.onRekeyHandshakeReady = { [weak self, weak service] peerID, initiation in
self?.messageQueue.async { [weak self, weak service] in
guard let self,
let service,
self.noiseService === service else {
return
}
self.noteNoiseSessionCleared(for: peerID)
guard let message = service.claimHandshakeInitiation(
initiation,
for: peerID
) else {
return
}
self.broadcastNoiseHandshake(message, to: peerID)
}
}
service.onHandshakeRecoveryRequired = { [weak self, weak service] request in
guard let self, let service else { return }
#if DEBUG
self._test_beforeHandshakeRecoveryEnqueued?(request.peerID)
#endif
self.messageQueue.async { [weak self, weak service] in
guard let self,
let service,
self.noiseService === service else {
return
}
let peerID = request.peerID
guard self.isPeerReachable(peerID) else {
service.cancelHandshakeRecovery(request)
return
}
do {
guard let preparation =
try service.prepareHandshakeRecovery(request) else {
return
}
switch preparation {
case .ordinary(let initiation):
self.noteNoiseSessionCleared(for: peerID)
guard let handshakeData =
service.claimHandshakeInitiation(
initiation,
for: peerID
) else {
return
}
self.broadcastNoiseHandshake(
handshakeData,
to: peerID
)
case .transferred:
return
}
} catch {
SecureLogger.error(
"Failed to prepare handshake recovery with \(peerID.id.prefix(8))…: \(error)",
category: .session
)
}
}
}
service.onSessionRestoredWithGeneration = { [weak self, weak service] peerID, generation, reason in
guard let self, let service else { return }
// The manager makes restored keys visible atomically. Reconcile
// transport state and queued sends as the next serialized phase.
self.messageQueue.async { [weak self, weak service] in
guard let self,
let service,
self.noiseService === service,
let fingerprint = service.getPeerFingerprint(peerID) else {
return
}
SecureLogger.debug(
"🔐 Restored quarantined Noise session with \(peerID.id.prefix(8))…",
category: .session
)
// Re-enter the same generation-bound transition used after a
// successful handshake to restore authenticated protocol
// state. Only a terminal restore may also drain the PM and
// typed-payload queues: after a responder timeout the
// counterpart may have completed the replacement handshake
// and discarded the restored keys, so encrypting the queues
// under them would lose every message silently. The mandatory
// convergence retry that accompanies the restore drains them
// under the new session instead (any establishment does).
self.handleNoisePeerAuthenticated(
peerID: peerID,
fingerprint: fingerprint,
sessionGeneration: generation,
deferOutboundUntilConvergence: reason == .pendingConvergence
)
}
}
}
func handleNoisePeerAuthenticated(
peerID: PeerID,
fingerprint: String,
sessionGeneration generation: UUID,
deferOutboundUntilConvergence: Bool = false
) {
// Engine-only: the store transition below runs inside the noise
// manager's critical section while this engine slot stays blocked.
// The store is a leaf lock, so that nesting is safe — but nothing in
// that closure may sync-re-enter the engine (self-deadlock).
#if DEBUG
dispatchPrecondition(condition: .onQueue(messageQueue))
#endif
let normalizedPeerID = peerID.toShort()
// The generation lease serializes this transition against session
// replacement; nil-inside-nil distinguishes a lost lease (outer)
// from the same-generation reconciliation path (inner).
guard let leased = noiseService.withCurrentSessionGeneration(
for: normalizedPeerID,
expected: generation,
{
privateMediaSessions.beginAuthenticatedGeneration(
for: normalizedPeerID,
fingerprint: fingerprint,
generation: generation
)
}
) else { return }
guard let fresh = leased else {
// A quarantined transport restored the same cryptographic
// generation. Its capability proof and announce state never
// became stale; only work queued while outbound keys were paused
// needs one idempotent ready transition. Retrying the bounded
// early-ciphertext queue is receive-side and therefore always
// safe under the restored keys.
noisePacketHandler.handleSessionAuthenticated(normalizedPeerID)
finalizeNoisePeerAuthentication(
for: normalizedPeerID,
deferOutboundUntilConvergence: deferOutboundUntilConvergence,
sendInitialStateAndAnnounce: false
)
return
}
completePrivateMediaPolicyResolution(fresh.rejected, with: .blockedDowngrade)
schedulePrivateMediaProofTimeout(
for: normalizedPeerID,
fingerprint: fingerprint,
sessionGeneration: generation,
nonce: fresh.watchdogNonce
)
// Cross-link delivery can put ciphertext sent immediately after
// message 3 ahead of message 3 itself. Retry the bounded queue only
// after this generation's transport state has been fully installed.
noisePacketHandler.handleSessionAuthenticated(normalizedPeerID)
finalizeNoisePeerAuthentication(
for: normalizedPeerID,
deferOutboundUntilConvergence: deferOutboundUntilConvergence,
sendInitialStateAndAnnounce: true
)
}
private func finalizeNoisePeerAuthentication(
for peerID: PeerID,
deferOutboundUntilConvergence: Bool,
sendInitialStateAndAnnounce: Bool
) {
if deferOutboundUntilConvergence {
// Timeout-restore: the counterpart may have completed the
// replacement handshake and discarded these keys, so encrypting
// the parked queues here would lose them silently. The restore's
// mandatory convergence retry — or any later handshake — re-enters
// with a fresh generation and drains them under keys both sides hold.
privateMediaSessions.setOutboundDeferredUntilConvergence(peerID)
#if DEBUG
_test_onPrivateMediaSessionReconciled?(peerID)
#endif
return
}
privateMediaSessions.clearOutboundDeferredUntilConvergence(peerID)
if sendInitialStateAndAnnounce {
sendAuthenticatedPeerState(to: peerID, echo: false)
}
#if DEBUG
_test_onPrivateMediaSessionReconciled?(peerID)
#endif
sendPendingMessagesAfterHandshake(for: peerID)
sendPendingNoisePayloadsAfterHandshake(for: peerID)
if sendInitialStateAndAnnounce {
sendAnnounce(forceSend: true)
}
}
private func sendAuthenticatedPeerState(to peerID: PeerID, echo: Bool) {
let normalizedPeerID = peerID.toShort()
guard privateMediaSessions.markPeerStateSend(for: normalizedPeerID, echo: echo) else { return }
let capabilities = localIdentityState.snapshot().advertisedCapabilities
let state = AuthenticatedPeerStatePacket(
capabilities: capabilities,
signingPublicKey: noiseService.getSigningPublicKeyData()
)
guard let payload = BLENoisePayloadFactory.authenticatedPeerState(state) else {
SecureLogger.error("Failed to encode authenticated peer state", category: .security)
return
}
sendNoisePayload(payload, to: normalizedPeerID)
}
func handleAuthenticatedPeerState(
_ payload: Data,
from peerID: PeerID,
sessionGeneration generation: UUID
) {
// Engine-only, like handleNoisePeerAuthenticated: the closure below
// runs on the noise manager's queue while this engine slot stays
// blocked, so it accesses engine-owned state directly instead of
// sync-re-entering the engine (self-deadlock).
#if DEBUG
dispatchPrecondition(condition: .onQueue(messageQueue))
#endif
let normalizedPeerID = peerID.toShort()
guard let state = AuthenticatedPeerStatePacket.decode(from: payload) else {
SecureLogger.warning(
"Ignoring malformed authenticated peer state from \(normalizedPeerID.id.prefix(8))…",
category: .security
)
return
}
guard let fingerprint = noiseService.getPeerFingerprint(normalizedPeerID),
let publicKey = noiseService.getPeerPublicKeyData(normalizedPeerID),
publicKey.sha256Fingerprint().caseInsensitiveCompare(fingerprint) == .orderedSame else {
SecureLogger.warning(
"Ignoring peer state without a matching authenticated Noise identity",
category: .security
)
return
}
guard let application = noiseService.withCurrentSessionGeneration(
for: normalizedPeerID,
expected: generation,
{
() -> (accepted: Bool, completions: [@MainActor (PrivateMediaSendPolicy) -> Void]) in
guard privateMediaSessions.currentGeneration(for: normalizedPeerID) == generation else {
return (false, [])
}
// The generation lease (plus the engine slot this section
// holds) prevents rekey/session promotion from interleaving
// between validation and these durable mutations.
identityManager.bindAuthenticatedSigningPublicKey(
state.signingPublicKey,
fingerprint: fingerprint
)
identityManager.upsertCryptographicIdentity(
fingerprint: fingerprint,
noisePublicKey: publicKey,
signingPublicKey: state.signingPublicKey,
claimedNickname: nil
)
if state.capabilities.contains(.privateMedia) {
identityManager.markPrivateMediaCapable(fingerprint: fingerprint)
}
peerRegistry.mutate {
$0.bindAuthenticatedSigningPublicKey(
state.signingPublicKey,
for: normalizedPeerID
)
}
guard let completions = privateMediaSessions.applyAuthenticatedPeerState(
for: normalizedPeerID,
fingerprint: fingerprint,
generation: generation,
capabilities: state.capabilities
) else {
return (false, [])
}
return (true, completions)
}
), application.accepted else { return }
// One bounded echo makes initiator/responder proof ordering converge
// even when message 3 and the first proof take different mesh links.
sendAuthenticatedPeerState(to: normalizedPeerID, echo: true)
let policy = privateMediaSendPolicy(to: normalizedPeerID)
sendPendingNoisePayloadsAfterHandshake(for: normalizedPeerID)
completePrivateMediaPolicyResolution(application.completions, with: policy)
}
func noteNoiseSessionCleared(for peerID: PeerID) {
let normalizedPeerID = peerID.toShort()
let reset = privateMediaSessions.clearSession(for: normalizedPeerID)
if let reset {
schedulePrivateMediaProofTimeout(
for: normalizedPeerID,
fingerprint: reset.fingerprint,
sessionGeneration: nil,
nonce: reset.nonce
)
}
}
func clearNoiseSession(for peerID: PeerID) {
noiseService.clearSession(for: peerID)
noteNoiseSessionCleared(for: peerID)
}
/// Swaps `myPeerID`/`myPeerIDData` to match the current Noise identity.
/// The swap runs as a `messageQueue` barrier so in-flight work items that
/// read the identity (e.g. `sendMessage` building packets) complete
/// against the old value and everything after sees the new one atomically.
/// Callers (init, panic reset on the main thread) are never on
/// `messageQueue`; the re-entrancy check keeps any future on-queue caller
/// from deadlocking.
func refreshPeerIdentity() {
onEngine {
let fingerprint = noiseService.getIdentityFingerprint()
localIdentityState.replacePeerIdentity(
with: PeerID(str: fingerprint.prefix(16))
)
meshTopology.reset()
}
}
func sendNoisePayload(_ typedPayload: Data, to peerID: PeerID) {
sendOrQueueNoisePayload(
typedPayload,
to: peerID,
initiateOnlyIfReachable: false,
logLabel: "noise payload"
)
}
func sendOrQueueNoisePayload(
_ typedPayload: Data,
to peerID: PeerID,
initiateOnlyIfReachable: Bool,
logLabel: String
) {
// Hop like sendMessage: callers are often on the main actor, and the
// send path sync-waits on bleQueue for link state.
if DispatchQueue.getSpecific(key: messageQueueKey) == nil {
messageQueue.async { [weak self] in
self?.sendOrQueueNoisePayload(
typedPayload,
to: peerID,
initiateOnlyIfReachable: initiateOnlyIfReachable,
logLabel: logLabel
)
}
return
}
guard noiseService.hasEstablishedSession(with: peerID) else {
pendingNoiseSessionQueues.appendTypedPayload(typedPayload, for: peerID)
SecureLogger.debug("📥 Queued \(logLabel) for \(peerID.id.prefix(8))… pending handshake", category: .session)
if !initiateOnlyIfReachable || (!noiseService.hasSession(with: peerID) && isPeerReachable(peerID)) {
initiateNoiseHandshake(with: peerID)
}
return
}
do {
broadcastPacket(try makeEncryptedNoisePacket(typedPayload, to: peerID))
} catch {
SecureLogger.error("Failed to send \(logLabel): \(error)")
}
}
func makeEncryptedNoisePacket(
_ typedPayload: Data,
to peerID: PeerID,
requiresAuthenticatedPrivateMediaReceipts: Bool = false
) throws -> BitchatPacket {
let encrypted: Data
let isPrivateFile = NoisePayloadType.isPrivateFile(rawValue: typedPayload.first)
if isPrivateFile {
let provenGeneration = privateMediaSessions.provenGeneration(
for: peerID,
requireReceipts: requiresAuthenticatedPrivateMediaReceipts
)
guard let provenGeneration else {
throw NoiseEncryptionError.sessionNotEstablished
}
encrypted = try noiseService.encryptPrivateFilePayload(
typedPayload,
for: peerID,
sessionGeneration: provenGeneration
)
} else {
encrypted = try noiseService.encrypt(typedPayload, for: peerID)
}
return BitchatPacket(
type: MessageType.noiseEncrypted.rawValue,
senderID: myPeerIDData,
recipientID: Data(hexString: peerID.id),
timestamp: UInt64(Date().timeIntervalSince1970 * 1000),
payload: encrypted,
signature: nil,
ttl: messageTTL,
// v1 has a 16-bit payload length; finalized media can exceed it.
version: isPrivateFile ? 2 : 1
)
}
}
@@ -0,0 +1,363 @@
#if DEBUG
import BitFoundation
import CoreBluetooth
import Foundation
// Test-only helper to inject packets into the receive pipeline
extension BLEService {
/// Queues an event through the same MainActor hop as production receive
/// handlers so panic-boundary tests can deterministically invalidate it.
func _test_emitTransportEvent(_ event: TransportEvent) {
emitTransportEvent(event)
}
var _test_isPanicIngressOpen: Bool {
capturePanicLifecycleGeneration() != nil
}
/// Queries the receipt store of the service's OWN incoming-file store —
/// the instance production lookups run against — so panic tests exercise
/// the real wiring instead of a same-instance shortcut.
func _test_privateMediaReceiptState(
messageID: String
) -> BLEPrivateMediaReceiptState {
incomingFileStore.privateMediaReceiptState(messageID: messageID)
}
/// Models a CoreBluetooth delegate callback without requiring a physical
/// peripheral. The callback itself runs on `bleQueue`, exactly where the
/// panic radio-stop barrier must linearize it.
func _test_handlePacketFromBLEQueue(
_ packet: BitchatPacket,
fromPeerID: PeerID
) {
bleQueue.async { [weak self] in
self?.handleReceivedPacket(packet, from: fromPeerID)
}
}
/// Simulated-link ingress: the full production attribution path —
/// binding lookup, spoof rejection, raw-announce binding, ingress
/// recording — for a frame arriving on a synthetic link. The
/// SimulatedMesh harness feeds every node through this, so multi-node
/// tests exercise the same engine code as CoreBluetooth ingress.
func _test_ingestFrame(_ packet: BitchatPacket, link: BLEIngressLinkID) {
emitLinkEvent(.frameDecoded(packet, link: link, linkDescription: "Simulated \(link)"))
}
/// Sends an unthrottled announce, exactly like the maintenance forced
/// path. SimulatedMesh uses this as the deterministic discovery step.
func _test_forceAnnounce() {
onEngine { sendAnnounceNow(forceSend: true) }
}
/// Clears the announce throttle's wall-clock debt — the simulator's
/// stand-in for "enough real time has passed", since scheduler time
/// cannot move the throttle's Date-based window. Deliberately NOT
/// part of `_test_forceAnnounce`: the panic-rotation mesh test relies
/// on the production panic path performing its own reset, and a
/// blanket reset here would mask that regression.
func _test_resetAnnounceThrottle() {
announceThrottle.reset()
}
/// Blocks until every engine slot enqueued so far has run — the
/// deterministic settling fence for simulated-mesh pumping.
func _test_fenceEngine() {
onEngine {}
}
func _test_emitTransportEvent(
_ event: TransportEvent,
completion: @escaping () -> Void,
finalization: @escaping (TransportEventDeliveryOutcome) -> Void
) {
emitTransportEvent(
event,
completion: completion,
finalization: finalization
)
}
func _test_handlePacket(_ packet: BitchatPacket, fromPeerID: PeerID, preseedPeer: Bool = true, signingPublicKey: Data? = nil) {
if preseedPeer {
// Ensure the synthetic peer is known and marked verified for public-message tests
let normalizedID = PeerID(hexData: packet.senderID)
peerRegistry.mutate { registry in
if var existing = registry.info(for: normalizedID) {
existing.isConnected = true
existing.isVerifiedNickname = true
if let signingPublicKey { existing.signingPublicKey = signingPublicKey }
existing.lastSeen = Date()
registry.upsert(existing)
} else {
registry.upsert(BLEPeerInfo(
peerID: normalizedID,
nickname: "TestPeer_\(fromPeerID.id.prefix(4))",
isConnected: true,
noisePublicKey: packet.senderID,
signingPublicKey: signingPublicKey,
isVerifiedNickname: true,
lastSeen: Date()
))
}
}
}
handleReceivedPacket(packet, from: fromPeerID)
}
/// Waits until fragment ingress already submitted by a test has finished
/// reassembly/reinjection and any resulting transport event has crossed
/// the MainActor delivery hop. This is a deterministic pipeline fence,
/// avoiding wall-clock sleeps that become flaky under a parallel suite.
func _test_drainFragmentPipeline() async {
await withCheckedContinuation { continuation in
messageQueue.async {
// Reassembled packets are reinjected synchronously on
// `messageQueue`; their UI delivery task is therefore already
// enqueued before this later MainActor marker.
Task { @MainActor in
continuation.resume()
}
}
}
}
func _test_hasGossipPrekeyBundle(for peerID: PeerID) -> Bool {
gossipSyncManager?._hasPrekeyBundle(for: peerID) ?? false
}
func _test_acceptsIngress(packet: BitchatPacket, boundPeerID: PeerID?) -> Bool {
let claimedSenderID = PeerID(hexData: packet.senderID)
guard case .success = BLEIngressLinkRegistry.packetContext(
for: packet,
claimedSenderID: claimedSenderID,
boundPeerID: boundPeerID,
localPeerID: myPeerID,
directAnnounceTTL: messageTTL
) else {
return false
}
return true
}
func _test_recordIngressIfNew(packet: BitchatPacket, linkID: String) -> Bool {
recordIngressIfNew(
messageID: BLEIngressLinkRegistry.messageID(for: packet),
link: .central(linkID),
peerID: PeerID(hexData: packet.senderID)
)
}
func _test_bindCentral(_ centralUUID: String, to peerID: PeerID) {
onEngine { linkBindings.bindCentral(centralUUID, to: peerID) }
}
func _test_centralBinding(_ centralUUID: String) -> PeerID? {
onEngine { linkBindings.peer(forCentralUUID: centralUUID) }
}
func _test_linkBinding(_ link: BLEIngressLinkID) -> PeerID? {
onEngine { linkBindings.boundPeer(for: link) }
}
func _test_knownPeerIDs() -> [PeerID] {
peerRegistry.peerIDs
}
func _test_markNoiseAuthenticatedCentral(_ centralUUID: String, to peerID: PeerID) {
onEngine {
guard linkBindings.peer(forCentralUUID: centralUUID) == peerID else { return }
linkAuth.markAuthenticated(.central(centralUUID), owner: peerID)
}
}
func _test_isNoiseAuthenticatedCentral(_ centralUUID: String, for peerID: PeerID) -> Bool {
onEngine {
linkAuth.isAuthenticated(.central(centralUUID), for: peerID)
}
}
func _test_seedConnectedPeer(
_ peerID: PeerID,
nickname: String,
capabilities: PeerCapabilities? = nil,
noisePublicKey: Data? = nil
) {
peerRegistry.mutate {
$0.upsert(BLEPeerInfo(
peerID: peerID,
nickname: nickname,
isConnected: true,
noisePublicKey: noisePublicKey,
signingPublicKey: nil,
isVerifiedNickname: true,
lastSeen: Date(),
capabilities: capabilities ?? []
))
}
}
/// Handshake plumbing for tests that need a real established Noise
/// session (e.g. canDeliverSecurely) without Bluetooth in the loop.
func _test_noiseInitiateHandshake(with peerID: PeerID) throws -> Data {
try noiseService.initiateHandshake(with: peerID)
}
func _test_noiseProcessHandshakeMessage(from peerID: PeerID, message: Data) throws -> Data? {
try noiseService.processHandshakeMessage(from: peerID, message: message)
}
func _test_enqueuePendingPrivateMessage(
content: String,
messageID: String,
for peerID: PeerID
) {
onEngine {
pendingNoiseSessionQueues.appendPrivateMessage(
content: content,
messageID: messageID,
for: peerID
)
}
}
func _test_enqueuePendingNoisePayload(
_ payload: Data,
transferId: String,
for peerID: PeerID
) {
guard privateMediaTransferAdmissions.begin(transferId) == .admitted else { return }
onEngine {
pendingNoiseSessionQueues.appendTypedPayload(
payload,
transferId: transferId,
for: peerID
)
}
}
func _test_sendPendingNoisePayloadsAfterHandshake(for peerID: PeerID) {
sendPendingNoisePayloadsAfterHandshake(for: peerID)
}
func _test_hasPendingPrivateMediaPolicyResolution(for peerID: PeerID) -> Bool {
privateMediaSessions.hasPendingPolicyResolution(for: peerID.toShort())
}
func _test_forcePrivateMediaProofTimeout(for peerID: PeerID) {
let normalizedPeerID = peerID.toShort()
let target = privateMediaSessions.proofTimeoutTarget(for: normalizedPeerID)
guard let target else { return }
handlePrivateMediaProofTimeout(
for: normalizedPeerID,
fingerprint: target.fingerprint,
sessionGeneration: target.generation,
nonce: target.nonce
)
}
func _test_privateMediaTransferState(
transferId: String
) -> (admissionActive: Bool, pendingNoise: Bool, activeScheduler: Int, pendingScheduler: Int) {
let scheduler = onEngine {
(
pendingNoiseSessionQueues.containsTypedPayload(transferId: transferId),
outboundFragmentTransfers.activeCount,
outboundFragmentTransfers.pendingCount
)
}
return (
privateMediaTransferAdmissions.isActive(transferId),
scheduler.0,
scheduler.1,
scheduler.2
)
}
func _test_privateMediaAdmissionEntryCount() -> Int {
privateMediaTransferAdmissions.count
}
@discardableResult
func _test_beginPrivateMediaAdmission(_ transferId: String, now: Date) -> Bool {
privateMediaTransferAdmissions.begin(transferId, now: now) == .admitted
}
func _test_isPrivateMediaAdmissionActive(_ transferId: String, now: Date) -> Bool {
privateMediaTransferAdmissions.isActive(transferId, now: now)
}
func _test_finishPrivateMediaAdmission(_ transferId: String) {
privateMediaTransferAdmissions.finish(transferId)
}
func _test_drainPrivateMediaSendPipeline() async {
// Capture only the (Sendable) queue, not self, so the @Sendable
// dispatch closures carry no non-Sendable state.
let queue = messageQueue
await withCheckedContinuation { continuation in
queue.async {
queue.async {
continuation.resume()
}
}
}
}
func _test_broadcastPrivateMediaPacket(
_ packet: BitchatPacket,
transferId: String
) {
broadcastPacket(
packet,
transferId: transferId,
requiresPrivateMediaAdmission: true
)
}
func _test_drainNoiseMessagePipeline() async {
await _test_drainPrivateMediaSendPipeline()
}
/// Replays the current generation's ready callback. Restore tests use
/// this to prove same-generation reconciliation is idempotent.
func _test_reconcileCurrentNoiseSession(for peerID: PeerID) {
let normalizedPeerID = peerID.toShort()
messageQueue.async { [weak self] in
guard let self,
let generation = self.noiseService.sessionGeneration(
for: normalizedPeerID
),
let fingerprint = self.noiseService.getPeerFingerprint(
normalizedPeerID
) else {
return
}
self.handleNoisePeerAuthenticated(
peerID: normalizedPeerID,
fingerprint: fingerprint,
sessionGeneration: generation
)
}
}
/// Builds an authenticated-session packet from an exact typed plaintext.
/// Compatibility tests use this to model Android's deployed 0x20 file
/// payload and the short-lived 0x09 prerelease payload without exposing a
/// production API that can emit the old value.
func _test_makeEncryptedNoisePacket(_ typedPayload: Data, to peerID: PeerID) throws -> BitchatPacket {
try makeEncryptedNoisePacket(typedPayload, to: peerID)
}
static func _test_shouldRediscoverBitChatService(
invalidatedServiceUUIDs: [CBUUID],
cachedServiceUUIDs: [CBUUID]?
) -> Bool {
shouldRediscoverBitChatService(
invalidatedServiceUUIDs: invalidatedServiceUUIDs,
cachedServiceUUIDs: cachedServiceUUIDs
)
}
}
#endif
File diff suppressed because it is too large. Load diff
@@ -1,95 +0,0 @@
import BitFoundation
import Foundation
/// Tracks whether source-routed sends to a recipient appear to be working.
///
/// A routed unicast rides exactly one path, so a broken hop silently loses the
/// packet where a flood would have healed around it. Rather than building a
/// retransmission machine (MessageRouter already retries at a higher layer),
/// this cache degrades: a routed send that sees no inbound traffic from the
/// recipient within the confirmation window marks the route as failed, and
/// subsequent sends fall back to flooding until the suppression TTL lapses.
struct BLESourceRouteFailureCache {
struct Config {
/// How long a routed send may go unconfirmed before it counts as a
/// route failure.
var confirmationWindowSeconds: TimeInterval = TransportConfig.bleSourceRouteConfirmationWindowSeconds
/// How long to flood instead of routing after a failure.
var suppressionSeconds: TimeInterval = TransportConfig.bleSourceRouteSuppressionSeconds
}
private struct State {
var pendingSince: Date?
var suppressedUntil: Date?
}
private let config: Config
private var states: [PeerID: State] = [:]
init(config: Config = Config()) {
self.config = config
}
/// Whether the next directed send to `recipient` may carry a source
/// route. Flips the recipient into suppression when the last routed send
/// went unconfirmed past the confirmation window.
mutating func shouldAttemptRoute(to recipient: PeerID, now: Date = Date()) -> Bool {
guard var state = states[recipient] else { return true }
if let until = state.suppressedUntil {
guard now >= until else { return false }
state.suppressedUntil = nil
}
if let pending = state.pendingSince,
now.timeIntervalSince(pending) > config.confirmationWindowSeconds {
// The routed send was never confirmed: treat the route as broken
// and flood until the suppression window lapses.
state.pendingSince = nil
state.suppressedUntil = now.addingTimeInterval(config.suppressionSeconds)
states[recipient] = state
return false
}
states[recipient] = state
return true
}
/// Records that a source-routed packet was sent to `recipient`. Keeps the
/// earliest unconfirmed send so back-to-back packets share one deadline.
mutating func noteRoutedSend(to recipient: PeerID, now: Date = Date()) {
var state = states[recipient] ?? State()
if state.pendingSince == nil {
state.pendingSince = now
}
states[recipient] = state
}
/// Any inbound packet authored by `peer` confirms the pending routed send
/// (delivery acks and replies arrive this way). Deliberately does not
/// lift an active suppression: that traffic may have arrived via flood.
mutating func noteInboundActivity(from peer: PeerID) {
guard var state = states[peer] else { return }
state.pendingSince = nil
if state.suppressedUntil == nil {
states.removeValue(forKey: peer)
} else {
states[peer] = state
}
}
/// Drops entries that can no longer influence a routing decision. An
/// expired-but-unconverted pending entry is kept for as long as the
/// suppression it would trigger could still be active.
mutating func prune(now: Date = Date()) {
let pendingRetention = config.confirmationWindowSeconds + config.suppressionSeconds
states = states.filter { _, state in
if let until = state.suppressedUntil, now < until { return true }
if let pending = state.pendingSince,
now.timeIntervalSince(pending) <= pendingRetention {
return true
}
return false
}
}
}
@@ -1,42 +0,0 @@
import BitFoundation
import Foundation
/// Decides whether an outbound directed packet should carry a v2 source
/// route. Pure gating logic so BLEService's hot send path stays a thin wire.
enum BLESourceRouteOriginationPolicy {
/// Returns the intermediate-hop route to attach, or nil to keep the
/// current flood/direct-write behavior unchanged.
///
/// Routes are only originated when every gate passes:
/// - we authored the packet (relays must not rewrite and re-sign someone
/// else's packet; route-following for in-flight routed packets lives in
/// `BLERouteForwardingPolicy`),
/// - the packet is directed at a single peer (not broadcast),
/// - the packet has TTL headroom to traverse hops (link-local TTL-0
/// packets like REQUEST_SYNC never route),
/// - the recipient is not directly connected (a direct write already
/// delivers in one hop),
/// - routing to the recipient is not suppressed by a recent unconfirmed
/// routed send, and
/// - the topology yields a complete path.
static func route(
for packet: BitchatPacket,
to recipient: PeerID,
localPeerIDData: Data,
isRecipientConnected: (PeerID) -> Bool,
shouldAttemptRoute: (PeerID) -> Bool,
computeRoute: (PeerID) -> [Data]?
) -> [Data]? {
guard packet.route == nil,
packet.type != MessageType.fragment.rawValue else { return nil }
guard packet.senderID == localPeerIDData else { return nil }
guard let recipientData = packet.recipientID,
recipientData.count == 8,
!recipientData.allSatisfy({ $0 == 0xFF }) else { return nil }
guard packet.ttl > 1 else { return nil }
guard !isRecipientConnected(recipient) else { return nil }
guard shouldAttemptRoute(recipient) else { return nil }
guard let route = computeRoute(recipient), !route.isEmpty else { return nil }
return route
}
}
+198
View File
@@ -0,0 +1,198 @@
import BitFoundation
import Foundation
// MARK: - Source-Route Origination
/// Decides whether an outbound directed packet should carry a v2 source route.
enum BLESourceRouteOriginationPolicy {
static func route(
for packet: BitchatPacket,
to recipient: PeerID,
localPeerIDData: Data,
isRecipientConnected: (PeerID) -> Bool,
shouldAttemptRoute: (PeerID) -> Bool,
computeRoute: (PeerID) -> [Data]?
) -> [Data]? {
guard packet.route == nil,
packet.type != MessageType.fragment.rawValue else { return nil }
guard packet.senderID == localPeerIDData else { return nil }
guard let recipientData = packet.recipientID,
recipientData.count == 8,
!recipientData.allSatisfy({ $0 == 0xFF }) else { return nil }
guard packet.ttl > 1 else { return nil }
guard !isRecipientConnected(recipient) else { return nil }
guard shouldAttemptRoute(recipient) else { return nil }
guard let route = computeRoute(recipient), !route.isEmpty else { return nil }
return route
}
}
// MARK: - Source-Route Failure Suppression
/// Tracks whether source-routed sends to a recipient appear to be working,
/// falling back to flooding when a routed send goes unconfirmed.
struct BLESourceRouteFailureCache {
struct Config {
var confirmationWindowSeconds: TimeInterval = TransportConfig.bleSourceRouteConfirmationWindowSeconds
var suppressionSeconds: TimeInterval = TransportConfig.bleSourceRouteSuppressionSeconds
}
private struct State {
var pendingSince: Date?
var suppressedUntil: Date?
}
private let config: Config
private var states: [PeerID: State] = [:]
init(config: Config = Config()) {
self.config = config
}
mutating func shouldAttemptRoute(to recipient: PeerID, now: Date = Date()) -> Bool {
guard var state = states[recipient] else { return true }
if let until = state.suppressedUntil {
guard now >= until else { return false }
state.suppressedUntil = nil
}
if let pending = state.pendingSince,
now.timeIntervalSince(pending) > config.confirmationWindowSeconds {
state.pendingSince = nil
state.suppressedUntil = now.addingTimeInterval(config.suppressionSeconds)
states[recipient] = state
return false
}
states[recipient] = state
return true
}
mutating func noteRoutedSend(to recipient: PeerID, now: Date = Date()) {
var state = states[recipient] ?? State()
if state.pendingSince == nil {
state.pendingSince = now
}
states[recipient] = state
}
mutating func noteInboundActivity(from peer: PeerID) {
guard var state = states[peer] else { return }
state.pendingSince = nil
if state.suppressedUntil == nil {
states.removeValue(forKey: peer)
} else {
states[peer] = state
}
}
mutating func prune(now: Date = Date()) {
let pendingRetention = config.confirmationWindowSeconds + config.suppressionSeconds
states = states.filter { _, state in
if let until = state.suppressedUntil, now < until { return true }
if let pending = state.pendingSince,
now.timeIntervalSince(pending) <= pendingRetention {
return true
}
return false
}
}
}
// MARK: - Source-Route Forwarding
struct BLERouteForwardingPlan {
let shouldSuppressFloodRelay: Bool
let forwardPacket: BitchatPacket?
let nextHop: PeerID?
static let allowFloodRelay = BLERouteForwardingPlan(
shouldSuppressFloodRelay: false,
forwardPacket: nil,
nextHop: nil
)
static let suppressFloodRelay = BLERouteForwardingPlan(
shouldSuppressFloodRelay: true,
forwardPacket: nil,
nextHop: nil
)
static func forward(_ packet: BitchatPacket, to nextHop: PeerID) -> BLERouteForwardingPlan {
BLERouteForwardingPlan(
shouldSuppressFloodRelay: true,
forwardPacket: packet,
nextHop: nextHop
)
}
}
struct BLERouteForwardingPolicy {
static func plan(
for packet: BitchatPacket,
localPeerID: PeerID,
localRoutingData: Data?,
routingPeer: (Data) -> PeerID?,
isPeerConnected: (PeerID) -> Bool
) -> BLERouteForwardingPlan {
if packet.type == MessageType.requestSync.rawValue {
return .suppressFloodRelay
}
if PeerID(hexData: packet.recipientID) == localPeerID {
return .suppressFloodRelay
}
guard let route = packet.route, !route.isEmpty else {
return .allowFloodRelay
}
guard packet.ttl > 1 else {
return .suppressFloodRelay
}
guard let localRoutingData else {
return .allowFloodRelay
}
guard let localIndex = route.firstIndex(of: localRoutingData) else {
return forward(packet, toRouteData: route[0], routingPeer: routingPeer, isPeerConnected: isPeerConnected)
}
if localIndex == route.count - 1 {
guard let destinationPeer = PeerID(hexData: packet.recipientID),
isPeerConnected(destinationPeer) else {
return .allowFloodRelay
}
return .forward(relayed(packet), to: destinationPeer)
}
return forward(
packet,
toRouteData: route[localIndex + 1],
routingPeer: routingPeer,
isPeerConnected: isPeerConnected
)
}
private static func forward(
_ packet: BitchatPacket,
toRouteData routeData: Data,
routingPeer: (Data) -> PeerID?,
isPeerConnected: (PeerID) -> Bool
) -> BLERouteForwardingPlan {
guard let nextPeer = routingPeer(routeData),
isPeerConnected(nextPeer) else {
return .allowFloodRelay
}
return .forward(relayed(packet), to: nextPeer)
}
private static func relayed(_ packet: BitchatPacket) -> BitchatPacket {
var relayPacket = packet
relayPacket.ttl = packet.ttl - 1
return relayPacket
}
}
+77 -142
View File
@@ -100,12 +100,6 @@ final class BridgeService: ObservableObject {
static let cellPrecision = 6
}
struct QueuedUplink {
let depositor: PeerID
let cell: String
let event: NostrEvent
}
/// A validated rendezvous message ready for the timeline.
struct InboundBridgeMessage {
let messageID: String
@@ -205,12 +199,7 @@ final class BridgeService: ObservableObject {
// MARK: State
/// Loop rule 1: event IDs seen in `fromBridge` mesh broadcasts.
private var meshBroadcastEventIDs: BoundedIDSet
/// Loop rule 2: event IDs this device published (own or deposited).
private var publishedEventIDs: BoundedIDSet
/// Loop rule 3: event IDs this device already rebroadcast.
private var rebroadcastEventIDs: BoundedIDSet
private let relayEngine: CarrierRelayEngine
/// Timeline message IDs already injected (either arrival path).
private var injectedMessageIDs: BoundedIDSet
/// Signed relay/carrier events already accepted. Kept separate from the
@@ -228,15 +217,10 @@ final class BridgeService: ObservableObject {
/// Cells the rendezvous subscription covers (own + neighbor ring).
private(set) var subscribedCells: Set<String> = []
private(set) var queuedUplinks: [QueuedUplink] = []
private var uplinkDepositTimes: [PeerID: [Date]] = [:]
private var downlinkSendTimes: [Date] = []
private var inboundEventTimes: [Date] = []
private var inboundEventTimesBySigner: [String: [Date]] = [:]
private var signatureVerificationTokens = Double(Limits.signatureVerificationAttemptsPerMinute)
private var signatureVerificationLastRefillAt: Date?
private var pendingDownlinks: [(event: NostrEvent, cell: String)] = []
private var downlinkDrainScheduled = false
private var presenceTimerArmed = false
private var lastPresenceAt = Date.distantPast
@@ -248,6 +232,10 @@ final class BridgeService: ObservableObject {
private let verifyEventSignature: (NostrEvent) -> Bool
private static let enabledKey = "bridge.userEnabled"
var queuedUplinks: [CarrierRelayEngine.QueuedUplink] {
relayEngine.queuedUplinks
}
init(
defaults: UserDefaults = .standard,
now: @escaping () -> Date = Date.init,
@@ -257,9 +245,18 @@ final class BridgeService: ObservableObject {
self.now = now
self.verifyEventSignature = verifyEventSignature
self.isEnabled = defaults.bool(forKey: Self.enabledKey)
self.meshBroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
self.publishedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
self.rebroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
self.relayEngine = CarrierRelayEngine(
config: .init(
maxQueuedUplinks: Limits.maxQueuedUplinks,
maxQueuedUplinksPerDepositor: Limits.maxQueuedUplinksPerDepositor,
uplinkEventsPerMinutePerDepositor: Limits.uplinkEventsPerMinutePerDepositor,
downlinkEventsPerMinute: Limits.downlinkEventsPerMinute,
maxPendingDownlinks: Limits.maxPendingDownlinks,
maxEventAgeSeconds: Limits.maxEventAgeSeconds,
maxTrackedEventIDs: Limits.maxTrackedEventIDs
),
now: now
)
self.injectedMessageIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
self.receivedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
self.observedRadioMessageIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
@@ -272,9 +269,7 @@ final class BridgeService: ObservableObject {
isEnabled = enabled
defaults.set(enabled, forKey: Self.enabledKey)
if !enabled {
queuedUplinks.removeAll()
pendingDownlinks.removeAll()
uplinkDepositTimes.removeAll()
relayEngine.clearQueuesOnDisable()
inboundEventTimes.removeAll()
inboundEventTimesBySigner.removeAll()
participants.removeAll()
@@ -294,16 +289,13 @@ final class BridgeService: ObservableObject {
closeSubscription?()
}
isEnabled = false
nearbyOnly = false
defaults.removeObject(forKey: Self.enabledKey)
activeCell = nil
subscribedCells = []
queuedUplinks.removeAll(keepingCapacity: false)
pendingDownlinks.removeAll(keepingCapacity: false)
downlinkDrainScheduled = false
relayEngine.resetForPanic()
presenceTimerArmed = false
lastPresenceAt = .distantPast
uplinkDepositTimes.removeAll(keepingCapacity: false)
downlinkSendTimes.removeAll(keepingCapacity: false)
inboundEventTimes.removeAll(keepingCapacity: false)
inboundEventTimesBySigner.removeAll(keepingCapacity: false)
signatureVerificationTokens = Double(Limits.signatureVerificationAttemptsPerMinute)
@@ -311,12 +303,11 @@ final class BridgeService: ObservableObject {
participants.removeAll(keepingCapacity: false)
bridgedPeerCount = 0
bridgedParticipants = []
meshBroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
publishedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
rebroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
injectedMessageIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
receivedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
observedRadioMessageIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
injectedRadioAliases.removeAll(keepingCapacity: false)
injectedRadioAliasOrder.removeAll(keepingCapacity: false)
onEnabledChanged?(false)
}
@@ -401,7 +392,7 @@ final class BridgeService: ObservableObject {
SecureLogger.error("🌉 Bridge: failed to compose rendezvous event", category: .session)
return
}
publishedEventIDs.insert(event.id)
relayEngine.publishedEventIDs.insert(event.id)
injectedMessageIDs.insert(event.id) // our own timeline already has it
if relaysConnected?() ?? false {
publishToRelays?(event, cell)
@@ -424,7 +415,7 @@ final class BridgeService: ObservableObject {
lastPresenceAt = now()
guard let identity = try? deriveIdentity?(cell),
let event = try? NostrProtocol.createBridgePresenceEvent(cell: cell, senderIdentity: identity) else { return }
publishedEventIDs.insert(event.id)
relayEngine.publishedEventIDs.insert(event.id)
publishToRelays?(event, cell)
}
@@ -478,9 +469,9 @@ final class BridgeService: ObservableObject {
// deterministically, so even after a relaunch wipes the cache our
// own relay-backfilled events are recognized (field bug: own
// pre-restart messages re-rendered as bridged).
guard !publishedEventIDs.contains(event.id) else { return }
guard !relayEngine.publishedEventIDs.contains(event.id) else { return }
if isOwnRendezvousEvent(event, cell: cell) {
publishedEventIDs.insert(event.id) // never downlink it either
relayEngine.publishedEventIDs.insert(event.id) // never downlink it either
return
}
guard signatureAlreadyVerified || (allowSignatureVerificationAttempt() && verifyEventSignature(event)) else { return }
@@ -506,14 +497,19 @@ final class BridgeService: ObservableObject {
// with every online bridger serving, the holdoff lets gateways
// hear each other's broadcasts and skip duplicates.
if !isLocalRadioCopy,
!meshBroadcastEventIDs.contains(event.id),
!rebroadcastEventIDs.contains(event.id),
!pendingDownlinks.contains(where: { $0.event.id == event.id }) {
pendingDownlinks.append((event, cell))
if pendingDownlinks.count > Limits.maxPendingDownlinks {
pendingDownlinks.removeFirst(pendingDownlinks.count - Limits.maxPendingDownlinks)
}
scheduleDownlinkDrainIfNeeded(jitter: true)
!relayEngine.meshBroadcastEventIDs.contains(event.id),
!relayEngine.rebroadcastEventIDs.contains(event.id),
!relayEngine.hasPendingDownlink(event.id) {
relayEngine.enqueuePendingDownlink(event: event, scope: cell)
// Multi-gateway suppression window: enough spread for another
// gateway's broadcast to land and mark the event mesh-carried.
relayEngine.scheduleDownlinkDrainIfNeeded(
jitterDelay: Double.random(in: 0.2...1.5),
scheduleTimer: scheduleTimer,
onFire: { [weak self] in
self?.drainPendingDownlinks()
}
)
}
}
}
@@ -539,8 +535,8 @@ final class BridgeService: ObservableObject {
// A relay event can already be waiting inside the multi-gateway jitter
// window. Remove it now so it cannot consume BLE airtime after the
// authenticated radio packet proved this island already has a copy.
pendingDownlinks.removeAll { item in
guard case .message(let message)? = classify(item.event, cell: item.cell) else { return false }
relayEngine.removePendingDownlinks { item in
guard case .message(let message)? = classify(item.event, cell: item.scope) else { return false }
return message.radioMessageIDHint == messageID
}
}
@@ -572,12 +568,10 @@ final class BridgeService: ObservableObject {
SecureLogger.debug("🌉 Bridge: rejected deposit from \(depositor.id.prefix(8))… (failed validation)", category: .security)
return
}
guard !meshBroadcastEventIDs.contains(event.id),
!publishedEventIDs.contains(event.id),
!queuedUplinks.contains(where: { $0.event.id == event.id }) else {
guard !relayEngine.isUplinkDuplicate(event.id) else {
return
}
guard allowUplinkDeposit(from: depositor) else {
guard relayEngine.allowUplinkDeposit(from: depositor) else {
SecureLogger.debug("🌉 Bridge: rate-limited deposit from \(depositor.id.prefix(8))…", category: .session)
return
}
@@ -588,7 +582,7 @@ final class BridgeService: ObservableObject {
if relaysConnected?() ?? false {
publish(event, cell: carrier.geohash)
} else {
enqueueUplink(QueuedUplink(depositor: depositor, cell: carrier.geohash, event: event))
relayEngine.enqueueUplink(depositor: depositor, scope: carrier.geohash, event: event)
}
// No local injection: the depositor's radio broadcast already carried
// the message to this island, including us.
@@ -596,47 +590,18 @@ final class BridgeService: ObservableObject {
/// Publish everything queued while relays were unreachable.
func flushQueuedUplinks() {
guard isEnabled, relaysConnected?() ?? false, !queuedUplinks.isEmpty else { return }
let queued = queuedUplinks
queuedUplinks.removeAll()
for item in queued where !publishedEventIDs.contains(item.event.id) {
publish(item.event, cell: item.cell)
guard isEnabled, relaysConnected?() ?? false else { return }
relayEngine.flushQueuedUplinks { event, cell in
publish(event, cell: cell)
}
}
private func publish(_ event: NostrEvent, cell: String) {
publishedEventIDs.insert(event.id)
relayEngine.publishedEventIDs.insert(event.id)
publishToRelays?(event, cell)
SecureLogger.info("🌉 Bridge: published carried event \(event.id.prefix(8))… for cell \(cell)", category: .session)
}
@discardableResult
private func enqueueUplink(_ item: QueuedUplink) -> Bool {
let fromDepositor = queuedUplinks.filter { $0.depositor == item.depositor }.count
guard fromDepositor < Limits.maxQueuedUplinksPerDepositor else { return false }
if queuedUplinks.count >= Limits.maxQueuedUplinks {
queuedUplinks.removeFirst(queuedUplinks.count - Limits.maxQueuedUplinks + 1)
}
queuedUplinks.append(item)
return true
}
private func allowUplinkDeposit(from depositor: PeerID) -> Bool {
let cutoff = now().addingTimeInterval(-60)
var times = uplinkDepositTimes[depositor, default: []]
times.removeAll { $0 < cutoff }
guard times.count < Limits.uplinkEventsPerMinutePerDepositor else {
uplinkDepositTimes[depositor] = times
return false
}
times.append(now())
uplinkDepositTimes[depositor] = times
if uplinkDepositTimes.count > Limits.maxTrackedEventIDs {
uplinkDepositTimes = uplinkDepositTimes.filter { $0.value.contains { $0 >= cutoff } }
}
return true
}
/// Bounds relay/carrier work independently of the downlink airtime budget.
/// A valid signature proves control of one key, not that the sender is
/// entitled to unbounded main-actor state or CPU.
@@ -686,59 +651,33 @@ final class BridgeService: ObservableObject {
// MARK: - Downlink (gateway role: internet -> mesh)
private func drainPendingDownlinks() {
let cutoff = now().addingTimeInterval(-60)
downlinkSendTimes.removeAll { $0 < cutoff }
while !pendingDownlinks.isEmpty,
downlinkSendTimes.count < Limits.downlinkEventsPerMinute {
let (event, cell) = pendingDownlinks.removeFirst()
guard isFresh(event) else { continue }
// Suppression recheck at send time: another gateway may have
// broadcast this event, or the authenticated radio copy may have
// arrived, during our jitter holdoff.
guard !meshBroadcastEventIDs.contains(event.id),
!rebroadcastEventIDs.contains(event.id) else { continue }
if case .message(let message)? = classify(event, cell: cell),
let radioMessageID = message.radioMessageIDHint,
radioCopyAlreadyPresent(radioMessageID) {
continue
relayEngine.drainPendingDownlinks(
direction: .fromBridge,
shouldSend: { [weak self] event, cell in
guard let self else { return false }
// Suppression recheck at send time: another gateway may have
// broadcast this event, or the authenticated radio copy may have
// arrived, during our jitter holdoff.
guard !self.relayEngine.meshBroadcastEventIDs.contains(event.id),
!self.relayEngine.rebroadcastEventIDs.contains(event.id) else {
return false
}
if case .message(let message)? = self.classify(event, cell: cell),
let radioMessageID = message.radioMessageIDHint,
self.radioCopyAlreadyPresent(radioMessageID) {
return false
}
return true
},
send: { [weak self] payload, event in
self?.broadcastToMesh?(payload)
SecureLogger.debug("🌉 Bridge: downlinked remote event \(event.id.prefix(8))… onto the mesh", category: .session)
},
scheduleTimer: scheduleTimer,
onScheduledDrain: { [weak self] in
self?.drainPendingDownlinks()
}
guard let carrier = NostrCarrierPacket(direction: .fromBridge, geohash: cell, event: event),
let payload = carrier.encode() else { continue }
broadcastToMesh?(payload)
SecureLogger.debug("🌉 Bridge: downlinked remote event \(event.id.prefix(8))… onto the mesh", category: .session)
// Mark-after-send (loop rule 3): a queue-overflow drop stays
// retryable on relay redelivery.
rebroadcastEventIDs.insert(event.id)
downlinkSendTimes.append(now())
}
scheduleDownlinkDrainIfNeeded()
}
private func scheduleDownlinkDrainIfNeeded(jitter: Bool = false) {
guard !pendingDownlinks.isEmpty, !downlinkDrainScheduled else { return }
let delay: TimeInterval
if jitter {
// Multi-gateway suppression window: enough spread for another
// gateway's broadcast to land and mark the event mesh-carried.
delay = Double.random(in: 0.2...1.5)
} else {
let oldest = downlinkSendTimes.min() ?? now()
delay = max(0.05, 60 - now().timeIntervalSince(oldest))
}
downlinkDrainScheduled = true
let fire: @MainActor () -> Void = { [weak self] in
guard let self else { return }
self.downlinkDrainScheduled = false
self.drainPendingDownlinks()
}
if let scheduleTimer {
scheduleTimer(delay, fire)
} else {
Task { @MainActor in
try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
fire()
}
}
)
}
// MARK: - Downlink (receiver role: carried event arrives over radio)
@@ -748,7 +687,7 @@ final class BridgeService: ObservableObject {
// radio, and two phones side by side should not disagree about what
// the channel said. Publishing/subscribing remain opt-in.
guard let event = structurallyValidEvent(from: carrier),
!publishedEventIDs.contains(event.id),
!relayEngine.publishedEventIDs.contains(event.id),
!isOwnRendezvousEvent(event, cell: carrier.geohash),
allowSignatureVerificationAttempt(),
verifyEventSignature(event) else {
@@ -757,7 +696,7 @@ final class BridgeService: ObservableObject {
// Mark after verification (a forged copy must not poison the cache),
// even when the relay copy won the injection race: pending gateway
// downlinks consult this cache and must stand down.
let firstMeshArrival = meshBroadcastEventIDs.insert(event.id)
let firstMeshArrival = relayEngine.meshBroadcastEventIDs.insert(event.id)
guard firstMeshArrival,
receivedEventIDs.insert(event.id),
allowInboundEvent(from: event.pubkey) else { return }
@@ -868,7 +807,7 @@ final class BridgeService: ObservableObject {
/// Classifies a structurally acceptable rendezvous event; nil rejects.
private func classify(_ event: NostrEvent, cell: String) -> RendezvousKind? {
guard isFresh(event),
guard relayEngine.isFresh(event),
event.tags.contains(where: { $0.count >= 2 && $0[0] == "r" && $0[1] == cell }),
GatewayService.isValidGeohash(cell) else {
return nil
@@ -925,10 +864,6 @@ final class BridgeService: ObservableObject {
return event
}
private func isFresh(_ event: NostrEvent) -> Bool {
abs(now().timeIntervalSince1970 - TimeInterval(event.created_at)) <= Limits.maxEventAgeSeconds
}
/// True when the event was signed by this device's own derived
/// rendezvous identity for the cell. Survives relaunches (unlike the
/// published-ID cache) because the derivation is deterministic; the
@@ -0,0 +1,203 @@
//
// CarrierRelayEngine.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import BitFoundation
import Foundation
/// Shared uplink/downlink queueing, rate-limiting, freshness, and loop-prevention
/// state machine used by `GatewayService` and `BridgeService`.
@MainActor
final class CarrierRelayEngine {
struct Config {
let maxQueuedUplinks: Int
let maxQueuedUplinksPerDepositor: Int
let uplinkEventsPerMinutePerDepositor: Int
let downlinkEventsPerMinute: Int
let maxPendingDownlinks: Int
let maxEventAgeSeconds: TimeInterval
let maxTrackedEventIDs: Int
}
struct QueuedUplink {
let depositor: PeerID
let scope: String
let event: NostrEvent
}
/// Loop rule 1: event IDs seen in downlink (`fromGateway`/`fromBridge`) mesh broadcasts.
var meshBroadcastEventIDs: BoundedIDSet
/// Loop rule 2: event IDs this device already published to relays.
var publishedEventIDs: BoundedIDSet
/// Loop rule 3: event IDs this device already rebroadcast onto the mesh.
var rebroadcastEventIDs: BoundedIDSet
private(set) var queuedUplinks: [QueuedUplink] = []
private(set) var pendingDownlinks: [(event: NostrEvent, scope: String)] = []
private var uplinkDepositTimes: [PeerID: [Date]] = [:]
private var downlinkSendTimes: [Date] = []
private var downlinkDrainScheduled = false
private let config: Config
private let now: () -> Date
init(config: Config, now: @escaping () -> Date) {
self.config = config
self.now = now
self.meshBroadcastEventIDs = BoundedIDSet(capacity: config.maxTrackedEventIDs)
self.publishedEventIDs = BoundedIDSet(capacity: config.maxTrackedEventIDs)
self.rebroadcastEventIDs = BoundedIDSet(capacity: config.maxTrackedEventIDs)
}
// MARK: - Lifecycle
func clearQueuesOnDisable() {
queuedUplinks.removeAll()
pendingDownlinks.removeAll()
uplinkDepositTimes.removeAll()
}
func resetForPanic() {
queuedUplinks.removeAll(keepingCapacity: false)
pendingDownlinks.removeAll(keepingCapacity: false)
downlinkDrainScheduled = false
uplinkDepositTimes.removeAll(keepingCapacity: false)
downlinkSendTimes.removeAll(keepingCapacity: false)
meshBroadcastEventIDs = BoundedIDSet(capacity: config.maxTrackedEventIDs)
publishedEventIDs = BoundedIDSet(capacity: config.maxTrackedEventIDs)
rebroadcastEventIDs = BoundedIDSet(capacity: config.maxTrackedEventIDs)
}
// MARK: - Freshness & Dedup
/// True when `event.created_at` is within the accepted clock skew window.
func isFresh(_ event: NostrEvent) -> Bool {
abs(now().timeIntervalSince1970 - TimeInterval(event.created_at)) <= config.maxEventAgeSeconds
}
func isUplinkDuplicate(_ eventID: String) -> Bool {
meshBroadcastEventIDs.contains(eventID)
|| publishedEventIDs.contains(eventID)
|| queuedUplinks.contains(where: { $0.event.id == eventID })
}
func hasPendingDownlink(_ eventID: String) -> Bool {
pendingDownlinks.contains(where: { $0.event.id == eventID })
}
func removePendingDownlinks(where shouldRemove: ((event: NostrEvent, scope: String)) -> Bool) {
pendingDownlinks.removeAll(where: shouldRemove)
}
// MARK: - Uplink Queue & Rate Limiting
@discardableResult
func enqueueUplink(depositor: PeerID, scope: String, event: NostrEvent) -> Bool {
let fromDepositor = queuedUplinks.filter { $0.depositor == depositor }.count
guard fromDepositor < config.maxQueuedUplinksPerDepositor else {
return false
}
if queuedUplinks.count >= config.maxQueuedUplinks {
queuedUplinks.removeFirst(queuedUplinks.count - config.maxQueuedUplinks + 1)
}
queuedUplinks.append(QueuedUplink(depositor: depositor, scope: scope, event: event))
return true
}
func flushQueuedUplinks(publish: (NostrEvent, String) -> Void) {
guard !queuedUplinks.isEmpty else { return }
let queued = queuedUplinks
queuedUplinks.removeAll()
for item in queued where !publishedEventIDs.contains(item.event.id) {
publish(item.event, item.scope)
}
}
func allowUplinkDeposit(from depositor: PeerID) -> Bool {
let currentTime = now()
let cutoff = currentTime.addingTimeInterval(-60)
var times = uplinkDepositTimes[depositor, default: []]
times.removeAll { $0 < cutoff }
guard times.count < config.uplinkEventsPerMinutePerDepositor else {
uplinkDepositTimes[depositor] = times
return false
}
times.append(currentTime)
uplinkDepositTimes[depositor] = times
if uplinkDepositTimes.count > config.maxTrackedEventIDs {
uplinkDepositTimes = uplinkDepositTimes.filter { $0.value.contains { $0 >= cutoff } }
}
return true
}
// MARK: - Downlink Queue & Paced Drain
func enqueuePendingDownlink(event: NostrEvent, scope: String) {
pendingDownlinks.append((event, scope))
if pendingDownlinks.count > config.maxPendingDownlinks {
// Bandwidth guard: drop-oldest — fresher chat is worth more. Dropped
// events are not yet marked in `rebroadcastEventIDs`, so a later
// relay redelivery can still carry them.
pendingDownlinks.removeFirst(pendingDownlinks.count - config.maxPendingDownlinks)
}
}
func drainPendingDownlinks(
direction: NostrCarrierPacket.Direction,
shouldSend: (NostrEvent, String) -> Bool = { _, _ in true },
send: (Data, NostrEvent) -> Void,
scheduleTimer: ((TimeInterval, @escaping @MainActor () -> Void) -> Void)?,
onScheduledDrain: @escaping @MainActor () -> Void
) {
let cutoff = now().addingTimeInterval(-60)
downlinkSendTimes.removeAll { $0 < cutoff }
while !pendingDownlinks.isEmpty,
downlinkSendTimes.count < config.downlinkEventsPerMinute {
let (event, scope) = pendingDownlinks.removeFirst()
guard isFresh(event), shouldSend(event, scope) else { continue }
guard let carrier = NostrCarrierPacket(direction: direction, geohash: scope, event: event),
let payload = carrier.encode() else { continue }
send(payload, event)
rebroadcastEventIDs.insert(event.id)
downlinkSendTimes.append(now())
}
scheduleDownlinkDrainIfNeeded(
jitterDelay: nil,
scheduleTimer: scheduleTimer,
onFire: onScheduledDrain
)
}
func scheduleDownlinkDrainIfNeeded(
jitterDelay: TimeInterval?,
scheduleTimer: ((TimeInterval, @escaping @MainActor () -> Void) -> Void)?,
onFire: @escaping @MainActor () -> Void
) {
guard !pendingDownlinks.isEmpty, !downlinkDrainScheduled else { return }
let delay: TimeInterval
if let jitterDelay {
delay = jitterDelay
} else {
let oldest = downlinkSendTimes.min() ?? now()
delay = max(0.05, 60 - now().timeIntervalSince(oldest))
}
downlinkDrainScheduled = true
let fire: @MainActor () -> Void = { [weak self] in
guard let self else { return }
self.downlinkDrainScheduled = false
onFire()
}
if let scheduleTimer {
scheduleTimer(delay, fire)
} else {
Task { @MainActor in
try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
fire()
}
}
}
}
+51 -152
View File
@@ -78,12 +78,6 @@ final class GatewayService: ObservableObject {
static let maxTrackedEventIDs = 512
}
struct QueuedUplink {
let depositor: PeerID
let geohash: String
let event: NostrEvent
}
static let shared = GatewayService()
/// The user toggle. While true this device advertises `.gateway` and
@@ -117,31 +111,29 @@ final class GatewayService: ObservableObject {
// MARK: State
/// Loop rule 1: event IDs seen in `fromGateway` mesh broadcasts.
private var meshBroadcastEventIDs: BoundedIDSet
/// Loop rule 2 (uplink): event IDs this gateway already published.
private var publishedEventIDs: BoundedIDSet
/// Loop rule 2 (downlink): event IDs this gateway already rebroadcast.
private var rebroadcastEventIDs: BoundedIDSet
private(set) var queuedUplinks: [QueuedUplink] = []
private var uplinkDepositTimes: [PeerID: [Date]] = [:]
private var downlinkSendTimes: [Date] = []
private var pendingDownlinks: [(event: NostrEvent, geohash: String)] = []
/// True while a drain timer is armed, so a burst schedules at most one.
private var downlinkDrainScheduled = false
private let relayEngine: CarrierRelayEngine
private let defaults: UserDefaults
private let now: () -> Date
private static let enabledKey = "gateway.userEnabled"
var queuedUplinks: [CarrierRelayEngine.QueuedUplink] {
relayEngine.queuedUplinks
}
init(defaults: UserDefaults = .standard, now: @escaping () -> Date = Date.init) {
self.defaults = defaults
self.now = now
self.isEnabled = defaults.bool(forKey: Self.enabledKey)
self.meshBroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
self.publishedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
self.rebroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
self.relayEngine = CarrierRelayEngine(
config: .init(
maxQueuedUplinks: Limits.maxQueuedUplinks,
maxQueuedUplinksPerDepositor: Limits.maxQueuedUplinksPerDepositor,
uplinkEventsPerMinutePerDepositor: Limits.uplinkEventsPerMinutePerDepositor,
downlinkEventsPerMinute: Limits.downlinkEventsPerMinute,
maxPendingDownlinks: Limits.maxPendingDownlinks,
maxEventAgeSeconds: Limits.maxEventAgeSeconds,
maxTrackedEventIDs: Limits.maxTrackedEventIDs
),
now: now
)
}
// MARK: - Toggle
@@ -151,9 +143,7 @@ final class GatewayService: ObservableObject {
isEnabled = enabled
defaults.set(enabled, forKey: Self.enabledKey)
if !enabled {
queuedUplinks.removeAll()
pendingDownlinks.removeAll()
uplinkDepositTimes.removeAll()
relayEngine.clearQueuesOnDisable()
}
SecureLogger.info("🌐 Gateway mode \(enabled ? "enabled" : "disabled")", category: .session)
onEnabledChanged?(enabled)
@@ -164,14 +154,7 @@ final class GatewayService: ObservableObject {
func resetForPanic() {
isEnabled = false
defaults.removeObject(forKey: Self.enabledKey)
queuedUplinks.removeAll(keepingCapacity: false)
pendingDownlinks.removeAll(keepingCapacity: false)
downlinkDrainScheduled = false
uplinkDepositTimes.removeAll(keepingCapacity: false)
downlinkSendTimes.removeAll(keepingCapacity: false)
meshBroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
publishedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
rebroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
relayEngine.resetForPanic()
onEnabledChanged?(false)
}
@@ -217,15 +200,13 @@ final class GatewayService: ObservableObject {
// re-published. Loop rule 2: repeat deposits of an already handled
// event are absorbed. A replay of one valid deposit is short-circuited
// here without a per-packet signature verify.
guard !meshBroadcastEventIDs.contains(event.id),
!publishedEventIDs.contains(event.id),
!queuedUplinks.contains(where: { $0.event.id == event.id }) else {
guard !relayEngine.isUplinkDuplicate(event.id) else {
return
}
// Consume the per-depositor rate token BEFORE the expensive verify so
// a flood of distinct forged/junk deposits is bounded by cheap work,
// not by main-actor Schnorr verifications.
guard allowUplinkDeposit(from: depositor) else {
guard relayEngine.allowUplinkDeposit(from: depositor) else {
SecureLogger.debug("🌐 Gateway: rate-limited uplink deposit from \(depositor.id.prefix(8))…", category: .session)
return
}
@@ -240,7 +221,10 @@ final class GatewayService: ObservableObject {
publish(event, geohash: carrier.geohash)
accepted = true
} else {
accepted = enqueueUplink(QueuedUplink(depositor: depositor, geohash: carrier.geohash, event: event))
accepted = relayEngine.enqueueUplink(depositor: depositor, scope: carrier.geohash, event: event)
if !accepted {
SecureLogger.debug("🌐 Gateway: uplink queue quota reached for \(depositor.id.prefix(8))…", category: .session)
}
}
// Only render on our own timeline what we actually accepted for
@@ -255,52 +239,18 @@ final class GatewayService: ObservableObject {
/// Publish everything queued while relays were unreachable. Called when
/// relay connectivity comes back.
func flushQueuedUplinks() {
guard isEnabled, relaysConnected?() ?? false, !queuedUplinks.isEmpty else { return }
let queued = queuedUplinks
queuedUplinks.removeAll()
for item in queued where !publishedEventIDs.contains(item.event.id) {
publish(item.event, geohash: item.geohash)
guard isEnabled, relaysConnected?() ?? false else { return }
relayEngine.flushQueuedUplinks { event, geohash in
publish(event, geohash: geohash)
}
}
private func publish(_ event: NostrEvent, geohash: String) {
publishedEventIDs.insert(event.id)
relayEngine.publishedEventIDs.insert(event.id)
publishToRelays?(event, geohash)
SecureLogger.info("🌐 Gateway: published carried event \(event.id.prefix(8))… to relays for #\(geohash)", category: .session)
}
/// Returns true when the item was actually stored for later publish.
@discardableResult
private func enqueueUplink(_ item: QueuedUplink) -> Bool {
let fromDepositor = queuedUplinks.filter { $0.depositor == item.depositor }.count
guard fromDepositor < Limits.maxQueuedUplinksPerDepositor else {
SecureLogger.debug("🌐 Gateway: uplink queue quota reached for \(item.depositor.id.prefix(8))…", category: .session)
return false
}
if queuedUplinks.count >= Limits.maxQueuedUplinks {
queuedUplinks.removeFirst(queuedUplinks.count - Limits.maxQueuedUplinks + 1)
}
queuedUplinks.append(item)
return true
}
private func allowUplinkDeposit(from depositor: PeerID) -> Bool {
let cutoff = now().addingTimeInterval(-60)
var times = uplinkDepositTimes[depositor, default: []]
times.removeAll { $0 < cutoff }
guard times.count < Limits.uplinkEventsPerMinutePerDepositor else {
uplinkDepositTimes[depositor] = times
return false
}
times.append(now())
uplinkDepositTimes[depositor] = times
// Bound the tracker itself against a churn of spoofed depositors.
if uplinkDepositTimes.count > Limits.maxTrackedEventIDs {
uplinkDepositTimes = uplinkDepositTimes.filter { !$0.value.isEmpty && $0.value.contains { $0 >= cutoff } }
}
return true
}
// MARK: - Downlink (gateway role: internet -> mesh)
/// Called for every event the gateway's own geohash-channel subscription
@@ -315,84 +265,40 @@ final class GatewayService: ObservableObject {
// same window — so rebroadcasting backfill would burn the whole
// per-minute budget on events no mesh peer accepts. Also require the
// event's own `#g` tag to match the carrier geohash.
guard isFresh(event),
guard relayEngine.isFresh(event),
event.tags.contains(where: { $0.count >= 2 && $0[0] == "g" && $0[1] == geohash }) else {
return
}
// Loop rule 1: never rebroadcast mesh-carried events back onto the
// mesh. Loop rule 2 (self-echo): never rebroadcast an event this
// gateway itself uplinked (`publishedEventIDs`) — it originated on this
// very mesh, so our own relay subscription echoing it back must not
// double the BLE airtime by pushing it out again. Loop rule 2
// (downlink): rebroadcast each genuine inbound relay event at most once
// — but mark only AFTER it is actually sent (in `drainPendingDownlinks`),
// so an event dropped by the queue overflow stays retryable on relay
// redelivery. Guard against a redelivery re-queueing an event that is
// still waiting to be sent.
guard !meshBroadcastEventIDs.contains(event.id),
!publishedEventIDs.contains(event.id),
!rebroadcastEventIDs.contains(event.id),
!pendingDownlinks.contains(where: { $0.event.id == event.id }) else {
// gateway itself uplinked (`publishedEventIDs`). Loop rule 2 (downlink):
// rebroadcast each genuine inbound relay event at most once — marked
// only AFTER it is actually sent so queue-overflow drops stay retryable.
guard !relayEngine.meshBroadcastEventIDs.contains(event.id),
!relayEngine.publishedEventIDs.contains(event.id),
!relayEngine.rebroadcastEventIDs.contains(event.id),
!relayEngine.hasPendingDownlink(event.id) else {
return
}
// Verify before spending BLE airtime when not already verified by
// NostrRelayManager's off-main inbound pipeline; receivers verify again.
guard signatureAlreadyVerified || event.isValidSignature() else { return }
pendingDownlinks.append((event, geohash))
if pendingDownlinks.count > Limits.maxPendingDownlinks {
// Bandwidth guard: drop-oldest — fresher chat is worth more. The
// dropped event is not yet in `rebroadcastEventIDs`, so a later
// relay redelivery can still carry it.
pendingDownlinks.removeFirst(pendingDownlinks.count - Limits.maxPendingDownlinks)
}
relayEngine.enqueuePendingDownlink(event: event, scope: geohash)
drainPendingDownlinks()
}
private func drainPendingDownlinks() {
let cutoff = now().addingTimeInterval(-60)
downlinkSendTimes.removeAll { $0 < cutoff }
while !pendingDownlinks.isEmpty,
downlinkSendTimes.count < Limits.downlinkEventsPerMinute {
let (event, geohash) = pendingDownlinks.removeFirst()
// A queued event may have aged past the window while it waited;
// don't burn airtime on what receivers would now drop.
guard isFresh(event) else { continue }
guard let carrier = NostrCarrierPacket(direction: .fromGateway, geohash: geohash, event: event),
let payload = carrier.encode() else { continue }
broadcastToMesh?(payload)
// Mark-after-send: only now is the relay event definitively
// rebroadcast (loop rule 2).
rebroadcastEventIDs.insert(event.id)
downlinkSendTimes.append(now())
}
// Budget exhausted with events still queued: arm a timer to drain when
// the window frees, instead of stranding them until the next inbound
// relay event (which may never come on a channel that went quiet).
scheduleDownlinkDrainIfNeeded()
}
/// Arms a single timer to drain the backlog once the per-minute window
/// frees. No-op when nothing is pending or a drain is already scheduled.
private func scheduleDownlinkDrainIfNeeded() {
guard !pendingDownlinks.isEmpty, !downlinkDrainScheduled else { return }
// The window frees when the oldest recorded send ages out of 60s.
let oldest = downlinkSendTimes.min() ?? now()
let delay = max(0.05, 60 - now().timeIntervalSince(oldest))
downlinkDrainScheduled = true
let fire: @MainActor () -> Void = { [weak self] in
guard let self else { return }
self.downlinkDrainScheduled = false
self.drainPendingDownlinks()
}
if let scheduleDrainTimer {
scheduleDrainTimer(delay, fire)
} else {
Task { @MainActor in
try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
fire()
relayEngine.drainPendingDownlinks(
direction: .fromGateway,
send: { [weak self] payload, _ in
self?.broadcastToMesh?(payload)
},
scheduleTimer: scheduleDrainTimer,
onScheduledDrain: { [weak self] in
self?.drainPendingDownlinks()
}
}
)
}
// MARK: - Downlink (receiver role: carried event arrives over mesh)
@@ -404,7 +310,7 @@ final class GatewayService: ObservableObject {
// marking as dedup: the same broadcast relayed along several mesh
// paths injects once (the pipeline's Nostr event-ID cache additionally
// dedups against our own relay subscription).
guard meshBroadcastEventIDs.insert(event.id) else { return }
guard relayEngine.meshBroadcastEventIDs.insert(event.id) else { return }
// Only inject events for the channel we're viewing; the inbound
// pipeline files public messages under the current geohash.
guard currentGeohash?() == carrier.geohash else { return }
@@ -425,8 +331,8 @@ final class GatewayService: ObservableObject {
/// never reach this path, and the mesh-carried guard below backstops it.
func uplinkViaMesh(event: NostrEvent, geohash: String) -> Bool {
if relaysConnected?() ?? true { return false }
guard !meshBroadcastEventIDs.contains(event.id),
!publishedEventIDs.contains(event.id) else {
guard !relayEngine.meshBroadcastEventIDs.contains(event.id),
!relayEngine.publishedEventIDs.contains(event.id) else {
return false
}
// A single gateway is enough — relays fan out from there, and BLE
@@ -464,19 +370,12 @@ final class GatewayService: ObservableObject {
let event = carrier.event(),
event.kind == NostrProtocol.EventKind.ephemeralEvent.rawValue,
event.tags.contains(where: { $0.count >= 2 && $0[0] == "g" && $0[1] == carrier.geohash }),
isFresh(event) else {
relayEngine.isFresh(event) else {
return nil
}
return event
}
/// True when `event.created_at` is within the accepted clock skew — the
/// SAME freshness window receivers enforce, so a gateway never spends
/// airtime on events every receiver would drop as stale.
private func isFresh(_ event: NostrEvent) -> Bool {
abs(now().timeIntervalSince1970 - TimeInterval(event.created_at)) <= Limits.maxEventAgeSeconds
}
private static let validGeohashCharacters: Set<Character> = Set("0123456789bcdefghjkmnpqrstuvwxyz")
static func isValidGeohash(_ geohash: String) -> Bool {
+2 -23
View File
@@ -240,18 +240,8 @@ final class NostrTransport: Transport, @unchecked Sendable {
weak var eventDelegate: TransportEventDelegate?
weak var peerEventsDelegate: TransportPeerEventsDelegate?
func currentPeerSnapshots() -> [TransportPeerSnapshot] { [] }
var myPeerID: PeerID { senderPeerID }
var myNickname: String { "" }
func setNickname(_ nickname: String) { /* not used for Nostr */ }
func startServices() { /* no-op */ }
func stopServices() { /* no-op */ }
func emergencyDisconnectAll() { /* no-op */ }
func isPeerConnected(_ peerID: PeerID) -> Bool { false }
func isPeerReachable(_ peerID: PeerID) -> Bool {
// Callers address peers by either the short 16-hex ID or the full
// 64-hex noise key (offline favorites), so compare in short form.
@@ -276,18 +266,8 @@ final class NostrTransport: Transport, @unchecked Sendable {
canDeliverPromptly(to: peerID)
}
func peerNickname(peerID: PeerID) -> String? { nil }
func getPeerNicknames() -> [PeerID: String] { [:] }
func getFingerprint(for peerID: PeerID) -> String? { nil }
func getNoiseSessionState(for peerID: PeerID) -> LazyHandshakeState { .none }
func triggerHandshake(with peerID: PeerID) { /* no-op */ }
// Nostr does not use Noise sessions here; the inert Transport defaults
// for the noise* identity hooks apply.
// Public broadcast not supported over Nostr here
func sendMessage(_ content: String, mentions: [String]) { /* no-op */ }
// Mesh-only lifecycle, discovery, Noise, and broadcast Transport hooks use
// the inert defaults defined in `extension Transport`.
func sendPrivateMessage(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String) {
let generation = dependencies.ackPacer.currentGeneration()
@@ -334,7 +314,6 @@ final class NostrTransport: Transport, @unchecked Sendable {
}
}
func sendBroadcastAnnounce() { /* no-op for Nostr */ }
func sendDeliveryAck(for messageID: String, to peerID: PeerID) {
enqueueAck(.deliveredDirect(messageID: messageID, peerID: peerID))
}
+9 -34
View File
@@ -8,25 +8,17 @@
import BitLogger
import BitFoundation
import Combine
import Foundation
import SwiftUI
/// Manages private chat session policy (selection, read receipts,
/// consolidation). Message storage lives in the single-writer
/// `ConversationStore` (docs/CONVERSATION-STORE-DESIGN.md); the
/// `privateChats` / `unreadMessages` properties below are read-only views
/// derived from it.
/// Manages private chat session policy (selection delegation, read receipts,
/// consolidation). Message and selection state live in the single-writer
/// `ConversationStore`.
@MainActor
final class PrivateChatManager: ObservableObject {
/// Read-only mirror of `ConversationStore.selectedPrivatePeerID` — the
/// store is the sole owner of conversation selection. Kept `@Published`
/// so existing observers (`objectWillChange` forwarding into
/// `ChatViewModel`) keep firing on selection changes. Mutate via
/// `startChat(with:)` / `endChat()`, which route through the store's
/// `setSelectedPrivatePeer` intent.
@Published private(set) var selectedPeer: PeerID? = nil
private var selectedPeerMirrorCancellable: AnyCancellable? = nil
final class PrivateChatManager {
/// Current direct-conversation selection, read directly from `ConversationStore`.
var selectedPeer: PeerID? {
conversationStore?.selectedPrivatePeerID
}
var sentReadReceipts: Set<String> = [] // Made accessible for ChatViewModel
@@ -37,34 +29,17 @@ final class PrivateChatManager: ObservableObject {
weak var unifiedPeerService: UnifiedPeerService?
/// Single source of truth for message and selection state; injected by
/// the bootstrapper (`wireServiceGraph`).
var conversationStore: ConversationStore? {
didSet { bindSelectionMirror() }
}
var conversationStore: ConversationStore?
init(meshService: Transport? = nil, conversationStore: ConversationStore? = nil) {
self.meshService = meshService
self.conversationStore = conversationStore
bindSelectionMirror() // didSet does not fire during init
}
func resetForPanic() {
sentReadReceipts.removeAll(keepingCapacity: false)
}
/// Keeps `selectedPeer` in lock-step with the store's selection axis
/// (including store-internal handoffs such as conversation migration).
private func bindSelectionMirror() {
guard let store = conversationStore else {
selectedPeerMirrorCancellable = nil
return
}
selectedPeerMirrorCancellable = store.$selectedPrivatePeerID
.sink { [weak self] peerID in
guard let self, self.selectedPeer != peerID else { return }
self.selectedPeer = peerID
}
}
#if DEBUG
// MARK: - Derived message state (read-only compat views)
+19 -6
View File
@@ -104,15 +104,11 @@ protocol PrivateMediaDeletionPersisting: AnyObject {
func persistDeletedPrivateMedia(
messageIDs: [String],
payloadRelativePaths: [String: String],
protectedPayloadRelativePaths: Set<String>,
completion: @escaping @MainActor (Bool) -> Void
)
/// Gated unlink for a LEGACY (non-stable-ID) incoming payload whose
/// bubble was explicitly removed. Implementations delete the file only
/// when its path is not pending delivery and not reserved by any receipt
/// or in-flight deletion transaction; otherwise the file stays for
/// bounded quota cleanup.
/// Unlinks a legacy (non-stable-ID) incoming payload whose bubble was
/// explicitly removed when no stable receipt owns the path.
@MainActor
func removeLegacyPrivateMediaPayload(relativePath: String)
}
@@ -232,6 +228,23 @@ extension BitchatMessage {
}
extension Transport {
// Inert defaults for transports that only handle a subset of the mesh
// surface (e.g. NostrTransport for offline private messaging).
func currentPeerSnapshots() -> [TransportPeerSnapshot] { [] }
var myNickname: String { "" }
func setNickname(_ nickname: String) {}
func startServices() {}
func stopServices() {}
func emergencyDisconnectAll() {}
func isPeerConnected(_ peerID: PeerID) -> Bool { false }
func peerNickname(peerID: PeerID) -> String? { nil }
func getPeerNicknames() -> [PeerID: String] { [:] }
func getFingerprint(for peerID: PeerID) -> String? { nil }
func getNoiseSessionState(for peerID: PeerID) -> LazyHandshakeState { .none }
func triggerHandshake(with peerID: PeerID) {}
func sendMessage(_ content: String, mentions: [String]) {}
func sendBroadcastAnnounce() {}
// Reachability implies prompt delivery for transports that hand packets
// straight to the radio; queue-backed transports override this.
func canDeliverPromptly(to peerID: PeerID) -> Bool { isPeerReachable(peerID) }
@@ -9,7 +9,7 @@ import Foundation
/// testable (see `ChatComposerCoordinatorContextTests`) and makes its true
/// dependencies explicit.
@MainActor
protocol ChatComposerContext: AnyObject {
protocol ChatComposerContext: ChatIdentityContext, ChatGeohashIdentityContext {
// MARK: Autocomplete UI state
var autocompleteSuggestions: [String] { get set }
var autocompleteRange: NSRange? { get set }
@@ -24,21 +24,12 @@ protocol ChatComposerContext: AnyObject {
/// Replaces the matched range in `text` with the chosen suggestion.
func applyAutocompleteSuggestion(_ suggestion: String, to text: String, range: NSRange) -> String
// MARK: Identity & channel state
var nickname: String { get }
var myPeerID: PeerID { get }
var activeChannel: ChannelID { get }
// MARK: Peer lookups
/// The transport's own nickname (excluded from autocomplete candidates).
var meshNickname: String { get }
func meshPeerNicknames() -> [PeerID: String]
/// True when this mesh nickname belongs to a blocked peer.
func isMeshNicknameBlocked(_ nickname: String) -> Bool
/// True when this geohash pubkey is blocked for location chats.
func isNostrBlocked(pubkeyHexLowercased: String) -> Bool
// MARK: Geohash identity (shared with the other contexts)
var geoNicknames: [String: String] { get }
func deriveNostrIdentity(forGeohash geohash: String) throws -> NostrIdentity
}
extension ChatViewModel: ChatComposerContext {
@@ -10,22 +10,11 @@ import Foundation
/// testable (see `ChatLifecycleCoordinatorContextTests`) and makes its true
/// dependencies explicit.
@MainActor
protocol ChatLifecycleContext: AnyObject {
protocol ChatLifecycleContext: ChatIdentityContext, ChatDirectMessageStoreContext {
// MARK: Chat & receipt state
/// A single private chat's timeline (store-direct lookup on
/// `ChatViewModel`; no `privateChats` dictionary build).
func privateMessages(for peerID: PeerID) -> [BitchatMessage]
var unreadPrivateMessages: Set<PeerID> { get }
var selectedPrivateChatPeer: PeerID? { get }
/// Appends a private message via the single-writer store intent.
@discardableResult
func appendPrivateMessage(_ message: BitchatMessage, to peerID: PeerID) -> Bool
/// Clears the peer's unread flag (store unread state only).
func markPrivateChatRead(_ peerID: PeerID)
var sentReadReceipts: Set<String> { get }
var nickname: String { get }
var myPeerID: PeerID { get }
var activeChannel: ChannelID { get }
var nostrKeyMapping: [PeerID: String] { get }
/// Records that a read receipt is being sent for `messageID`.
/// Returns `false` when one was already recorded — the caller must skip sending.
@@ -219,7 +219,7 @@ final class ChatLiveVoiceCoordinator {
/// `ioQueue` in production while keeping synchronous unit tests deterministic.
init(
context: any ChatLiveVoiceContext,
fileStore: BLEIncomingFileStore = BLEIncomingFileStore(),
fileStore: BLEIncomingFileStore = .shared,
sweepsOnInit: Bool = true,
asyncStartupSweep: Bool = false,
asyncQuotaEnforcement: Bool = false
@@ -67,13 +67,10 @@ private struct PrivateMediaReconnectRetryCandidate {
/// testable (see `ChatMediaTransferCoordinatorContextTests`) and makes its
/// true dependencies explicit.
@MainActor
protocol ChatMediaTransferContext: AnyObject {
protocol ChatMediaTransferContext: ChatIdentityContext {
// MARK: Composition state
var canSendMediaInCurrentContext: Bool { get }
var selectedPrivateChatPeer: PeerID? { get }
var nickname: String { get }
var myPeerID: PeerID { get }
var activeChannel: ChannelID { get }
func nicknameForPeer(_ peerID: PeerID) -> String
func currentPublicSender() -> (name: String, peerID: PeerID)
@@ -309,44 +306,17 @@ extension ChatViewModel: ChatMediaTransferContext {
return
}
let requestedIDs = Set(messageIDs)
let incomingPathReferences = Array(
conversations.conversationsByID.values
.lazy
.flatMap(\.messages)
.compactMap { message -> (
messageID: String,
path: String
)? in
guard self.isIncomingPrivateMessage(message),
let path = self.incomingMediaRelativePath(
for: message
) else {
return nil
}
return (message.id, path)
}
)
let ownerIDsByPath = Dictionary(
grouping: incomingPathReferences,
by: { $0.path }
).mapValues { Set($0.map(\.messageID)) }
let protectedPayloadRelativePaths = Set(
ownerIDsByPath.compactMap { path, ownerIDs in
ownerIDs.isSubset(of: requestedIDs) ? nil : path
}
)
var payloadRelativePaths: [String: String] = [:]
for reference in incomingPathReferences
where requestedIDs.contains(reference.messageID)
&& ownerIDsByPath[reference.path, default: []]
.isSubset(of: requestedIDs) {
payloadRelativePaths[reference.messageID] = reference.path
for message in conversations.conversationsByID.values.lazy.flatMap(\.messages)
where requestedIDs.contains(message.id)
&& isIncomingPrivateMessage(message) {
if let path = incomingMediaRelativePath(for: message) {
payloadRelativePaths[message.id] = path
}
}
persistence.persistDeletedPrivateMedia(
messageIDs: messageIDs,
payloadRelativePaths: payloadRelativePaths,
protectedPayloadRelativePaths:
protectedPayloadRelativePaths,
completion: completion
)
}
@@ -10,11 +10,8 @@ import Foundation
/// testable (see `ChatOutgoingCoordinatorContextTests`) and makes its true
/// dependencies explicit.
@MainActor
protocol ChatOutgoingContext: AnyObject {
// MARK: Identity & channel state
var nickname: String { get }
var myPeerID: PeerID { get }
var activeChannel: ChannelID { get }
protocol ChatOutgoingContext: ChatIdentityContext {
// MARK: Channel & selection state
var selectedPrivateChatPeer: PeerID? { get }
var isTeleported: Bool { get }
@@ -12,25 +12,14 @@ import Foundation
/// documents the coordinator's real coupling to private-chat state, peer
/// identity, and the routing/ack transports.
@MainActor
protocol ChatPrivateConversationContext: AnyObject {
protocol ChatPrivateConversationContext: ChatIdentityContext, ChatDirectMessageStoreContext {
// MARK: Conversation state
var privateChats: [PeerID: [BitchatMessage]] { get }
/// A single private chat's timeline. Witnessed by the store-direct
/// lookup on `ChatViewModel` (no `privateChats` dictionary build).
func privateMessages(for peerID: PeerID) -> [BitchatMessage]
var sentReadReceipts: Set<String> { get }
var selectedPrivateChatPeer: PeerID? { get }
var nickname: String { get }
var activeChannel: ChannelID { get }
var nostrKeyMapping: [PeerID: String] { get }
// MARK: Conversation store intents
// The sole mutation paths for private message state (single-writer
// `ConversationStore` ops; see docs/CONVERSATION-STORE-DESIGN.md).
/// Appends a private message in timestamp order; returns `false` on
/// duplicate message ID.
@discardableResult
func appendPrivateMessage(_ message: BitchatMessage, to peerID: PeerID) -> Bool
/// Replace-or-append a private message by ID, keeping its position.
func upsertPrivateMessage(_ message: BitchatMessage, in peerID: PeerID)
/// Applies a delivery status by message ID; returns `false` when the
@@ -38,7 +27,6 @@ protocol ChatPrivateConversationContext: AnyObject {
@discardableResult
func setPrivateDeliveryStatus(_ status: DeliveryStatus, forMessageID messageID: String, peerID: PeerID) -> Bool
func markPrivateChatUnread(_ peerID: PeerID)
func markPrivateChatRead(_ peerID: PeerID)
/// Moves all messages from `oldPeerID`'s chat into `newPeerID`'s chat
/// (dedup by ID, order preserved, unread carried, old chat removed).
func migratePrivateChat(from oldPeerID: PeerID, to newPeerID: PeerID)
@@ -60,7 +48,6 @@ protocol ChatPrivateConversationContext: AnyObject {
func handOffSelectedPrivateChat(from oldPeerIDs: [PeerID], to newPeerID: PeerID)
// MARK: Peers & identity
var myPeerID: PeerID { get }
func peerNickname(for peerID: PeerID) -> String?
func isPeerConnected(_ peerID: PeerID) -> Bool
func isPeerReachable(_ peerID: PeerID) -> Bool
@@ -18,12 +18,9 @@ import UIKit
/// conversation stores, geohash participants, and the inbound public message
/// pipeline.
@MainActor
protocol ChatPublicConversationContext: AnyObject {
protocol ChatPublicConversationContext: ChatIdentityContext {
// MARK: Channel state
var activeChannel: ChannelID { get }
var currentGeohash: String? { get }
var nickname: String { get }
var myPeerID: PeerID { get }
// MARK: Public conversation store (single-writer intents)
/// Appends a public message in timestamp order. Returns `false` when a
@@ -0,0 +1,27 @@
import BitFoundation
import Foundation
/// Shared local identity and channel state read by multiple ViewModel coordinators.
@MainActor
protocol ChatIdentityContext: AnyObject {
var nickname: String { get }
var myPeerID: PeerID { get }
var activeChannel: ChannelID { get }
}
/// Shared single-writer direct-conversation store intents.
@MainActor
protocol ChatDirectMessageStoreContext: AnyObject {
func privateMessages(for peerID: PeerID) -> [BitchatMessage]
@discardableResult
func appendPrivateMessage(_ message: BitchatMessage, to peerID: PeerID) -> Bool
func markPrivateChatRead(_ peerID: PeerID)
}
/// Shared geohash/Nostr identity lookup and blocking surface.
@MainActor
protocol ChatGeohashIdentityContext: AnyObject {
var geoNicknames: [String: String] { get }
func deriveNostrIdentity(forGeohash geohash: String) throws -> NostrIdentity
func isNostrBlocked(pubkeyHexLowercased: String) -> Bool
}
@@ -312,6 +312,19 @@ private extension ChatViewModelBootstrapper {
)
}
private static func publishToGeoRelays(event: NostrEvent, geohash: String, logPrefix: String) {
let relays = GeoRelayDirectory.shared.closestRelays(
toGeohash: geohash,
count: TransportConfig.nostrGeoRelayCount
)
// Refuse rather than publish to default relays no geo subscriber reads.
guard !relays.isEmpty else {
SecureLogger.warning("\(logPrefix): no geo relays for #\(geohash); not publishing", category: .session)
return
}
NostrRelayManager.shared.sendEvent(event, to: relays)
}
/// Wires the gateway-mode policy layer (`GatewayService`) to the mesh
/// transport, the relay manager, and the inbound Nostr pipeline. All
/// dependencies are closures so the service stays unit-testable with
@@ -323,19 +336,7 @@ private extension ChatViewModelBootstrapper {
let gateway = GatewayService.shared
gateway.publishToRelays = { event, geohash in
let relays = GeoRelayDirectory.shared.closestRelays(
toGeohash: geohash,
count: TransportConfig.nostrGeoRelayCount
)
// Symmetric with the local send path (GeohashSubscriptionManager
// .sendGeohash): with no known geo relay, refuse rather than
// publish to default relays no geo subscriber reads — that would
// be silent dead traffic, not delivery.
guard !relays.isEmpty else {
SecureLogger.warning("🌐 Gateway: no geo relays for #\(geohash); not publishing carried event", category: .session)
return
}
NostrRelayManager.shared.sendEvent(event, to: relays)
Self.publishToGeoRelays(event: event, geohash: geohash, logPrefix: "🌐 Gateway")
}
gateway.broadcastToMesh = { [weak bleService] payload in
bleService?.broadcastNostrCarrier(payload)
@@ -403,15 +404,7 @@ private extension ChatViewModelBootstrapper {
let idBridge = viewModel.idBridge
bridge.publishToRelays = { event, cell in
let relays = GeoRelayDirectory.shared.closestRelays(
toGeohash: cell,
count: TransportConfig.nostrGeoRelayCount
)
guard !relays.isEmpty else {
SecureLogger.warning("🌉 Bridge: no geo relays for cell \(cell); not publishing", category: .session)
return
}
NostrRelayManager.shared.sendEvent(event, to: relays)
Self.publishToGeoRelays(event: event, geohash: cell, logPrefix: "🌉 Bridge")
}
bridge.openSubscription = { cells in
guard let cell = cells.first else { return }
+3 -5
View File
@@ -1303,7 +1303,7 @@ struct ChatViewModelPrivateMediaDeletionTests {
}
@Test @MainActor
func stableDeleteProtectsPathSharedWithLegacyBubble() {
func stableDeleteRefusalKeepsBubblesAndSurfacesSystemMessage() {
let (viewModel, transport) = makeTestableViewModel()
transport.persistDeletedPrivateMediaResult = false
let peerID = PeerID(str: String(repeating: "6", count: 64))
@@ -1332,11 +1332,9 @@ struct ChatViewModelPrivateMediaDeletionTests {
#expect(
transport.deletedPrivateMediaMessageIDBatches == [[stableID]]
)
#expect(transport.deletedPrivateMediaRelativePaths == [[:]])
#expect(
transport.protectedPrivateMediaRelativePaths == [[
"images/incoming/\(filename)"
]]
transport.deletedPrivateMediaRelativePaths
== [[stableID: "images/incoming/\(filename)"]]
)
let messages = viewModel.privateChats[peerID] ?? []
#expect(messages.prefix(2).map(\.id) == [stableID, legacyID])
@@ -1544,6 +1544,7 @@ struct PrivateMediaEndToEndTests {
guard let url = item as? URL,
!url.pathComponents.contains(".private-media-receipts"),
url.lastPathComponent != ".private-media-receipts.json",
url.lastPathComponent != BLEPrivateMediaReceiptStore.ledgerFileName,
(try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true else {
return nil
}
-6
View File
@@ -44,7 +44,6 @@ final class MockTransport: Transport, PrivateMediaDeletionPersisting,
private(set) var deletedPrivateMediaRelativePaths: [
[String: String]
] = []
private(set) var protectedPrivateMediaRelativePaths: [Set<String>] = []
private(set) var sentVerifyChallenges: [(peerID: PeerID, noiseKeyHex: String, nonceA: Data)] = []
private(set) var sentVerifyResponses: [(peerID: PeerID, noiseKeyHex: String, nonceA: Data)] = []
private(set) var sentCourierMessages: [(content: String, messageID: String, recipientNoiseKey: Data, couriers: [PeerID])] = []
@@ -252,14 +251,10 @@ final class MockTransport: Transport, PrivateMediaDeletionPersisting,
func persistDeletedPrivateMedia(
messageIDs: [String],
payloadRelativePaths: [String: String],
protectedPayloadRelativePaths: Set<String>,
completion: @escaping @MainActor (Bool) -> Void
) {
deletedPrivateMediaMessageIDBatches.append(messageIDs)
deletedPrivateMediaRelativePaths.append(payloadRelativePaths)
protectedPrivateMediaRelativePaths.append(
protectedPayloadRelativePaths
)
if deferDeletedPrivateMediaPersistence {
pendingDeletedPrivateMediaCompletions.append(completion)
} else {
@@ -381,7 +376,6 @@ final class MockTransport: Transport, PrivateMediaDeletionPersisting,
cancelledTransfers.removeAll()
deletedPrivateMediaMessageIDBatches.removeAll()
deletedPrivateMediaRelativePaths.removeAll()
protectedPrivateMediaRelativePaths.removeAll()
sentVerifyChallenges.removeAll()
sentVerifyResponses.removeAll()
startServicesCallCount = 0
+7 -7
View File
@@ -669,7 +669,7 @@ struct NoiseCoverageTests {
try establishManagerSessions(aliceManager: aliceManager, bobManager: bobManager)
let establishedSession = try #require(
aliceManager.getSession(for: alicePeerID) as? SecureNoiseSession
aliceManager.getSession(for: alicePeerID)
)
establishedSession.setMessageCountForTesting(
UInt64(Double(NoiseSecurityConstants.maxMessagesPerSession) * 0.9)
@@ -810,13 +810,13 @@ struct NoiseCoverageTests {
@Test("Secure noise sessions enforce limits and renegotiation thresholds")
func secureNoiseSessionsEnforceLimitsAndThresholds() throws {
let initiator = SecureNoiseSession(
let initiator = NoiseSession(
peerID: alicePeerID,
role: .initiator,
keychain: keychain,
localStaticKey: aliceStaticKey
)
let responder = SecureNoiseSession(
let responder = NoiseSession(
peerID: bobPeerID,
role: .responder,
keychain: keychain,
@@ -863,13 +863,13 @@ struct NoiseCoverageTests {
@Test("Secure noise sessions expire based on session start time")
func secureNoiseSessionsExpireBasedOnSessionStartTime() throws {
let initiator = SecureNoiseSession(
let initiator = NoiseSession(
peerID: alicePeerID,
role: .initiator,
keychain: keychain,
localStaticKey: aliceStaticKey
)
let responder = SecureNoiseSession(
let responder = NoiseSession(
peerID: bobPeerID,
role: .responder,
keychain: keychain,
@@ -901,13 +901,13 @@ struct NoiseCoverageTests {
// sessionExpired on every call. needsRenegotiation() has to notice
// the session is old on its own -- it can't rely on the idle check,
// because there is no idle time to find.
let session = SecureNoiseSession(
let session = NoiseSession(
peerID: alicePeerID,
role: .initiator,
keychain: keychain,
localStaticKey: aliceStaticKey
)
let responder = SecureNoiseSession(
let responder = NoiseSession(
peerID: bobPeerID,
role: .responder,
keychain: keychain,
+11 -7
View File
@@ -186,14 +186,18 @@ struct NoiseProtocolTests {
@Test func largeMessageEncryption() throws {
try performHandshake(initiator: aliceSession, responder: bobSession)
// Create a large message
let largeMessage = TestHelpers.generateRandomData(length: 100_000)
// Encrypt and decrypt
let ciphertext = try aliceSession.encrypt(largeMessage)
// Ordinary Noise payloads are capped at NoiseSecurityConstants.maxMessageSize.
let maxOrdinaryMessage = TestHelpers.generateRandomData(length: NoiseSecurityConstants.maxMessageSize)
let ciphertext = try aliceSession.encrypt(maxOrdinaryMessage)
let decrypted = try bobSession.decrypt(ciphertext)
#expect(decrypted == largeMessage)
#expect(decrypted == maxOrdinaryMessage)
// Private-file typed payloads may exceed the ordinary cap up to the framed-file limit.
var largePrivateFile = Data([NoisePayloadType.privateFile.rawValue])
largePrivateFile.append(TestHelpers.generateRandomData(length: 100_000))
let fileCiphertext = try aliceSession.encrypt(largePrivateFile)
let fileDecrypted = try bobSession.decrypt(fileCiphertext)
#expect(fileDecrypted == largePrivateFile)
}
@Test func encryptionBeforeHandshake() {
@@ -14,18 +14,18 @@ import BitFoundation
struct SecureNoiseSessionConcurrencyTests {
private func makeEstablishedPair() throws -> (initiator: SecureNoiseSession, responder: SecureNoiseSession) {
private func makeEstablishedPair() throws -> (initiator: NoiseSession, responder: NoiseSession) {
let aliceKey = Curve25519.KeyAgreement.PrivateKey()
let bobKey = Curve25519.KeyAgreement.PrivateKey()
let keychain = MockKeychain()
let alice = SecureNoiseSession(
let alice = NoiseSession(
peerID: PeerID(publicKey: bobKey.publicKey.rawRepresentation),
role: .initiator,
keychain: keychain,
localStaticKey: aliceKey
)
let bob = SecureNoiseSession(
let bob = NoiseSession(
peerID: PeerID(publicKey: aliceKey.publicKey.rawRepresentation),
role: .responder,
keychain: keychain,
@@ -21,7 +21,8 @@ struct BLEFileTransferHandlerTests {
var receiptCommits: [(messageID: String, storedURL: URL)] = []
var receiptCommitSucceeds = true
var removedIncomingFiles: [URL] = []
var finishedIncomingFileDeliveries: [URL] = []
var beganPendingDeliveries: [URL] = []
var finishedPendingDeliveries: [URL] = []
var lastSeenUpdates: [PeerID] = []
var deliveryAcks: [(messageID: String, peerID: PeerID)] = []
var deliveredMessages: [BitchatMessage] = []
@@ -37,85 +38,12 @@ struct BLEFileTransferHandlerTests {
var receiptStateOverride: ((String) -> BLEPrivateMediaReceiptState)?
var receiptCommitOverride: ((String, URL) -> Bool)?
var removeIncomingFileOverride: ((URL) -> Void)?
var finishIncomingFileDeliveryOverride: ((URL) -> Void)?
}
private let localPeerID = PeerID(str: "0102030405060708")
private let remotePeerID = PeerID(str: "1122334455667788")
private let sampleSigningKey = Data(repeating: 0xAB, count: 32)
@Test @MainActor
func deliveryGateFinalizesInitialRejection() {
var completions = 0
var finalizations = 0
TransportEventDeliveryGate.attempt(
shouldDeliver: { false },
deliver: {
Issue.record("delivery sink must not run")
return .accepted
},
completion: { completions += 1 },
finalization: { _ in finalizations += 1 }
)
#expect(completions == 0)
#expect(finalizations == 1)
}
@Test @MainActor
func deliveryGateFinalizesMissingOrRejectingSink() {
var completions = 0
var finalizations = 0
TransportEventDeliveryGate.attempt(
shouldDeliver: { true },
deliver: { .rejected },
completion: { completions += 1 },
finalization: { _ in finalizations += 1 }
)
#expect(completions == 0)
#expect(finalizations == 1)
}
@Test @MainActor
func deliveryGateFinalizesPostInsertionRejection() {
var deliveryChecks = 0
var completions = 0
var finalizations = 0
TransportEventDeliveryGate.attempt(
shouldDeliver: {
deliveryChecks += 1
return deliveryChecks == 1
},
deliver: { .accepted },
completion: { completions += 1 },
finalization: { _ in finalizations += 1 }
)
#expect(deliveryChecks == 2)
#expect(completions == 0)
#expect(finalizations == 1)
}
@Test @MainActor
func deliveryGatePreservesInvokedUnconfirmedOutcomeWithoutAck() {
var completions = 0
var outcomes: [TransportEventDeliveryOutcome] = []
TransportEventDeliveryGate.attempt(
shouldDeliver: { true },
deliver: { .invokedUnconfirmed },
completion: { completions += 1 },
finalization: { outcomes.append($0) }
)
#expect(completions == 0)
#expect(outcomes == [.invokedUnconfirmed])
}
private func makeHandler(recorder: Recorder) -> BLEFileTransferHandler {
let environment = BLEFileTransferHandlerEnvironment(
localPeerID: { [localPeerID] in localPeerID },
@@ -162,9 +90,11 @@ struct BLEFileTransferHandlerTests {
recorder.removedIncomingFiles.append(storedURL)
recorder.removeIncomingFileOverride?(storedURL)
},
finishIncomingFileDelivery: { storedURL in
recorder.finishedIncomingFileDeliveries.append(storedURL)
recorder.finishIncomingFileDeliveryOverride?(storedURL)
beginPendingDelivery: { storedURL in
recorder.beganPendingDeliveries.append(storedURL)
},
finishPendingDelivery: { storedURL in
recorder.finishedPendingDeliveries.append(storedURL)
},
isPrivateMediaSenderBlocked: { peerID in
recorder.blockedPeers.contains(peerID)
@@ -216,6 +146,8 @@ struct BLEFileTransferHandlerTests {
#expect(recorder.saveCalls.first?.defaultPrefix == "file")
#expect(recorder.lastSeenUpdates.isEmpty)
#expect(recorder.deliveredMessages.count == 1)
#expect(recorder.beganPendingDeliveries == [recorder.saveResult])
#expect(recorder.finishedPendingDeliveries == [recorder.saveResult])
let message = recorder.deliveredMessages.first
#expect(message?.sender == "Alice")
#expect(message?.content == "[file] sample.pdf")
@@ -289,6 +221,8 @@ struct BLEFileTransferHandlerTests {
#expect(recorder.signedNameQueries == [remotePeerID])
#expect(recorder.deliveredMessages.count == 1)
#expect(recorder.beganPendingDeliveries == [recorder.saveResult])
#expect(recorder.finishedPendingDeliveries == [recorder.saveResult])
#expect(recorder.deliveredMessages.first?.sender == "Bob")
}
@@ -311,6 +245,8 @@ struct BLEFileTransferHandlerTests {
#expect(recorder.signatureVerifyCount == 1)
#expect(recorder.signedNameQueries.isEmpty)
#expect(recorder.deliveredMessages.count == 1)
#expect(recorder.beganPendingDeliveries == [recorder.saveResult])
#expect(recorder.finishedPendingDeliveries == [recorder.saveResult])
#expect(recorder.deliveredMessages.first?.sender == "Me")
}
@@ -327,6 +263,8 @@ struct BLEFileTransferHandlerTests {
// signature lookup (mirrors BLEPublicMessageHandler).
#expect(recorder.signedNameQueries == [remotePeerID])
#expect(recorder.deliveredMessages.count == 1)
#expect(recorder.beganPendingDeliveries == [recorder.saveResult])
#expect(recorder.finishedPendingDeliveries == [recorder.saveResult])
#expect(recorder.deliveredMessages.first?.sender == "Carol")
}
@@ -418,6 +356,8 @@ struct BLEFileTransferHandlerTests {
#expect(recorder.trackedPackets.isEmpty)
#expect(recorder.lastSeenUpdates == [remotePeerID])
#expect(recorder.deliveredMessages.count == 1)
#expect(recorder.beganPendingDeliveries == [recorder.saveResult])
#expect(recorder.finishedPendingDeliveries == [recorder.saveResult])
#expect(recorder.deliveredMessages.first?.isPrivate == true)
#expect(recorder.deliveredMessages.first?.id.hasPrefix("media-") == false)
// Must be explicit: BitchatMessage defaults private messages to
@@ -451,6 +391,8 @@ struct BLEFileTransferHandlerTests {
#expect(recorder.saveCalls.first?.data == content)
#expect(recorder.lastSeenUpdates == [remotePeerID])
#expect(recorder.deliveredMessages.count == 1)
#expect(recorder.beganPendingDeliveries == [recorder.saveResult])
#expect(recorder.finishedPendingDeliveries == [recorder.saveResult])
#expect(recorder.deliveredMessages.first?.isPrivate == true)
#expect(recorder.deliveredMessages.first?.timestamp == timestamp)
#expect(recorder.deliveredMessages.first?.id == PrivateMediaMessageIdentity.stableID(
@@ -496,9 +438,6 @@ struct BLEFileTransferHandlerTests {
recorder.removeIncomingFileOverride = {
store.removeIncomingFile(at: $0)
}
recorder.finishIncomingFileDeliveryOverride = {
store.finishIncomingFileDelivery(at: $0)
}
let content = TestImageFixtures.makeJPEG()
let fileName =
@@ -523,11 +462,10 @@ struct BLEFileTransferHandlerTests {
))
#expect(recorder.deliveredMessages.isEmpty)
#expect(recorder.deliveryAcks.isEmpty)
#expect(recorder.finishedIncomingFileDeliveries.count == 1)
#expect(store.reservePrivateMediaDeletion(
#expect(store.commitPrivateMediaDeletion(
messageIDs: [stableID],
payloadRelativePaths: [:]
) != nil)
))
}
@Test
@@ -554,6 +492,8 @@ struct BLEFileTransferHandlerTests {
#expect(recorder.receiptCommits.isEmpty)
#expect(recorder.deliveryAcks.isEmpty)
#expect(recorder.deliveredMessages.count == 1)
#expect(recorder.beganPendingDeliveries == [recorder.saveResult])
#expect(recorder.finishedPendingDeliveries == [recorder.saveResult])
#expect(recorder.deliveredMessages.first?.id.hasPrefix("media-") == false)
}
@@ -581,7 +521,6 @@ struct BLEFileTransferHandlerTests {
#expect(recorder.deliveredMessages.isEmpty)
#expect(recorder.removedIncomingFiles.count == 1)
#expect(recorder.removedIncomingFiles.first == recorder.saveResult)
#expect(recorder.finishedIncomingFileDeliveries.isEmpty)
}
@Test
@@ -606,13 +545,10 @@ struct BLEFileTransferHandlerTests {
#expect(handler.handle(packet, from: remotePeerID))
#expect(recorder.deliveredMessages.count == 1)
#expect(recorder.beganPendingDeliveries == [recorder.saveResult])
#expect(recorder.finishedPendingDeliveries == [recorder.saveResult])
#expect(recorder.deliveryAcks.isEmpty)
#expect(recorder.removedIncomingFiles.isEmpty)
#expect(recorder.finishedIncomingFileDeliveries.count == 1)
#expect(
recorder.finishedIncomingFileDeliveries.first
== recorder.saveResult
)
}
@Test
@@ -733,9 +669,6 @@ struct BLEFileTransferHandlerTests {
recorder.removeIncomingFileOverride = {
store.removeIncomingFile(at: $0)
}
recorder.finishIncomingFileDeliveryOverride = {
store.finishIncomingFileDelivery(at: $0)
}
}
let first = Recorder()
@@ -819,6 +752,8 @@ struct BLEFileTransferHandlerTests {
#expect(recorder.saveCalls.count == 2)
#expect(recorder.deliveryAcks.count == 1)
#expect(recorder.deliveredMessages.count == 1)
#expect(recorder.beganPendingDeliveries == [recorder.saveResult])
#expect(recorder.finishedPendingDeliveries == [recorder.saveResult])
}
@Test
@@ -926,6 +861,8 @@ struct BLEFileTransferHandlerTests {
))
#expect(recorder.saveCalls.count == 1)
#expect(recorder.deliveredMessages.count == 1)
#expect(recorder.beganPendingDeliveries == [recorder.saveResult])
#expect(recorder.finishedPendingDeliveries == [recorder.saveResult])
#expect(recorder.deliveryAcks.count == 1)
}
@@ -1113,36 +1050,6 @@ struct BLEFileTransferHandlerTests {
#expect(FileManager.default.fileExists(atPath: victim.path))
}
@Test
func legacyIncomingDeleteLeavesPendingDeliveryPayload() throws {
let base = FileManager.default.temporaryDirectory
.appendingPathComponent(
"legacy-pending-\(UUID().uuidString)",
isDirectory: true
)
defer { try? FileManager.default.removeItem(at: base) }
let store = BLEIncomingFileStore(baseDirectory: base)
// save() marks the stored path pending until delivery finishes; a
// legacy delete naming the same basename must not unlink it.
let stored = try #require(store.save(
data: Data([0xFF, 0xD8, 0xFF, 0xD9]),
preferredName: "pending.jpg",
subdirectory: "images/incoming",
fallbackExtension: "jpg",
defaultPrefix: "img"
))
let relativePath = "images/incoming/\(stored.lastPathComponent)"
#expect(!store.removeLegacyIncomingFile(relativePath: relativePath))
#expect(FileManager.default.fileExists(atPath: stored.path))
// Once the delivery window closes the same unlink is allowed.
store.finishIncomingFileDelivery(at: stored)
#expect(store.removeLegacyIncomingFile(relativePath: relativePath))
#expect(!FileManager.default.fileExists(atPath: stored.path))
}
@Test
func legacyIncomingDeleteLeavesReceiptProtectedPayload() throws {
let base = FileManager.default.temporaryDirectory
@@ -1277,49 +1184,37 @@ struct BLEFileTransferHandlerTests {
}
@Test
func panicWipeInvalidatesPayloadCoordinationReservations() throws {
func panicWipeAllowsFreshUniqueSavesAfterReset() throws {
let base = FileManager.default.temporaryDirectory
.appendingPathComponent(
"panic-payload-coordination-\(UUID().uuidString)",
"panic-unique-saves-\(UUID().uuidString)",
isDirectory: true
)
defer { try? FileManager.default.removeItem(at: base) }
let store = BLEIncomingFileStore(baseDirectory: base)
let pendingName = "pending-before-panic.jpg"
let pendingURL = try #require(store.save(
let preferredName = "image-before-panic.jpg"
let prePanicURL = try #require(store.save(
data: Data("old".utf8),
preferredName: pendingName,
preferredName: preferredName,
subdirectory: "images/incoming",
fallbackExtension: "jpg",
defaultPrefix: "image"
))
let messageID = "media-aabbccddeeff00112233445566778899"
let reservation = try #require(store.reservePrivateMediaDeletion(
messageIDs: [messageID],
payloadRelativePaths: [
messageID: "images/incoming/delete-before-panic.jpg"
]
))
try store.panicWipe()
#expect(!store.commitPrivateMediaDeletion(
reservation: reservation,
messageIDs: [messageID],
payloadRelativePaths: [
messageID: "images/incoming/delete-before-panic.jpg"
],
protectedPayloadRelativePaths: []
))
let postPanicURL = try #require(store.save(
data: Data("new".utf8),
preferredName: pendingName,
preferredName: preferredName,
subdirectory: "images/incoming",
fallbackExtension: "jpg",
defaultPrefix: "image"
))
#expect(pendingURL.lastPathComponent == pendingName)
#expect(postPanicURL.lastPathComponent == pendingName)
#expect(prePanicURL.lastPathComponent.hasSuffix("_\(preferredName)"))
#expect(postPanicURL.lastPathComponent.hasSuffix("_\(preferredName)"))
#expect(prePanicURL != postPanicURL)
#expect(!FileManager.default.fileExists(atPath: prePanicURL.path))
#expect(FileManager.default.fileExists(atPath: postPanicURL.path))
}
@Test
File diff suppressed because it is too large. Load diff
@@ -897,4 +897,36 @@ struct BridgeServiceTests {
#expect(fixture.broadcasts.isEmpty)
}
@Test func resetForPanicClearsNearbyOnlyAndRadioAliases() throws {
let fixture = Fixture(enabled: true)
fixture.service.refreshRendezvous()
fixture.service.nearbyOnly = true
let radioHint = MeshMessageIdentity.stableID(
senderIDHex: "0011223344556677",
timestampMs: 1_700_000_000_000,
content: "bridged message"
)
let event = try makeRemoteEvent(
content: "bridged message",
meshSenderID: "0011223344556677",
meshTimestampMs: 1_700_000_000_000
)
fixture.service.handleRendezvousEvent(event)
#expect(fixture.injected.count == 1)
var removedIDs: [String] = []
fixture.service.removeInjectedInbound = { removedIDs.append($0) }
fixture.service.resetForPanic()
#expect(!fixture.service.isEnabled)
#expect(!fixture.service.nearbyOnly)
// Radio alias table was cleared by panic wipe, so a post-panic radio
// message with the old hint must not try to remove pre-panic rows.
fixture.service.handleAuthenticatedRadioMessage(messageID: radioHint)
#expect(removedIDs.isEmpty)
}
}
@@ -115,6 +115,31 @@ struct MediaRetentionTests {
#expect(BLEIncomingFileStore.defaultMediaRetention == 7 * 24 * 60 * 60)
}
@Test
func quotaEvictionSkipsFilesAwaitingUIDeliveryUntilFinalized() throws {
let root = makeRoot()
defer { try? FileManager.default.removeItem(at: root) }
let store = BLEIncomingFileStore(baseDirectory: root, quotaBytes: 12)
let pending = try #require(store.save(
data: Data(repeating: 0xAA, count: 10),
preferredName: "first.jpg",
subdirectory: "images/incoming",
fallbackExtension: "jpg",
defaultPrefix: "img"
))
store.beginPendingDelivery(at: pending)
// Even under quota pressure from a second arrival, the pending file
// stays protected on disk until UI delivery finishes.
store.enforceQuota(reservingBytes: 10)
#expect(FileManager.default.fileExists(atPath: pending.path))
store.finishPendingDelivery(at: pending)
store.enforceQuota(reservingBytes: 10)
#expect(!FileManager.default.fileExists(atPath: pending.path))
}
#if os(iOS)
/// Media was the one persistence layer that never stated a protection
/// class at its write site, so payloads inherited the container