mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-11-29 08:29:22 +00:00
perf(nostr,tor): eliminate per-frame MainActor hops, coalesce fan-in Schnorr verifies, and offload Tor lifecycle (#1894)
This commit is contained in:
20 files changed
+1060
-360
No files matched your search
@@ -91,29 +91,13 @@ private extension GeoRelayDirectoryDependencies {
|
||||
},
|
||||
makeFetchData: {
|
||||
let session = TorURLSession.shared.session
|
||||
let maximumBytes = validationPolicy.maximumBytes
|
||||
return { request in
|
||||
let (bytes, response) = try await session.bytes(for: request)
|
||||
guard let response = response as? HTTPURLResponse,
|
||||
(200...299).contains(response.statusCode),
|
||||
response.url == request.url else {
|
||||
throw URLError(.badServerResponse)
|
||||
}
|
||||
|
||||
let maximumBytes = validationPolicy.maximumBytes
|
||||
guard response.expectedContentLength <= Int64(maximumBytes) else {
|
||||
throw URLError(.dataLengthExceedsMaximum)
|
||||
}
|
||||
var data = Data()
|
||||
if response.expectedContentLength > 0 {
|
||||
data.reserveCapacity(Int(response.expectedContentLength))
|
||||
}
|
||||
for try await byte in bytes {
|
||||
guard data.count < maximumBytes else {
|
||||
throw URLError(.dataLengthExceedsMaximum)
|
||||
}
|
||||
data.append(byte)
|
||||
}
|
||||
return data
|
||||
try await BoundedHTTPDataReader.fetch(
|
||||
request: request,
|
||||
using: session,
|
||||
maximumBytes: maximumBytes
|
||||
)
|
||||
}
|
||||
},
|
||||
readData: { try? Data(contentsOf: $0) },
|
||||
@@ -521,6 +505,7 @@ final class GeoRelayDirectory {
|
||||
}
|
||||
|
||||
var entriesByHost: [String: Entry] = [:]
|
||||
entriesByHost.reserveCapacity(min(lines.count, policy.maximumEntries))
|
||||
for line in lines.dropFirst() {
|
||||
let parts = line
|
||||
.split(separator: ",", omittingEmptySubsequences: false)
|
||||
@@ -562,33 +547,59 @@ final class GeoRelayDirectory {
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated private static let allowedHostLabelCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz0123456789-")
|
||||
nonisolated private static func isAllowedHostLabelByte(_ byte: UInt8) -> Bool {
|
||||
(byte >= 0x61 && byte <= 0x7A) // a-z
|
||||
|| (byte >= 0x30 && byte <= 0x39) // 0-9
|
||||
|| byte == 0x2D // '-'
|
||||
}
|
||||
|
||||
nonisolated private static func validatedDirectoryAddress(_ rawValue: String) -> String? {
|
||||
let value = rawValue.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !value.isEmpty,
|
||||
value.unicodeScalars.allSatisfy({
|
||||
$0.isASCII && !CharacterSet.controlCharacters.contains($0)
|
||||
}) else {
|
||||
guard !value.isEmpty else { return nil }
|
||||
// Printable ASCII only (0x20...0x7E) — rejects all non-ASCII and control chars.
|
||||
for scalar in value.unicodeScalars {
|
||||
guard scalar.value >= 0x20 && scalar.value < 0x7F else { return nil }
|
||||
}
|
||||
|
||||
var remainder: Substring = value[...]
|
||||
if let schemeRange = remainder.range(of: "://") {
|
||||
let scheme = remainder[..<schemeRange.lowerBound].lowercased()
|
||||
guard scheme == "wss" || scheme == "https" else { return nil }
|
||||
remainder = remainder[schemeRange.upperBound...]
|
||||
}
|
||||
|
||||
// Reject userinfo, query, fragment, whitespace, and non-root paths.
|
||||
if remainder.hasSuffix("/") {
|
||||
remainder = remainder.dropLast()
|
||||
}
|
||||
guard !remainder.isEmpty,
|
||||
!remainder.contains("/"),
|
||||
!remainder.contains("@"),
|
||||
!remainder.contains("?"),
|
||||
!remainder.contains("#"),
|
||||
!remainder.contains(" ") else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let candidate = value.contains("://") ? value : "wss://\(value)"
|
||||
guard let components = URLComponents(string: candidate),
|
||||
let scheme = components.scheme?.lowercased(),
|
||||
scheme == "wss" || scheme == "https",
|
||||
components.user == nil,
|
||||
components.password == nil,
|
||||
components.query == nil,
|
||||
components.fragment == nil,
|
||||
components.path.isEmpty || components.path == "/",
|
||||
let rawHost = components.host else {
|
||||
return nil
|
||||
let hostPart: Substring
|
||||
let port: Int?
|
||||
if let colonIndex = remainder.firstIndex(of: ":") {
|
||||
hostPart = remainder[..<colonIndex]
|
||||
let portPart = remainder[remainder.index(after: colonIndex)...]
|
||||
guard !portPart.isEmpty,
|
||||
portPart.utf8.allSatisfy({ $0 >= 0x30 && $0 <= 0x39 }),
|
||||
let parsedPort = Int(portPart),
|
||||
(1...65_535).contains(parsedPort) else {
|
||||
return nil
|
||||
}
|
||||
port = parsedPort
|
||||
} else {
|
||||
hostPart = remainder
|
||||
port = nil
|
||||
}
|
||||
|
||||
let host = rawHost.lowercased()
|
||||
let host = hostPart.lowercased()
|
||||
guard !host.isEmpty, host.count <= 253,
|
||||
host.unicodeScalars.allSatisfy({ $0.isASCII }),
|
||||
!host.hasSuffix("."),
|
||||
host != "localhost",
|
||||
!host.hasSuffix(".localhost"),
|
||||
@@ -598,21 +609,19 @@ final class GeoRelayDirectory {
|
||||
}
|
||||
|
||||
let labels = host.split(separator: ".", omittingEmptySubsequences: false)
|
||||
let allowed = allowedHostLabelCharacters
|
||||
guard labels.count >= 2,
|
||||
!labels.allSatisfy({ $0.allSatisfy(\.isNumber) }),
|
||||
!labels.allSatisfy({ $0.utf8.allSatisfy { $0 >= 0x30 && $0 <= 0x39 } }),
|
||||
labels.allSatisfy({ label in
|
||||
(1...63).contains(label.count) &&
|
||||
label.first != "-" &&
|
||||
label.last != "-" &&
|
||||
label.unicodeScalars.allSatisfy { allowed.contains($0) }
|
||||
label.utf8.allSatisfy(isAllowedHostLabelByte)
|
||||
}) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
if let port = components.port {
|
||||
guard (1...65_535).contains(port) else { return nil }
|
||||
if port != 443 { return "\(host):\(port)" }
|
||||
if let port, port != 443 {
|
||||
return "\(host):\(port)"
|
||||
}
|
||||
return host
|
||||
}
|
||||
@@ -682,3 +691,144 @@ final class GeoRelayDirectory {
|
||||
var debugObserverCount: Int { cleanupState.observers.count }
|
||||
var debugClosestRelaysCacheCount: Int { closestRelaysCache.count }
|
||||
}
|
||||
|
||||
/// Chunked, strictly byte-bounded HTTP body reader for `GeoRelayDirectory`.
|
||||
/// Replaces byte-by-byte `AsyncBytes` iteration (~50k async suspensions for
|
||||
/// the relay CSV) while still enforcing `maximumBytes` before unbounded memory
|
||||
/// allocation and rejecting HTTP errors or unexpected redirect URLs.
|
||||
private final class BoundedHTTPDataReader: NSObject, URLSessionDataDelegate, @unchecked Sendable {
|
||||
private let expectedURL: URL?
|
||||
private let maximumBytes: Int
|
||||
private let lock = NSLock()
|
||||
private var buffer = Data()
|
||||
private var continuation: CheckedContinuation<Data, Error>?
|
||||
private var settled = false
|
||||
private weak var task: URLSessionDataTask?
|
||||
|
||||
private init(expectedURL: URL?, maximumBytes: Int) {
|
||||
self.expectedURL = expectedURL
|
||||
self.maximumBytes = maximumBytes
|
||||
}
|
||||
|
||||
static func fetch(
|
||||
request: URLRequest,
|
||||
using session: URLSession,
|
||||
maximumBytes: Int
|
||||
) async throws -> Data {
|
||||
let reader = BoundedHTTPDataReader(expectedURL: request.url, maximumBytes: maximumBytes)
|
||||
return try await withTaskCancellationHandler {
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
let dataTask = session.dataTask(with: request)
|
||||
reader.start(task: dataTask, continuation: continuation)
|
||||
}
|
||||
} onCancel: {
|
||||
reader.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
private func start(task: URLSessionDataTask, continuation: CheckedContinuation<Data, Error>) {
|
||||
lock.lock()
|
||||
if settled {
|
||||
lock.unlock()
|
||||
task.cancel()
|
||||
continuation.resume(throwing: CancellationError())
|
||||
return
|
||||
}
|
||||
self.task = task
|
||||
self.continuation = continuation
|
||||
lock.unlock()
|
||||
|
||||
task.delegate = self
|
||||
task.resume()
|
||||
}
|
||||
|
||||
private func cancel() {
|
||||
let activeTask: URLSessionDataTask?
|
||||
let pendingContinuation: CheckedContinuation<Data, Error>?
|
||||
lock.lock()
|
||||
activeTask = task
|
||||
if !settled {
|
||||
settled = true
|
||||
pendingContinuation = continuation
|
||||
continuation = nil
|
||||
} else {
|
||||
pendingContinuation = nil
|
||||
}
|
||||
lock.unlock()
|
||||
|
||||
activeTask?.cancel()
|
||||
pendingContinuation?.resume(throwing: CancellationError())
|
||||
}
|
||||
|
||||
private func finish(with result: Result<Data, Error>) {
|
||||
let pendingContinuation: CheckedContinuation<Data, Error>?
|
||||
lock.lock()
|
||||
guard !settled else {
|
||||
lock.unlock()
|
||||
return
|
||||
}
|
||||
settled = true
|
||||
pendingContinuation = continuation
|
||||
continuation = nil
|
||||
lock.unlock()
|
||||
|
||||
pendingContinuation?.resume(with: result)
|
||||
}
|
||||
|
||||
func urlSession(
|
||||
_ session: URLSession,
|
||||
dataTask: URLSessionDataTask,
|
||||
didReceive response: URLResponse,
|
||||
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void
|
||||
) {
|
||||
_ = session
|
||||
guard let http = response as? HTTPURLResponse,
|
||||
(200...299).contains(http.statusCode),
|
||||
http.url == expectedURL else {
|
||||
completionHandler(.cancel)
|
||||
finish(with: .failure(URLError(.badServerResponse)))
|
||||
return
|
||||
}
|
||||
guard http.expectedContentLength <= Int64(maximumBytes) else {
|
||||
completionHandler(.cancel)
|
||||
finish(with: .failure(URLError(.dataLengthExceedsMaximum)))
|
||||
return
|
||||
}
|
||||
if http.expectedContentLength > 0 {
|
||||
lock.lock()
|
||||
buffer.reserveCapacity(Int(http.expectedContentLength))
|
||||
lock.unlock()
|
||||
}
|
||||
completionHandler(.allow)
|
||||
}
|
||||
|
||||
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
|
||||
_ = session
|
||||
lock.lock()
|
||||
guard !settled else {
|
||||
lock.unlock()
|
||||
return
|
||||
}
|
||||
if buffer.count + data.count > maximumBytes {
|
||||
lock.unlock()
|
||||
dataTask.cancel()
|
||||
finish(with: .failure(URLError(.dataLengthExceedsMaximum)))
|
||||
return
|
||||
}
|
||||
buffer.append(data)
|
||||
lock.unlock()
|
||||
}
|
||||
|
||||
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
|
||||
_ = session
|
||||
_ = task
|
||||
if let error {
|
||||
finish(with: .failure(error))
|
||||
return
|
||||
}
|
||||
lock.lock()
|
||||
let resultData = buffer
|
||||
lock.unlock()
|
||||
finish(with: .success(resultData))
|
||||
}
|
||||
}
|
||||
@@ -97,7 +97,8 @@ struct NostrProtocol {
|
||||
/// Returns the content, sender pubkey, and the actual message timestamp (not the randomized outer timestamp)
|
||||
static func decryptPrivateMessage(
|
||||
giftWrap: NostrEvent,
|
||||
recipientIdentity: NostrIdentity
|
||||
recipientIdentity: NostrIdentity,
|
||||
outerSignatureAlreadyVerified: Bool = false
|
||||
) throws -> (content: String, senderPubkey: String, timestamp: Int) {
|
||||
|
||||
// 0. Validate the untrusted outer envelope before any decryption work.
|
||||
@@ -110,7 +111,7 @@ struct NostrProtocol {
|
||||
}
|
||||
guard giftWrap.kind == EventKind.giftWrap.rawValue,
|
||||
giftWrap.tags == [["p", recipientIdentity.publicKeyHex]],
|
||||
giftWrap.isValidSignature() else {
|
||||
(outerSignatureAlreadyVerified || giftWrap.isValidSignature()) else {
|
||||
SecureLogger.error("❌ Rejecting DM: malformed or misbound outer envelope", category: .session)
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
@@ -294,6 +294,8 @@ final class NostrRelayManager: ObservableObject {
|
||||
|
||||
// Bump generation to invalidate scheduled reconnects when we reset/disconnect
|
||||
private var connectionGeneration: Int = 0
|
||||
/// Per-relay cancellation tokens for scheduled idle teardowns of non-default relays.
|
||||
private var idleTeardownTokens: [String: UUID] = [:]
|
||||
|
||||
// Per-relay off-main inbound pipeline: raw socket frames are parsed and
|
||||
// Schnorr-verified in arrival order OFF the main actor (this is the single
|
||||
@@ -393,8 +395,8 @@ final class NostrRelayManager: ObservableObject {
|
||||
/// check-and-RECORD plus handler dispatch. Recording only after
|
||||
/// verification means a forged-signature copy can never poison the
|
||||
/// dedup cache and suppress the genuine event.
|
||||
private func ensureRelayInboundPipeline(for relayUrl: String) {
|
||||
let started = inboundRouter.startPipeline(for: relayUrl) { [weak self] stream in
|
||||
private func ensureRelayInboundPipeline(for relayUrl: String, connectionID: ObjectIdentifier) {
|
||||
let started = inboundRouter.startPipeline(for: relayUrl, connectionID: connectionID) { [weak self] stream in
|
||||
Task.detached(priority: .userInitiated) {
|
||||
for await frame in stream {
|
||||
guard let parsed = ParsedInbound(frame.message) else { continue }
|
||||
@@ -408,7 +410,7 @@ final class NostrRelayManager: ObservableObject {
|
||||
) else {
|
||||
continue
|
||||
}
|
||||
guard event.isValidSignature() else {
|
||||
guard await self.inboundRouter.verifySignatureCoalesced(event) else {
|
||||
SecureLogger.warning(
|
||||
"⚠️ Dropped invalid Nostr event id=\(event.id.prefix(16))… sub=\(subId) relay=\(relayUrl)",
|
||||
category: .session
|
||||
@@ -448,6 +450,7 @@ final class NostrRelayManager: ObservableObject {
|
||||
/// Disconnect from all relays
|
||||
func disconnect() {
|
||||
connectionGeneration &+= 1
|
||||
idleTeardownTokens.removeAll()
|
||||
for (_, task) in connections {
|
||||
task.cancel(with: .goingAway, reason: nil)
|
||||
}
|
||||
@@ -482,6 +485,7 @@ final class NostrRelayManager: ObservableObject {
|
||||
/// can capture pre-wipe Nostr private keys.
|
||||
func resetForPanicWipe() {
|
||||
connectionGeneration &+= 1
|
||||
idleTeardownTokens.removeAll()
|
||||
for (_, task) in connections {
|
||||
task.cancel(with: .goingAway, reason: nil)
|
||||
}
|
||||
@@ -538,9 +542,12 @@ final class NostrRelayManager: ObservableObject {
|
||||
let targets = allowedRelayList(from: relayUrls)
|
||||
guard !targets.isEmpty else { return }
|
||||
var existing = Set(relays.map { $0.url })
|
||||
for url in targets where !existing.contains(url) {
|
||||
relays.append(Relay(url: url))
|
||||
existing.insert(url)
|
||||
for url in targets {
|
||||
idleTeardownTokens.removeValue(forKey: url)
|
||||
if !existing.contains(url) {
|
||||
relays.append(Relay(url: url))
|
||||
existing.insert(url)
|
||||
}
|
||||
}
|
||||
connectToRelays(targets)
|
||||
}
|
||||
@@ -851,6 +858,7 @@ final class NostrRelayManager: ObservableObject {
|
||||
private func dropRelays(_ urls: Set<String>) {
|
||||
guard !urls.isEmpty else { return }
|
||||
for url in urls {
|
||||
idleTeardownTokens.removeValue(forKey: url)
|
||||
if let connection = connections[url] {
|
||||
connection.cancel(with: .goingAway, reason: nil)
|
||||
}
|
||||
@@ -900,8 +908,11 @@ final class NostrRelayManager: ObservableObject {
|
||||
subscriptionRequestState.removeValue(forKey: id)
|
||||
pendingEOSECallbacks.removeValue(forKey: id)
|
||||
eoseTrackers.removeValue(forKey: id)
|
||||
var affectedRelays = Set<String>()
|
||||
for url in Array(pendingSubscriptions.keys) {
|
||||
pendingSubscriptions[url]?.removeValue(forKey: id)
|
||||
if pendingSubscriptions[url]?.removeValue(forKey: id) != nil {
|
||||
affectedRelays.insert(url)
|
||||
}
|
||||
}
|
||||
|
||||
let req = NostrRequest.close(id: id)
|
||||
@@ -914,11 +925,59 @@ final class NostrRelayManager: ObservableObject {
|
||||
for (relayUrl, connection) in connections {
|
||||
if subscriptions[relayUrl]?.contains(id) == true {
|
||||
subscriptions[relayUrl]?.remove(id)
|
||||
affectedRelays.insert(relayUrl)
|
||||
connection.send(.string(messageString)) { _ in
|
||||
// Local state is cleared before sending so callers can re-subscribe immediately.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reclaim idle non-default (geohash/notes) relay sockets after a short
|
||||
// grace window so switching channels does not accumulate dead sockets.
|
||||
for relayUrl in affectedRelays {
|
||||
scheduleIdleTeardownIfUnused(for: relayUrl)
|
||||
}
|
||||
}
|
||||
|
||||
private func hasPendingMessages(for relayUrl: String) -> Bool {
|
||||
messageQueueLock.lock()
|
||||
defer { messageQueueLock.unlock() }
|
||||
return messageQueue.contains { $0.pendingRelays.contains(relayUrl) }
|
||||
}
|
||||
|
||||
private func isRelayIdle(_ relayUrl: String) -> Bool {
|
||||
let hasActiveSubs = !(subscriptions[relayUrl]?.isEmpty ?? true)
|
||||
let hasPendingSubs = !(pendingSubscriptions[relayUrl]?.isEmpty ?? true)
|
||||
let hasConfirmedSends = confirmedSends.values.contains { $0.awaitingRelays.contains(relayUrl) }
|
||||
return !hasActiveSubs && !hasPendingSubs && !hasConfirmedSends && !hasPendingMessages(for: relayUrl)
|
||||
}
|
||||
|
||||
private func scheduleIdleTeardownIfUnused(for relayUrl: String) {
|
||||
guard !defaultRelaySet.contains(relayUrl),
|
||||
connections[relayUrl] != nil,
|
||||
isRelayIdle(relayUrl) else {
|
||||
return
|
||||
}
|
||||
let token = UUID()
|
||||
idleTeardownTokens[relayUrl] = token
|
||||
let generation = connectionGeneration
|
||||
dependencies.scheduleAfter(TransportConfig.nostrIdleRelayTeardownSeconds) { [weak self] in
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self,
|
||||
self.connectionGeneration == generation,
|
||||
self.idleTeardownTokens[relayUrl] == token else {
|
||||
return
|
||||
}
|
||||
self.idleTeardownTokens.removeValue(forKey: relayUrl)
|
||||
guard !self.defaultRelaySet.contains(relayUrl),
|
||||
self.connections[relayUrl] != nil,
|
||||
self.isRelayIdle(relayUrl) else {
|
||||
return
|
||||
}
|
||||
SecureLogger.debug("🧹 Closing idle non-default Nostr relay: \(relayUrl)", category: .session)
|
||||
self.dropRelays([relayUrl])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private Methods
|
||||
@@ -1196,14 +1255,16 @@ final class NostrRelayManager: ObservableObject {
|
||||
let task = session.webSocketTask(with: url)
|
||||
|
||||
connections[urlString] = task
|
||||
idleTeardownTokens.removeValue(forKey: urlString)
|
||||
task.resume()
|
||||
|
||||
// Bring up this relay's own serial verify pipeline before arming the
|
||||
// socket, so inbound frames have somewhere to land.
|
||||
ensureRelayInboundPipeline(for: urlString)
|
||||
let connectionID = ObjectIdentifier(task)
|
||||
ensureRelayInboundPipeline(for: urlString, connectionID: connectionID)
|
||||
|
||||
// Start receiving messages
|
||||
receiveMessage(from: task, relayUrl: urlString)
|
||||
// Start receiving messages (re-arms directly off-main via InboundFrameRouter)
|
||||
receiveMessage(from: task, relayUrl: urlString, connectionID: connectionID)
|
||||
|
||||
// Send initial ping to verify connection
|
||||
task.sendPing { [weak self] error in
|
||||
@@ -1270,28 +1331,25 @@ final class NostrRelayManager: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
private func receiveMessage(from task: NostrRelayConnectionProtocol, relayUrl: String) {
|
||||
nonisolated private func receiveMessage(
|
||||
from task: NostrRelayConnectionProtocol,
|
||||
relayUrl: String,
|
||||
connectionID: ObjectIdentifier
|
||||
) {
|
||||
task.receive { [weak self] result in
|
||||
guard let self = self else { return }
|
||||
|
||||
switch result {
|
||||
case .success(let message):
|
||||
// Hand the raw frame to this relay's serial inbound pipeline:
|
||||
// parsing and signature verification run off-main, in arrival
|
||||
// order, independently of every other relay's pipeline. Routing
|
||||
// through the lock-guarded router keeps this off the main actor
|
||||
// (no per-frame main hop).
|
||||
self.inboundRouter.yield(InboundFrame(message: message), to: relayUrl)
|
||||
|
||||
|
||||
// Continue receiving
|
||||
Task { @MainActor in
|
||||
guard self.connections[relayUrl] === task else { return }
|
||||
self.receiveMessage(from: task, relayUrl: relayUrl)
|
||||
// Hand the raw frame to this relay's serial inbound pipeline and
|
||||
// re-arm directly off-main when this socket is still active —
|
||||
// zero main-actor hop per WebSocket frame.
|
||||
if self.inboundRouter.yield(InboundFrame(message: message), to: relayUrl, from: connectionID) {
|
||||
self.receiveMessage(from: task, relayUrl: relayUrl, connectionID: connectionID)
|
||||
}
|
||||
|
||||
case .failure(let error):
|
||||
DispatchQueue.main.async {
|
||||
Task { @MainActor in
|
||||
self.handleDisconnection(relayUrl: relayUrl, error: error, connection: task)
|
||||
}
|
||||
}
|
||||
@@ -1511,6 +1569,7 @@ final class NostrRelayManager: ObservableObject {
|
||||
) {
|
||||
if let connection, connections[relayUrl] !== connection { return }
|
||||
connections.removeValue(forKey: relayUrl)
|
||||
idleTeardownTokens.removeValue(forKey: relayUrl)
|
||||
teardownRelayInboundPipeline(for: relayUrl)
|
||||
subscriptions.removeValue(forKey: relayUrl)
|
||||
let awaitingConfirmation = confirmedSends.compactMap { eventID, state in
|
||||
@@ -1715,9 +1774,54 @@ private struct InboundFrame: Sendable {
|
||||
/// 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
|
||||
@@ -1727,10 +1831,12 @@ private final class InboundFrameRouter: @unchecked Sendable {
|
||||
/// 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)
|
||||
@@ -1740,20 +1846,66 @@ private final class InboundFrameRouter: @unchecked Sendable {
|
||||
return true
|
||||
}
|
||||
|
||||
/// Route a frame to a relay's stream. No-op if the relay has no live
|
||||
/// pipeline (socket already torn down) — the frame is simply dropped, which
|
||||
/// is safe for best-effort Nostr inbound.
|
||||
func yield(_ frame: InboundFrame, to relayUrl: String) {
|
||||
/// 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()
|
||||
let continuation = continuations[relayUrl]
|
||||
guard activeConnections[relayUrl] == connectionID,
|
||||
let continuation = continuations[relayUrl] else {
|
||||
lock.unlock()
|
||||
return false
|
||||
}
|
||||
lock.unlock()
|
||||
continuation?.yield(frame)
|
||||
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()
|
||||
@@ -1763,6 +1915,7 @@ private final class InboundFrameRouter: @unchecked Sendable {
|
||||
func finishAll() {
|
||||
lock.lock()
|
||||
let allContinuations = continuations
|
||||
activeConnections.removeAll()
|
||||
continuations.removeAll()
|
||||
tasks.removeAll()
|
||||
lock.unlock()
|
||||
|
||||
@@ -29,14 +29,18 @@ final class FavoritesPersistenceService: ObservableObject {
|
||||
private static let keychainService = "chat.bitchat.favorites"
|
||||
private let keychain: KeychainManagerProtocol
|
||||
|
||||
@Published private(set) var favorites: [Data: FavoriteRelationship] = [:] // Noise pubkey -> relationship
|
||||
@Published private(set) var favorites: [Data: FavoriteRelationship] = [:] { // Noise pubkey -> relationship
|
||||
didSet { rebuildNostrKeyIndex() }
|
||||
}
|
||||
@Published private(set) var mutualFavorites: Set<Data> = []
|
||||
private var noiseKeyByNostrKey: [String: Data] = [:] // npub and lowercase hex -> Noise pubkey
|
||||
|
||||
static let shared = FavoritesPersistenceService()
|
||||
|
||||
init(keychain: KeychainManagerProtocol = KeychainManager.makeDefault()) {
|
||||
self.keychain = keychain
|
||||
loadFavorites()
|
||||
rebuildNostrKeyIndex()
|
||||
|
||||
// Update mutual favorites when favorites change
|
||||
$favorites
|
||||
@@ -45,6 +49,29 @@ final class FavoritesPersistenceService: ObservableObject {
|
||||
}
|
||||
.assign(to: &$mutualFavorites)
|
||||
}
|
||||
|
||||
/// O(1) reverse lookup from a Nostr pubkey (either `npub1...` or 64-char hex)
|
||||
/// to the peer's Noise static public key.
|
||||
func noisePublicKey(forNostrPubkey nostrPubkey: String) -> Data? {
|
||||
noiseKeyByNostrKey[nostrPubkey] ?? noiseKeyByNostrKey[nostrPubkey.lowercased()]
|
||||
}
|
||||
|
||||
private func rebuildNostrKeyIndex() {
|
||||
var index: [String: Data] = [:]
|
||||
index.reserveCapacity(favorites.count * 2)
|
||||
for (noiseKey, relationship) in favorites {
|
||||
guard let storedKey = relationship.peerNostrPublicKey, !storedKey.isEmpty else { continue }
|
||||
index[storedKey] = noiseKey
|
||||
if storedKey.hasPrefix("npub"),
|
||||
let (hrp, data) = try? Bech32.decode(storedKey),
|
||||
hrp == "npub" {
|
||||
index[data.hexEncodedString().lowercased()] = noiseKey
|
||||
} else {
|
||||
index[storedKey.lowercased()] = noiseKey
|
||||
}
|
||||
}
|
||||
noiseKeyByNostrKey = index
|
||||
}
|
||||
|
||||
/// Add or update a favorite
|
||||
func addFavorite(
|
||||
|
||||
@@ -463,7 +463,7 @@ final class BridgeService: ObservableObject {
|
||||
/// Entry point for every event the rendezvous subscription delivers.
|
||||
/// Handles presence accounting, timeline injection, and — when acting as
|
||||
/// the island's gateway — downlink rebroadcast.
|
||||
func handleRendezvousEvent(_ event: NostrEvent) {
|
||||
func handleRendezvousEvent(_ event: NostrEvent, signatureAlreadyVerified: Bool = false) {
|
||||
guard isEnabled else { return }
|
||||
// The subscription spans our cell + neighbors; trust only the
|
||||
// event's own signed `r` tag, and only within that ring.
|
||||
@@ -483,7 +483,7 @@ final class BridgeService: ObservableObject {
|
||||
publishedEventIDs.insert(event.id) // never downlink it either
|
||||
return
|
||||
}
|
||||
guard allowSignatureVerificationAttempt(), verifyEventSignature(event) else { return }
|
||||
guard signatureAlreadyVerified || (allowSignatureVerificationAttempt() && verifyEventSignature(event)) else { return }
|
||||
guard receivedEventIDs.insert(event.id), allowInboundEvent(from: event.pubkey) else { return }
|
||||
guard let kind = classify(event, cell: cell) else { return }
|
||||
|
||||
|
||||
@@ -306,7 +306,7 @@ final class GatewayService: ObservableObject {
|
||||
/// Called for every event the gateway's own geohash-channel subscription
|
||||
/// delivers. Wraps it in a `fromGateway` carrier and broadcasts it on
|
||||
/// the mesh, within the airtime budget.
|
||||
func rebroadcastRelayEvent(_ event: NostrEvent, geohash: String) {
|
||||
func rebroadcastRelayEvent(_ event: NostrEvent, geohash: String, signatureAlreadyVerified: Bool = false) {
|
||||
guard isEnabled, broadcastToMesh != nil else { return }
|
||||
guard event.kind == NostrProtocol.EventKind.ephemeralEvent.rawValue else { return }
|
||||
// Freshness + geohash gate BEFORE spending any budget. A channel
|
||||
@@ -335,8 +335,9 @@ final class GatewayService: ObservableObject {
|
||||
!pendingDownlinks.contains(where: { $0.event.id == event.id }) else {
|
||||
return
|
||||
}
|
||||
// Verify before spending BLE airtime; receivers verify again.
|
||||
guard event.isValidSignature() 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 {
|
||||
@@ -476,9 +477,10 @@ final class GatewayService: ObservableObject {
|
||||
abs(now().timeIntervalSince1970 - TimeInterval(event.created_at)) <= Limits.maxEventAgeSeconds
|
||||
}
|
||||
|
||||
private static let validGeohashCharacters: Set<Character> = Set("0123456789bcdefghjkmnpqrstuvwxyz")
|
||||
|
||||
static func isValidGeohash(_ geohash: String) -> Bool {
|
||||
let allowed = Set("0123456789bcdefghjkmnpqrstuvwxyz")
|
||||
return (1...NostrCarrierPacket.maxGeohashLength).contains(geohash.count)
|
||||
&& geohash.allSatisfy { allowed.contains($0) }
|
||||
(1...NostrCarrierPacket.maxGeohashLength).contains(geohash.count)
|
||||
&& geohash.allSatisfy { validGeohashCharacters.contains($0) }
|
||||
}
|
||||
}
|
||||
@@ -62,12 +62,15 @@ final class GeohashChatActivityTracker: ObservableObject {
|
||||
timestamp: Date
|
||||
) {
|
||||
let gh = geohash.lowercased()
|
||||
let clamped = min(timestamp, now())
|
||||
guard now().timeIntervalSince(clamped) < window else { return }
|
||||
let currentNow = now()
|
||||
let clamped = min(timestamp, currentNow)
|
||||
let cutoff = currentNow.addingTimeInterval(-window)
|
||||
guard currentNow.timeIntervalSince(clamped) < window else { return }
|
||||
|
||||
var times = messageTimes[gh] ?? []
|
||||
times.append(clamped)
|
||||
messageTimes[gh] = prune(times)
|
||||
times.removeAll { $0 < cutoff }
|
||||
messageTimes[gh] = times
|
||||
|
||||
if let existing = lastMessages[gh], existing.timestamp > clamped {
|
||||
// Keep the newer preview.
|
||||
@@ -81,14 +84,16 @@ final class GeohashChatActivityTracker: ObservableObject {
|
||||
// one entry per distinct geohash ever observed. Sweep other geohashes
|
||||
// here so activity that has fully aged out gets evicted instead of
|
||||
// sitting in memory for the rest of the process's lifetime.
|
||||
pruneStaleGeohashes(except: gh)
|
||||
pruneStaleGeohashes(except: gh, cutoff: cutoff)
|
||||
|
||||
objectWillChange.send()
|
||||
}
|
||||
|
||||
/// Messages seen in the window for one geohash.
|
||||
func messageCount(for geohash: String) -> Int {
|
||||
prune(messageTimes[geohash.lowercased()] ?? []).count
|
||||
guard let times = messageTimes[geohash.lowercased()], !times.isEmpty else { return 0 }
|
||||
let cutoff = now().addingTimeInterval(-window)
|
||||
return times.reduce(0) { $1 >= cutoff ? $0 + 1 : $0 }
|
||||
}
|
||||
|
||||
func lastMessage(for geohash: String) -> GeohashChatPreview? {
|
||||
@@ -124,17 +129,23 @@ final class GeohashChatActivityTracker: ObservableObject {
|
||||
objectWillChange.send()
|
||||
}
|
||||
|
||||
private func prune(_ times: [Date]) -> [Date] {
|
||||
let cutoff = now().addingTimeInterval(-window)
|
||||
return times.filter { $0 >= cutoff }
|
||||
}
|
||||
|
||||
/// Drops any tracked geohash (other than `keep`) whose messages have all
|
||||
/// aged out of the window, so the maps stay bounded to recently-active
|
||||
/// geohashes instead of growing for the life of the process.
|
||||
private func pruneStaleGeohashes(except keep: String) {
|
||||
for gh in Array(messageTimes.keys) where gh != keep {
|
||||
guard prune(messageTimes[gh] ?? []).isEmpty else { continue }
|
||||
private func pruneStaleGeohashes(except keep: String, cutoff: Date) {
|
||||
var stale: [String] = []
|
||||
for (gh, times) in messageTimes where gh != keep {
|
||||
// `lastMessages[gh]` tracks the newest timestamp recorded for `gh`,
|
||||
// so checking it avoids allocating a filtered `[Date]` per geohash.
|
||||
if let newest = lastMessages[gh]?.timestamp {
|
||||
if newest < cutoff {
|
||||
stale.append(gh)
|
||||
}
|
||||
} else if !times.contains(where: { $0 >= cutoff }) {
|
||||
stale.append(gh)
|
||||
}
|
||||
}
|
||||
for gh in stale {
|
||||
messageTimes.removeValue(forKey: gh)
|
||||
lastMessages.removeValue(forKey: gh)
|
||||
}
|
||||
|
||||
@@ -112,10 +112,15 @@ final class GeohashParticipantTracker: ObservableObject {
|
||||
let wasActive = previous.map { $0 >= cutoff } ?? false
|
||||
guard !wasActive else { return true }
|
||||
// Someone newly counts as present here: participant counts for
|
||||
// this geohash changed (sampled channels included).
|
||||
objectWillChange.send()
|
||||
// this geohash changed (sampled channels included). When this is the
|
||||
// active geohash, `refresh()` publishes `visiblePeople` (which already
|
||||
// emits `objectWillChange`), avoiding a double invalidation per join.
|
||||
if activeGeohash == geohash {
|
||||
refresh()
|
||||
if !refresh() {
|
||||
objectWillChange.send()
|
||||
}
|
||||
} else {
|
||||
objectWillChange.send()
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -176,11 +181,14 @@ final class GeohashParticipantTracker: ObservableObject {
|
||||
/// Refresh the visible people list. Publishes only when what the roster
|
||||
/// shows changed — who is present or how they're named — so subscribers
|
||||
/// (the people sheet, the bootstrapper's prune) don't rebuild on
|
||||
/// activity that only moved timestamps.
|
||||
func refresh() {
|
||||
/// activity that only moved timestamps. Returns whether `visiblePeople`
|
||||
/// was published.
|
||||
@discardableResult
|
||||
func refresh() -> Bool {
|
||||
let people = getVisiblePeople()
|
||||
guard Self.rosterKey(people) != Self.rosterKey(visiblePeople) else { return }
|
||||
guard Self.rosterKey(people) != Self.rosterKey(visiblePeople) else { return false }
|
||||
publishVisiblePeople(people)
|
||||
return true
|
||||
}
|
||||
|
||||
private static func rosterKey(_ people: [GeoPerson]) -> [String: String] {
|
||||
|
||||
@@ -265,31 +265,59 @@ final class LocationNotesManager: ObservableObject {
|
||||
dependencies.subscribe(filter, subID, relays, { [weak self] event in
|
||||
guard let self = self else { return }
|
||||
guard event.kind == NostrProtocol.EventKind.textNote.rawValue else { return }
|
||||
// Ensure matching tag - accept any of our 9 geohashes
|
||||
guard let matchedGeohash = event.tags.first(where: { tag in
|
||||
tag.count >= 2 && tag[0].lowercased() == "g" && validGeohashes.contains(tag[1].lowercased())
|
||||
})?[1].lowercased() else { return }
|
||||
guard !self.noteIDs.contains(event.id) else { return }
|
||||
|
||||
// Single pass over tags: match any of our 9 cells + extract nick/expiration/urgent.
|
||||
var matchedGeohash: String?
|
||||
var nick: String?
|
||||
var expiresAt: Date?
|
||||
var urgent = false
|
||||
for tag in event.tags where tag.count >= 2 {
|
||||
let key = tag[0].lowercased()
|
||||
switch key {
|
||||
case "g":
|
||||
if matchedGeohash == nil {
|
||||
let candidate = tag[1].lowercased()
|
||||
if validGeohashes.contains(candidate) {
|
||||
matchedGeohash = candidate
|
||||
}
|
||||
}
|
||||
case "n":
|
||||
if nick == nil {
|
||||
nick = tag[1]
|
||||
}
|
||||
case "expiration":
|
||||
if expiresAt == nil, let seconds = TimeInterval(tag[1]) {
|
||||
expiresAt = Date(timeIntervalSince1970: seconds)
|
||||
}
|
||||
case "t":
|
||||
if !urgent && tag[1].lowercased() == "urgent" {
|
||||
urgent = true
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
guard let matchedGeohash else { return }
|
||||
// NIP-40: relays are not required to enforce expiration — drop
|
||||
// expired notes client-side so 24h dead drops actually vanish.
|
||||
let expiresAt = Self.expirationDate(of: event)
|
||||
if let expiresAt, expiresAt <= self.dependencies.now() { return }
|
||||
self.noteIDs.insert(event.id)
|
||||
let nick = event.tags.first(where: { $0.first?.lowercased() == "n" && $0.count >= 2 })?.dropFirst().first
|
||||
let now = self.dependencies.now()
|
||||
if let expiresAt, expiresAt <= now { return }
|
||||
self.recordNoteID(event.id)
|
||||
// created_at is author-chosen; clamp so a future-dated note can't
|
||||
// hold the top of the newest-first list past the memory cap. The
|
||||
// bound is the board's clock-skew allowance: a bridged copy of an
|
||||
// accepted board post must keep its timestamp, or
|
||||
// UnifiedNotices.merge no longer recognizes it as the same notice.
|
||||
let latestAccepted = self.dependencies.now()
|
||||
let latestAccepted = now
|
||||
.addingTimeInterval(TimeInterval(BoardStore.Limits.clockSkewMs) / 1000)
|
||||
let ts = min(Date(timeIntervalSince1970: TimeInterval(event.created_at)), latestAccepted)
|
||||
let urgent = event.tags.contains { $0.count >= 2 && $0[0].lowercased() == "t" && $0[1].lowercased() == "urgent" }
|
||||
let note = Note(id: event.id, pubkey: event.pubkey, content: event.content, createdAt: ts, nickname: nick, geohash: matchedGeohash, expiresAt: expiresAt, isUrgent: urgent)
|
||||
self.notes.append(note)
|
||||
self.notes.sort { $0.createdAt > $1.createdAt }
|
||||
self.insertNoteSorted(note)
|
||||
self.enforceMemoryCap()
|
||||
self.state = .ready
|
||||
if self.state != .ready {
|
||||
self.state = .ready
|
||||
}
|
||||
}, { [weak self] in
|
||||
guard let self = self else { return }
|
||||
self.initialLoadComplete = true
|
||||
@@ -300,12 +328,37 @@ final class LocationNotesManager: ObservableObject {
|
||||
if self.notes.isEmpty, !self.dependencies.anyRelayConnected(relays) {
|
||||
self.state = .connecting
|
||||
self.scheduleConnectivityRetry(relays: relays)
|
||||
} else {
|
||||
} else if self.state != .ready {
|
||||
self.state = .ready
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Inserts a note in descending `createdAt` order via binary search
|
||||
/// ($O(\log N)$ compare instead of re-sorting the entire array per note).
|
||||
private func insertNoteSorted(_ note: Note) {
|
||||
var low = 0
|
||||
var high = notes.count
|
||||
while low < high {
|
||||
let mid = (low + high) / 2
|
||||
if notes[mid].createdAt >= note.createdAt {
|
||||
low = mid + 1
|
||||
} else {
|
||||
high = mid
|
||||
}
|
||||
}
|
||||
notes.insert(note, at: low)
|
||||
}
|
||||
|
||||
private func recordNoteID(_ id: String) {
|
||||
noteIDs.insert(id)
|
||||
if noteIDs.count > maxNotesInMemory * 4 {
|
||||
// Keep all currently visible note IDs so active notes never duplicate.
|
||||
let liveIDs = Set(notes.map(\.id))
|
||||
noteIDs = liveIDs.union([id])
|
||||
}
|
||||
}
|
||||
|
||||
/// While `.connecting`, poll for a live target relay and re-subscribe as
|
||||
/// soon as one appears (fresh REQ, fresh EOSE tracking). The poll dies
|
||||
/// with the state: any subscribe/cancel invalidates it.
|
||||
@@ -411,14 +464,6 @@ final class LocationNotesManager: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
/// The NIP-40 `expiration` tag as a date, if the event carries one.
|
||||
static func expirationDate(of event: NostrEvent) -> Date? {
|
||||
guard let tag = event.tags.first(where: { $0.count >= 2 && $0[0].lowercased() == "expiration" }),
|
||||
let seconds = TimeInterval(tag[1])
|
||||
else { return nil }
|
||||
return Date(timeIntervalSince1970: seconds)
|
||||
}
|
||||
|
||||
/// Enforces defensive memory cap on notes array (keeps newest).
|
||||
private func enforceMemoryCap() {
|
||||
if notes.count > maxNotesInMemory {
|
||||
|
||||
@@ -154,6 +154,7 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
|
||||
// Reachability Cache (thread-safe)
|
||||
private var reachablePeers: Set<PeerID> = []
|
||||
private var reachableShortPeers: Set<PeerID> = []
|
||||
// Mirror of the relay manager's connection state, cached here because
|
||||
// canDeliverPromptly is called synchronously off the main actor.
|
||||
private var relaysConnected = false
|
||||
@@ -175,9 +176,12 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
let reachable = favorites.values
|
||||
.filter { $0.peerNostrPublicKey != nil }
|
||||
.map { PeerID(publicKey: $0.peerNoisePublicKey) }
|
||||
let reachableSet = Set(reachable)
|
||||
let reachableShortSet = Set(reachable.map { $0.toShort() })
|
||||
|
||||
queue.sync(flags: .barrier) {
|
||||
self.reachablePeers = Set(reachable)
|
||||
self.reachablePeers = reachableSet
|
||||
self.reachableShortPeers = reachableShortSet
|
||||
}
|
||||
|
||||
relayConnectivityCancellable = self.dependencies.relayConnectivity()
|
||||
@@ -204,14 +208,18 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
}
|
||||
|
||||
private func refreshReachablePeers() {
|
||||
Task { @MainActor [self] in
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
let favorites = dependencies.loadFavorites()
|
||||
let reachable = favorites.values
|
||||
.filter { $0.peerNostrPublicKey != nil }
|
||||
.map { PeerID(publicKey: $0.peerNoisePublicKey) }
|
||||
let reachableSet = Set(reachable)
|
||||
let reachableShortSet = Set(reachable.map { $0.toShort() })
|
||||
|
||||
self.queue.async(flags: .barrier) { [weak self] in
|
||||
self?.reachablePeers = Set(reachable)
|
||||
self?.reachablePeers = reachableSet
|
||||
self?.reachableShortPeers = reachableShortSet
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -239,8 +247,7 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
// 64-hex noise key (offline favorites), so compare in short form.
|
||||
let short = peerID.toShort()
|
||||
return queue.sync {
|
||||
if reachablePeers.contains(peerID) { return true }
|
||||
return reachablePeers.contains(where: { $0.toShort() == short })
|
||||
reachablePeers.contains(peerID) || reachableShortPeers.contains(short)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -362,17 +369,36 @@ extension NostrTransport {
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates and sends a gift-wrapped private message event
|
||||
/// Creates and sends a gift-wrapped private message event.
|
||||
/// The NIP-17 wrap (2× ECDH + ChaCha20 + 2× Schnorr) runs off the main actor
|
||||
/// while fencing delivery against panic-wipe generation bumps.
|
||||
@MainActor
|
||||
private func sendWrappedMessage(content: String, recipientHex: String, senderIdentity: NostrIdentity, registerPending: Bool = false) {
|
||||
guard let event = try? NostrProtocol.createPrivateMessage(content: content, recipientPubkey: recipientHex, senderIdentity: senderIdentity) else {
|
||||
SecureLogger.error("NostrTransport: failed to build Nostr event", category: .session)
|
||||
return
|
||||
private func sendWrappedMessage(
|
||||
content: String,
|
||||
recipientHex: String,
|
||||
senderIdentity: NostrIdentity,
|
||||
registerPending: Bool = false,
|
||||
expectedGeneration: UInt64? = nil
|
||||
) {
|
||||
let generation = expectedGeneration ?? dependencies.ackPacer.currentGeneration()
|
||||
let dependencies = self.dependencies
|
||||
Task.detached(priority: .userInitiated) {
|
||||
guard let event = try? NostrProtocol.createPrivateMessage(
|
||||
content: content,
|
||||
recipientPubkey: recipientHex,
|
||||
senderIdentity: senderIdentity
|
||||
) else {
|
||||
SecureLogger.error("NostrTransport: failed to build Nostr event", category: .session)
|
||||
return
|
||||
}
|
||||
await MainActor.run {
|
||||
guard dependencies.ackPacer.currentGeneration() == generation else { return }
|
||||
if registerPending {
|
||||
dependencies.registerPendingGiftWrap(event.id)
|
||||
}
|
||||
dependencies.sendEvent(event)
|
||||
}
|
||||
}
|
||||
if registerPending {
|
||||
dependencies.registerPendingGiftWrap(event.id)
|
||||
}
|
||||
dependencies.sendEvent(event)
|
||||
}
|
||||
|
||||
|
||||
@@ -392,7 +418,7 @@ extension NostrTransport {
|
||||
SecureLogger.error("NostrTransport: failed to embed READ ack", category: .session)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: ack, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
sendWrappedMessage(content: ack, recipientHex: recipientHex, senderIdentity: senderIdentity, expectedGeneration: generation)
|
||||
|
||||
case .deliveredDirect(let messageID, let peerID):
|
||||
guard let recipientNpub = resolveRecipientNpub(for: peerID),
|
||||
@@ -403,17 +429,17 @@ extension NostrTransport {
|
||||
SecureLogger.error("NostrTransport: failed to embed DELIVERED ack", category: .session)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: ack, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
sendWrappedMessage(content: ack, recipientHex: recipientHex, senderIdentity: senderIdentity, expectedGeneration: generation)
|
||||
|
||||
case .deliveredGeohash(let messageID, let recipientHex, let identity):
|
||||
SecureLogger.debug("GeoDM: send DELIVERED mid=\(messageID.prefix(8))…", category: .session)
|
||||
guard let embedded = NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(type: .delivered, messageID: messageID) else { return }
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true, expectedGeneration: generation)
|
||||
|
||||
case .readGeohash(let messageID, let recipientHex, let identity):
|
||||
SecureLogger.debug("GeoDM: send READ mid=\(messageID.prefix(8))…", category: .session)
|
||||
guard let embedded = NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(type: .readReceipt, messageID: messageID) else { return }
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true, expectedGeneration: generation)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,6 +248,9 @@ enum TransportConfig {
|
||||
static let nostrRelayInitialBackoffSeconds: TimeInterval = 1.0
|
||||
static let nostrRelayMaxBackoffSeconds: TimeInterval = 300.0
|
||||
static let nostrRelayBackoffMultiplier: Double = 2.0
|
||||
// Grace period before closing a non-default (geohash/notes) relay socket
|
||||
// with zero active/pending subscriptions or outbound work.
|
||||
static let nostrIdleRelayTeardownSeconds: TimeInterval = 30.0
|
||||
static let nostrRelayMaxReconnectAttempts: Int = 10
|
||||
// Reconnect delays get ±20% random jitter so relays that dropped together
|
||||
// (e.g. a network blip) don't thundering-herd the same reconnect instant.
|
||||
|
||||
@@ -230,7 +230,12 @@ extension ChatViewModel: ChatPrivateConversationContext {
|
||||
/// inbound account DMs sent through here) must never carry the mesh
|
||||
/// peer ID. The recipient-less encoders fill that field with random bytes.
|
||||
private func makeGeohashNostrTransport() -> NostrTransport {
|
||||
NostrTransport(keychain: keychain, idBridge: idBridge)
|
||||
if let existing = geohashNostrTransportStorage {
|
||||
return existing
|
||||
}
|
||||
let transport = NostrTransport(keychain: keychain, idBridge: idBridge)
|
||||
geohashNostrTransportStorage = transport
|
||||
return transport
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -340,6 +340,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
let locationManager: LocationChannelManager
|
||||
|
||||
var nostrRelayManager: NostrRelayManager?
|
||||
var geohashNostrTransportStorage: NostrTransport?
|
||||
private let userDefaults = UserDefaults.standard
|
||||
let keychain: KeychainManagerProtocol
|
||||
private let panicRecoveryOperations: PanicRecoveryOperations
|
||||
@@ -1733,6 +1734,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
// dropped at the main-actor delivery hop instead of landing here.
|
||||
nostrCoordinator.inbound.invalidateInFlightDecrypts()
|
||||
nostrRelayManager = nil
|
||||
geohashNostrTransportStorage = nil
|
||||
|
||||
// Clear Nostr identity associations
|
||||
idBridge.clearAllAssociations()
|
||||
|
||||
@@ -442,7 +442,7 @@ private extension ChatViewModelBootstrapper {
|
||||
id: Self.bridgeSubscriptionID,
|
||||
relayUrls: relays.isEmpty ? nil : relays,
|
||||
handler: { event in
|
||||
BridgeService.shared.handleRendezvousEvent(event)
|
||||
BridgeService.shared.handleRendezvousEvent(event, signatureAlreadyVerified: true)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -159,7 +159,11 @@ final class GeohashSubscriptionManager {
|
||||
self.inbound.subscribeNostrEvent(event, isHistoryReplay: self.replayingGeoSubscriptionID == subID)
|
||||
// Gateway downlink: rebroadcast relay events for the viewed
|
||||
// channel onto the mesh (no-op unless gateway mode is on).
|
||||
GatewayService.shared.rebroadcastRelayEvent(event, geohash: channel.geohash)
|
||||
GatewayService.shared.rebroadcastRelayEvent(
|
||||
event,
|
||||
geohash: channel.geohash,
|
||||
signatureAlreadyVerified: true
|
||||
)
|
||||
}
|
||||
}, onEOSE: { [weak self] in
|
||||
Task { @MainActor [weak self] in
|
||||
@@ -181,7 +185,11 @@ final class GeohashSubscriptionManager {
|
||||
)
|
||||
NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub) { [weak self] giftWrap in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.inbound.subscribeGiftWrap(giftWrap, id: identity)
|
||||
self?.inbound.subscribeGiftWrap(
|
||||
giftWrap,
|
||||
id: identity,
|
||||
outerSignatureAlreadyVerified: true
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -258,7 +266,11 @@ final class GeohashSubscriptionManager {
|
||||
self.inbound.handleNostrEvent(event, isHistoryReplay: self.replayingGeoSubscriptionID == subID)
|
||||
// Gateway downlink: rebroadcast relay events for the viewed
|
||||
// channel onto the mesh (no-op unless gateway mode is on).
|
||||
GatewayService.shared.rebroadcastRelayEvent(event, geohash: channel.geohash)
|
||||
GatewayService.shared.rebroadcastRelayEvent(
|
||||
event,
|
||||
geohash: channel.geohash,
|
||||
signatureAlreadyVerified: true
|
||||
)
|
||||
}
|
||||
}, onEOSE: { [weak self] in
|
||||
Task { @MainActor [weak self] in
|
||||
@@ -285,7 +297,11 @@ final class GeohashSubscriptionManager {
|
||||
)
|
||||
NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub) { [weak self] giftWrap in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.inbound.handleGiftWrap(giftWrap, id: identity)
|
||||
self?.inbound.handleGiftWrap(
|
||||
giftWrap,
|
||||
id: identity,
|
||||
outerSignatureAlreadyVerified: true
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -420,7 +436,7 @@ final class GeohashSubscriptionManager {
|
||||
|
||||
context.nostrRelayManager?.subscribe(filter: filter, id: "chat-messages") { [weak self] event in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.inbound.handleNostrMessage(event)
|
||||
self?.inbound.handleNostrMessage(event, outerSignatureAlreadyVerified: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,9 @@ protocol NostrInboundPipelineContext: AnyObject {
|
||||
/// All favorite relationships, used to bridge a Nostr pubkey back to a
|
||||
/// Noise key on the inbound DM path.
|
||||
func allFavoriteRelationships() -> [FavoritesPersistenceService.FavoriteRelationship]
|
||||
/// Fast reverse lookup from a Nostr pubkey (hex or npub) to a favorite's
|
||||
/// Noise static key; defaults to scanning `allFavoriteRelationships()`.
|
||||
func favoriteNoiseKey(forNostrPubkey nostrPubkey: String) -> Data?
|
||||
|
||||
// MARK: Presence & key mapping
|
||||
func setGeoNickname(_ nickname: String, forPubkey pubkeyHex: String)
|
||||
@@ -56,6 +59,38 @@ protocol NostrInboundPipelineContext: AnyObject {
|
||||
func handleReadReceipt(_ payload: NoisePayload, senderPubkey: String, convKey: PeerID)
|
||||
}
|
||||
|
||||
extension NostrInboundPipelineContext {
|
||||
func favoriteNoiseKey(forNostrPubkey nostrPubkey: String) -> Data? {
|
||||
let favorites = allFavoriteRelationships()
|
||||
var npubToMatch = nostrPubkey
|
||||
|
||||
if !nostrPubkey.hasPrefix("npub") {
|
||||
if let pubkeyData = Data(hexString: nostrPubkey),
|
||||
let encoded = try? Bech32.encode(hrp: "npub", data: pubkeyData) {
|
||||
npubToMatch = encoded
|
||||
} else {
|
||||
SecureLogger.warning(
|
||||
"⚠️ Invalid hex public key format or encoding failed: \(nostrPubkey.prefix(16))...",
|
||||
category: .session
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
for relationship in favorites {
|
||||
if let storedNostrKey = relationship.peerNostrPublicKey {
|
||||
if storedNostrKey == npubToMatch {
|
||||
return relationship.peerNoisePublicKey
|
||||
}
|
||||
if !storedNostrKey.hasPrefix("npub") && storedNostrKey == nostrPubkey {
|
||||
SecureLogger.debug("✅ Found Noise key for Nostr sender (hex match)", category: .session)
|
||||
return relationship.peerNoisePublicKey
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
extension ChatViewModel: NostrInboundPipelineContext {
|
||||
// `currentGeohash`, the identity/blocking members, key mapping, and the
|
||||
// inbound message handlers already have witnesses on `ChatViewModel`.
|
||||
@@ -69,6 +104,10 @@ extension ChatViewModel: NostrInboundPipelineContext {
|
||||
Array(FavoritesPersistenceService.shared.favorites.values)
|
||||
}
|
||||
|
||||
func favoriteNoiseKey(forNostrPubkey nostrPubkey: String) -> Data? {
|
||||
FavoritesPersistenceService.shared.noisePublicKey(forNostrPubkey: nostrPubkey)
|
||||
}
|
||||
|
||||
func recordProcessedNostrEvent(_ eventID: String) {
|
||||
deduplicationService.recordNostrEvent(eventID, persist: true)
|
||||
}
|
||||
@@ -205,14 +244,11 @@ final class NostrInboundPipeline {
|
||||
mentions: mentions.isEmpty ? nil : mentions
|
||||
)
|
||||
|
||||
Task { @MainActor [weak context] in
|
||||
guard let context else { return }
|
||||
let isBlocked = context.isNostrBlocked(pubkeyHexLowercased: event.pubkey.lowercased())
|
||||
context.handlePublicMessage(message, powBits: powBits)
|
||||
if !isBlocked {
|
||||
context.checkForMentions(message)
|
||||
context.sendHapticFeedback(for: message)
|
||||
}
|
||||
let isBlocked = context.isNostrBlocked(pubkeyHexLowercased: event.pubkey.lowercased())
|
||||
context.handlePublicMessage(message, powBits: powBits)
|
||||
if !isBlocked {
|
||||
context.checkForMentions(message)
|
||||
context.sendHapticFeedback(for: message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,21 +339,22 @@ final class NostrInboundPipeline {
|
||||
mentions: mentions.isEmpty ? nil : mentions
|
||||
)
|
||||
|
||||
Task { @MainActor [weak context] in
|
||||
guard let context else { return }
|
||||
context.handlePublicMessage(message, powBits: powBits)
|
||||
context.checkForMentions(message)
|
||||
context.sendHapticFeedback(for: message)
|
||||
}
|
||||
context.handlePublicMessage(message, powBits: powBits)
|
||||
context.checkForMentions(message)
|
||||
context.sendHapticFeedback(for: message)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func subscribeGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) {
|
||||
func subscribeGiftWrap(
|
||||
_ giftWrap: NostrEvent,
|
||||
id: NostrIdentity,
|
||||
outerSignatureAlreadyVerified: Bool = false
|
||||
) {
|
||||
guard let context else { return }
|
||||
// Cheap dedup pre-check only; processGeohashGiftWrap does the
|
||||
// authoritative main-actor check-and-record before the off-main
|
||||
// NIP-17 unwrap. The outer signature was already verified (exactly
|
||||
// once, off the main actor) by NostrRelayManager.
|
||||
// once, off the main actor) by NostrRelayManager when sourced from a relay.
|
||||
guard !context.hasProcessedNostrEvent(giftWrap.id) else { return }
|
||||
|
||||
// Capture the wipe generation at spawn, alongside the per-geohash
|
||||
@@ -326,12 +363,22 @@ final class NostrInboundPipeline {
|
||||
// drops its result instead of delivering plaintext post-wipe.
|
||||
let wipeGeneration = self.wipeGeneration
|
||||
Task.detached(priority: .userInitiated) { [weak self] in
|
||||
await self?.processGeohashGiftWrap(giftWrap, id: id, verbose: false, wipeGeneration: wipeGeneration)
|
||||
await self?.processGeohashGiftWrap(
|
||||
giftWrap,
|
||||
id: id,
|
||||
verbose: false,
|
||||
wipeGeneration: wipeGeneration,
|
||||
outerSignatureAlreadyVerified: outerSignatureAlreadyVerified
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func handleGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) {
|
||||
func handleGiftWrap(
|
||||
_ giftWrap: NostrEvent,
|
||||
id: NostrIdentity,
|
||||
outerSignatureAlreadyVerified: Bool = false
|
||||
) {
|
||||
guard let context else { return }
|
||||
// Cheap dedup pre-check only; see subscribeGiftWrap.
|
||||
if context.hasProcessedNostrEvent(giftWrap.id) {
|
||||
@@ -341,14 +388,20 @@ final class NostrInboundPipeline {
|
||||
// Spawn-time wipe-generation capture; see subscribeGiftWrap.
|
||||
let wipeGeneration = self.wipeGeneration
|
||||
Task.detached(priority: .userInitiated) { [weak self] in
|
||||
await self?.processGeohashGiftWrap(giftWrap, id: id, verbose: true, wipeGeneration: wipeGeneration)
|
||||
await self?.processGeohashGiftWrap(
|
||||
giftWrap,
|
||||
id: id,
|
||||
verbose: true,
|
||||
wipeGeneration: wipeGeneration,
|
||||
outerSignatureAlreadyVerified: outerSignatureAlreadyVerified
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Geohash-DM gift wrap ingest. The NIP-17 unwrap (two ECDH+ChaCha
|
||||
/// layers) runs off the main actor; results hop back for state updates.
|
||||
/// `verbose` keeps `handleGiftWrap`'s decrypt logging without adding it
|
||||
/// to the sampling path.
|
||||
/// layers) and BitChat packet decode run off the main actor; results hop
|
||||
/// back for state updates. `verbose` keeps `handleGiftWrap`'s decrypt
|
||||
/// logging without adding it to the sampling path.
|
||||
///
|
||||
/// `wipeGeneration` is this pipeline's generation captured at spawn (the
|
||||
/// moment the pre-wipe `id` was captured); a mismatch at either main-actor
|
||||
@@ -360,7 +413,8 @@ final class NostrInboundPipeline {
|
||||
_ giftWrap: NostrEvent,
|
||||
id: NostrIdentity,
|
||||
verbose: Bool,
|
||||
wipeGeneration: UInt64
|
||||
wipeGeneration: UInt64,
|
||||
outerSignatureAlreadyVerified: Bool
|
||||
) async {
|
||||
guard let context else { return }
|
||||
// Authoritative check-and-record, atomic on the main actor so two
|
||||
@@ -375,7 +429,8 @@ final class NostrInboundPipeline {
|
||||
|
||||
guard let (content, senderPubkey, rumorTs) = try? NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
recipientIdentity: id
|
||||
recipientIdentity: id,
|
||||
outerSignatureAlreadyVerified: outerSignatureAlreadyVerified
|
||||
) else {
|
||||
if verbose {
|
||||
SecureLogger.warning("GeoDM: failed decrypt giftWrap id=\(giftWrap.id.prefix(8))…", category: .session)
|
||||
@@ -397,17 +452,18 @@ final class NostrInboundPipeline {
|
||||
)
|
||||
}
|
||||
|
||||
guard let packet = Self.decodeEmbeddedBitChatPacket(from: content),
|
||||
packet.type == MessageType.noiseEncrypted.rawValue,
|
||||
let payload = NoisePayload.decode(packet.payload)
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
await MainActor.run {
|
||||
// A panic wipe during the off-main decrypt must not let the
|
||||
// pre-wipe plaintext reach post-wipe state; drop it here, atomic
|
||||
// with the wipe on the main actor.
|
||||
guard self.wipeGeneration == wipeGeneration else { return }
|
||||
guard let packet = Self.decodeEmbeddedBitChatPacket(from: content),
|
||||
packet.type == MessageType.noiseEncrypted.rawValue,
|
||||
let payload = NoisePayload.decode(packet.payload)
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
let convKey = PeerID(nostr_: senderPubkey)
|
||||
context.registerNostrKeyMapping(senderPubkey, for: convKey)
|
||||
@@ -437,7 +493,7 @@ final class NostrInboundPipeline {
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func handleNostrMessage(_ giftWrap: NostrEvent) {
|
||||
func handleNostrMessage(_ giftWrap: NostrEvent, outerSignatureAlreadyVerified: Bool = false) {
|
||||
guard let context else { return }
|
||||
// Cheap dedup pre-check only; processNostrMessage does the
|
||||
// authoritative check-and-record before the off-main NIP-17 unwrap.
|
||||
@@ -448,34 +504,34 @@ final class NostrInboundPipeline {
|
||||
if context.hasProcessedNostrEvent(giftWrap.id) { return }
|
||||
|
||||
Task.detached(priority: .userInitiated) { [weak self] in
|
||||
await self?.processNostrMessage(giftWrap)
|
||||
await self?.processNostrMessage(
|
||||
giftWrap,
|
||||
outerSignatureAlreadyVerified: outerSignatureAlreadyVerified
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func processNostrMessage(_ giftWrap: NostrEvent) async {
|
||||
func processNostrMessage(
|
||||
_ giftWrap: NostrEvent,
|
||||
outerSignatureAlreadyVerified: Bool = false
|
||||
) async {
|
||||
guard let context else { return }
|
||||
// Authoritative check-and-record, atomic on the main actor so two
|
||||
// concurrent detached tasks can't both process the same event.
|
||||
let alreadyProcessed: Bool = await MainActor.run {
|
||||
if context.hasProcessedNostrEvent(giftWrap.id) { return true }
|
||||
// Single pre-decrypt main-actor hop: atomically check-and-record dedup
|
||||
// AND snapshot `(currentIdentity, wipeGeneration)` so the generation
|
||||
// vouches for exactly this identity.
|
||||
let preDecrypt: (identity: NostrIdentity, wipeGeneration: UInt64)? = await MainActor.run {
|
||||
if context.hasProcessedNostrEvent(giftWrap.id) { return nil }
|
||||
context.recordProcessedNostrEvent(giftWrap.id)
|
||||
return false
|
||||
guard let identity = context.currentNostrIdentity() else { return nil }
|
||||
return (identity, self.wipeGeneration)
|
||||
}
|
||||
if alreadyProcessed { return }
|
||||
// Fetch the identity and the wipe generation in ONE main-actor hop:
|
||||
// the generation then vouches for exactly this identity. A wipe after
|
||||
// this point bumps the generation and the delivery hop below drops
|
||||
// the decrypted result (same guard as processGeohashGiftWrap; this
|
||||
// account-mailbox path had the identical hazard).
|
||||
let (currentIdentity, wipeGeneration): (NostrIdentity?, UInt64) = await MainActor.run {
|
||||
(context.currentNostrIdentity(), self.wipeGeneration)
|
||||
}
|
||||
guard let currentIdentity else { return }
|
||||
guard let (currentIdentity, wipeGeneration) = preDecrypt else { return }
|
||||
|
||||
do {
|
||||
let (content, senderPubkey, rumorTimestamp) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
recipientIdentity: currentIdentity
|
||||
recipientIdentity: currentIdentity,
|
||||
outerSignatureAlreadyVerified: outerSignatureAlreadyVerified
|
||||
)
|
||||
|
||||
guard Self.isPlausibleRumorTimestamp(rumorTimestamp) else {
|
||||
@@ -487,53 +543,50 @@ final class NostrInboundPipeline {
|
||||
return
|
||||
}
|
||||
|
||||
if content.hasPrefix("bitchat1:") {
|
||||
let packet: BitchatPacket? = await MainActor.run {
|
||||
Self.decodeEmbeddedBitChatPacket(from: content)
|
||||
}
|
||||
guard let packet else {
|
||||
SecureLogger.error("Failed to decode embedded BitChat packet from Nostr DM", category: .session)
|
||||
return
|
||||
}
|
||||
|
||||
let actualSenderNoiseKey: Data? = await MainActor.run {
|
||||
self.findNoiseKey(for: senderPubkey)
|
||||
}
|
||||
let targetPeerID = PeerID(str: actualSenderNoiseKey?.hexEncodedString()) ?? PeerID(nostr_: senderPubkey)
|
||||
|
||||
if packet.type == MessageType.noiseEncrypted.rawValue,
|
||||
let payload = NoisePayload.decode(packet.payload) {
|
||||
let messageTimestamp = Date(timeIntervalSince1970: TimeInterval(rumorTimestamp))
|
||||
await MainActor.run {
|
||||
// Drop pre-wipe plaintext if a panic wipe landed
|
||||
// during the off-main decrypt (see above).
|
||||
guard self.wipeGeneration == wipeGeneration else { return }
|
||||
context.registerNostrKeyMapping(senderPubkey, for: targetPeerID)
|
||||
|
||||
switch payload.type {
|
||||
case .privateMessage:
|
||||
context.handlePrivateMessage(
|
||||
payload,
|
||||
senderPubkey: senderPubkey,
|
||||
convKey: targetPeerID,
|
||||
id: currentIdentity,
|
||||
messageTimestamp: messageTimestamp
|
||||
)
|
||||
case .delivered:
|
||||
context.handleDelivered(payload, senderPubkey: senderPubkey, convKey: targetPeerID)
|
||||
case .readReceipt:
|
||||
context.handleReadReceipt(payload, senderPubkey: senderPubkey, convKey: targetPeerID)
|
||||
// Group state travels only over mesh Noise sessions
|
||||
// in v1; group traffic over Nostr is ignored.
|
||||
// Live voice is mesh-only: latency and relay cost make it
|
||||
// meaningless over Nostr.
|
||||
case .verifyChallenge, .verifyResponse, .groupInvite, .groupKeyUpdate, .vouch, .voiceFrame, .privateFile, .authenticatedPeerState:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
guard content.hasPrefix("bitchat1:") else {
|
||||
SecureLogger.debug("Ignoring non-embedded Nostr DM content", category: .session)
|
||||
return
|
||||
}
|
||||
|
||||
guard let packet = Self.decodeEmbeddedBitChatPacket(from: content) else {
|
||||
SecureLogger.error("Failed to decode embedded BitChat packet from Nostr DM", category: .session)
|
||||
return
|
||||
}
|
||||
|
||||
guard packet.type == MessageType.noiseEncrypted.rawValue,
|
||||
let payload = NoisePayload.decode(packet.payload) else {
|
||||
return
|
||||
}
|
||||
|
||||
let messageTimestamp = Date(timeIntervalSince1970: TimeInterval(rumorTimestamp))
|
||||
await MainActor.run {
|
||||
// Drop pre-wipe plaintext if a panic wipe landed
|
||||
// during the off-main decrypt (see above).
|
||||
guard self.wipeGeneration == wipeGeneration else { return }
|
||||
let actualSenderNoiseKey = self.findNoiseKey(for: senderPubkey)
|
||||
let targetPeerID = PeerID(str: actualSenderNoiseKey?.hexEncodedString()) ?? PeerID(nostr_: senderPubkey)
|
||||
context.registerNostrKeyMapping(senderPubkey, for: targetPeerID)
|
||||
|
||||
switch payload.type {
|
||||
case .privateMessage:
|
||||
context.handlePrivateMessage(
|
||||
payload,
|
||||
senderPubkey: senderPubkey,
|
||||
convKey: targetPeerID,
|
||||
id: currentIdentity,
|
||||
messageTimestamp: messageTimestamp
|
||||
)
|
||||
case .delivered:
|
||||
context.handleDelivered(payload, senderPubkey: senderPubkey, convKey: targetPeerID)
|
||||
case .readReceipt:
|
||||
context.handleReadReceipt(payload, senderPubkey: senderPubkey, convKey: targetPeerID)
|
||||
// Group state travels only over mesh Noise sessions
|
||||
// in v1; group traffic over Nostr is ignored.
|
||||
// Live voice is mesh-only: latency and relay cost make it
|
||||
// meaningless over Nostr.
|
||||
case .verifyChallenge, .verifyResponse, .groupInvite, .groupKeyUpdate, .vouch, .voiceFrame, .privateFile, .authenticatedPeerState:
|
||||
break
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
SecureLogger.error("Failed to decrypt Nostr message: \(error)", category: .session)
|
||||
@@ -545,35 +598,11 @@ final class NostrInboundPipeline {
|
||||
@MainActor
|
||||
func findNoiseKey(for nostrPubkey: String) -> Data? {
|
||||
guard let context else { return nil }
|
||||
let favorites = context.allFavoriteRelationships()
|
||||
var npubToMatch = nostrPubkey
|
||||
|
||||
if !nostrPubkey.hasPrefix("npub") {
|
||||
if let pubkeyData = Data(hexString: nostrPubkey),
|
||||
let encoded = try? Bech32.encode(hrp: "npub", data: pubkeyData) {
|
||||
npubToMatch = encoded
|
||||
} else {
|
||||
SecureLogger.warning(
|
||||
"⚠️ Invalid hex public key format or encoding failed: \(nostrPubkey.prefix(16))...",
|
||||
category: .session
|
||||
)
|
||||
}
|
||||
if let noiseKey = context.favoriteNoiseKey(forNostrPubkey: nostrPubkey) {
|
||||
return noiseKey
|
||||
}
|
||||
|
||||
for relationship in favorites {
|
||||
if let storedNostrKey = relationship.peerNostrPublicKey {
|
||||
if storedNostrKey == npubToMatch {
|
||||
return relationship.peerNoisePublicKey
|
||||
}
|
||||
if !storedNostrKey.hasPrefix("npub") && storedNostrKey == nostrPubkey {
|
||||
SecureLogger.debug("✅ Found Noise key for Nostr sender (hex match)", category: .session)
|
||||
return relationship.peerNoisePublicKey
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SecureLogger.debug(
|
||||
"⚠️ No matching Noise key found for Nostr pubkey: \(nostrPubkey.prefix(16))... (tried npub: \(npubToMatch.prefix(16))...)",
|
||||
"⚠️ No matching Noise key found for Nostr pubkey: \(nostrPubkey.prefix(16))...",
|
||||
category: .session
|
||||
)
|
||||
return nil
|
||||
@@ -597,8 +626,7 @@ extension NostrInboundPipeline {
|
||||
}
|
||||
|
||||
private extension NostrInboundPipeline {
|
||||
@MainActor
|
||||
static func decodeEmbeddedBitChatPacket(from content: String) -> BitchatPacket? {
|
||||
nonisolated static func decodeEmbeddedBitChatPacket(from content: String) -> BitchatPacket? {
|
||||
guard content.hasPrefix("bitchat1:") else { return nil }
|
||||
let encoded = String(content.dropFirst("bitchat1:".count))
|
||||
let maxBytes = FileTransferLimits.maxFramedFileBytes
|
||||
|
||||
@@ -456,6 +456,20 @@ struct GeohashParticipantTrackerTests {
|
||||
_ = cancellable
|
||||
}
|
||||
|
||||
@Test func objectWillChange_firesOncePerNewActiveParticipant() async {
|
||||
let tracker = GeohashParticipantTracker()
|
||||
let context = MockParticipantContext()
|
||||
tracker.configure(context: context)
|
||||
tracker.setActiveGeohash("abc123")
|
||||
|
||||
var changes = 0
|
||||
let cancellable = tracker.objectWillChange.sink { _ in changes += 1 }
|
||||
tracker.recordParticipant(pubkeyHex: "pubkey1")
|
||||
|
||||
#expect(changes == 1)
|
||||
_ = cancellable
|
||||
}
|
||||
|
||||
// MARK: - GeoPerson Tests
|
||||
|
||||
@Test func geoPerson_identifiable() async {
|
||||
|
||||
@@ -110,4 +110,24 @@ final class FavoritesPersistenceServiceTests: XCTestCase {
|
||||
let decoded = try JSONDecoder().decode([FavoritesPersistenceService.FavoriteRelationship].self, from: cleaned)
|
||||
XCTAssertEqual(decoded.count, 1)
|
||||
}
|
||||
|
||||
func test_noisePublicKey_indexesBothNpubAndHexKeys() throws {
|
||||
let service = FavoritesPersistenceService(keychain: MockKeychain())
|
||||
let peerKey = Data((160..<192).map(UInt8.init))
|
||||
let identity = try NostrIdentity.generate()
|
||||
|
||||
service.addFavorite(
|
||||
peerNoisePublicKey: peerKey,
|
||||
peerNostrPublicKey: identity.npub,
|
||||
peerNickname: "Frank"
|
||||
)
|
||||
|
||||
XCTAssertEqual(service.noisePublicKey(forNostrPubkey: identity.npub), peerKey)
|
||||
XCTAssertEqual(service.noisePublicKey(forNostrPubkey: identity.publicKeyHex), peerKey)
|
||||
XCTAssertEqual(service.noisePublicKey(forNostrPubkey: identity.publicKeyHex.uppercased()), peerKey)
|
||||
|
||||
service.removeFavorite(peerNoisePublicKey: peerKey)
|
||||
XCTAssertNil(service.noisePublicKey(forNostrPubkey: identity.npub))
|
||||
XCTAssertNil(service.noisePublicKey(forNostrPubkey: identity.publicKeyHex))
|
||||
}
|
||||
}
|
||||
@@ -746,6 +746,80 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
XCTAssertTrue(resubscribed)
|
||||
}
|
||||
|
||||
func test_unsubscribe_tearsDownIdleNonDefaultRelayAfterGracePeriod() async {
|
||||
let relayURL = "wss://idle-geo.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let filter = makeFilter()
|
||||
|
||||
context.manager.subscribe(filter: filter, id: "geo-sub", relayUrls: [relayURL], handler: { _ in })
|
||||
let subscribed = await waitUntil {
|
||||
context.sessionFactory.latestConnection(for: relayURL)?.sentStrings.count == 1
|
||||
}
|
||||
XCTAssertTrue(subscribed)
|
||||
|
||||
context.manager.unsubscribe(id: "geo-sub")
|
||||
let closeSent = await waitUntil {
|
||||
context.sessionFactory.latestConnection(for: relayURL)?.sentStrings.count == 2
|
||||
}
|
||||
XCTAssertTrue(closeSent)
|
||||
XCTAssertEqual(context.scheduler.scheduled.last?.delay, TransportConfig.nostrIdleRelayTeardownSeconds)
|
||||
|
||||
context.scheduler.runNext()
|
||||
let tornDown = await waitUntil {
|
||||
context.manager.relays.allSatisfy { $0.url != relayURL } &&
|
||||
(context.sessionFactory.latestConnection(for: relayURL)?.cancelCallCount ?? 0) >= 1
|
||||
}
|
||||
XCTAssertTrue(tornDown)
|
||||
}
|
||||
|
||||
func test_unsubscribe_cancelsIdleTeardownWhenResubscribedBeforeGracePeriodExpires() async {
|
||||
let relayURL = "wss://reused-geo.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let filter = makeFilter()
|
||||
|
||||
context.manager.subscribe(filter: filter, id: "geo-sub", relayUrls: [relayURL], handler: { _ in })
|
||||
let subscribed = await waitUntil {
|
||||
context.sessionFactory.latestConnection(for: relayURL)?.sentStrings.count == 1
|
||||
}
|
||||
XCTAssertTrue(subscribed)
|
||||
|
||||
context.manager.unsubscribe(id: "geo-sub")
|
||||
XCTAssertEqual(context.scheduler.scheduled.count, 1)
|
||||
|
||||
// Resubscribe before the idle grace period expires.
|
||||
context.clock.now = context.clock.now.addingTimeInterval(0.2)
|
||||
context.manager.subscribe(filter: filter, id: "geo-sub", relayUrls: [relayURL], handler: { _ in })
|
||||
let resubscribed = await waitUntil {
|
||||
context.sessionFactory.latestConnection(for: relayURL)?.sentStrings.count == 3
|
||||
}
|
||||
XCTAssertTrue(resubscribed)
|
||||
|
||||
// Firing the stale teardown timer must be a no-op.
|
||||
context.scheduler.runNext()
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertTrue(context.manager.relays.contains(where: { $0.url == relayURL && $0.isConnected }))
|
||||
XCTAssertEqual(context.sessionFactory.latestConnection(for: relayURL)?.cancelCallCount, 0)
|
||||
}
|
||||
|
||||
func test_unsubscribe_doesNotTearDownDefaultRelayWhenIdle() async {
|
||||
let context = makeContext(permission: .authorized)
|
||||
let connected = await waitUntil {
|
||||
context.manager.relays.count == self.expectedDefaultRelayCount &&
|
||||
context.manager.relays.allSatisfy(\.isConnected)
|
||||
}
|
||||
XCTAssertTrue(connected)
|
||||
|
||||
context.manager.subscribe(filter: makeFilter(), id: "default-sub", handler: { _ in })
|
||||
let subscribed = await waitUntil {
|
||||
context.sessionFactory.allConnections.allSatisfy { $0.sentStrings.count == 1 }
|
||||
}
|
||||
XCTAssertTrue(subscribed)
|
||||
|
||||
let scheduledBefore = context.scheduler.scheduled.count
|
||||
context.manager.unsubscribe(id: "default-sub")
|
||||
XCTAssertEqual(context.scheduler.scheduled.count, scheduledBefore)
|
||||
}
|
||||
|
||||
func test_receiveEvent_deliversHandlerAndTracksReceivedCount() async throws {
|
||||
let relayURL = "wss://events.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
|
||||
@@ -85,9 +85,9 @@ public final class TorManager: ObservableObject {
|
||||
private var startPendingAfterShutdown = false
|
||||
private var wipeDataDirectoryOnShutdown = false
|
||||
private var bootstrapMonitorStarted = false
|
||||
// Fences the detached poll loop: shutdown, dormancy, and restart each bump
|
||||
// this, so a loop from a previous attempt cannot run out its deadline and
|
||||
// report a stall over state that a newer lifecycle event already owns.
|
||||
// Fences detached lifecycle tasks (start, bootstrap poll, SOCKS probe):
|
||||
// shutdown, dormancy, and restart each bump this, so work from a previous
|
||||
// attempt cannot overwrite state owned by a newer lifecycle event.
|
||||
private var bootstrapGeneration = 0
|
||||
private var pathMonitor: NWPathMonitor?
|
||||
private var isAppForeground: Bool = true
|
||||
@@ -95,6 +95,12 @@ public final class TorManager: ObservableObject {
|
||||
private var startedAt: Date? = nil // Tracks initial startup time for grace period
|
||||
private(set) var allowAutoStart: Bool = false
|
||||
|
||||
private struct ReadyWaiter {
|
||||
let continuation: CheckedContinuation<Bool, Never>
|
||||
let timeoutTask: Task<Void, Never>
|
||||
}
|
||||
private var readyWaiters: [UUID: ReadyWaiter] = [:]
|
||||
|
||||
private init() {}
|
||||
|
||||
// MARK: - Public API
|
||||
@@ -115,8 +121,9 @@ public final class TorManager: ObservableObject {
|
||||
SecureLogger.debug("TorManager: startIfNeeded() - startedAt set", category: .session)
|
||||
lastError = nil
|
||||
NotificationCenter.default.post(name: .TorWillStart, object: nil)
|
||||
ensureFilesystemLayout()
|
||||
startArti()
|
||||
bootstrapGeneration += 1
|
||||
let generation = bootstrapGeneration
|
||||
startArti(generation: generation)
|
||||
startPathMonitorIfNeeded()
|
||||
}
|
||||
|
||||
@@ -130,21 +137,68 @@ public final class TorManager: ObservableObject {
|
||||
// Default matches the bootstrap monitor deadline (75s); a shorter wait here
|
||||
// reports "not ready" while Arti is still legitimately bootstrapping.
|
||||
public func awaitReady(timeout: TimeInterval = 75.0) async -> Bool {
|
||||
await MainActor.run {
|
||||
let alreadyPermitted: Bool = await MainActor.run {
|
||||
if self.isAppForeground { self.startIfNeeded() }
|
||||
return self.networkPermitted
|
||||
}
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
if await MainActor.run(body: { self.networkPermitted }) { return true }
|
||||
while Date() < deadline {
|
||||
try? await Task.sleep(nanoseconds: 200_000_000)
|
||||
if await MainActor.run(body: { self.networkPermitted }) { return true }
|
||||
if alreadyPermitted { return true }
|
||||
guard timeout > 0 else { return false }
|
||||
|
||||
let waiterID = UUID()
|
||||
let cancellationFlag = AtomicOnceFlag()
|
||||
let timeoutNanoseconds = UInt64(max(0, timeout) * 1_000_000_000)
|
||||
|
||||
return await withTaskCancellationHandler {
|
||||
await withCheckedContinuation { continuation in
|
||||
Task { @MainActor in
|
||||
if cancellationFlag.isSet {
|
||||
continuation.resume(returning: false)
|
||||
return
|
||||
}
|
||||
if self.networkPermitted {
|
||||
continuation.resume(returning: true)
|
||||
return
|
||||
}
|
||||
let timeoutTask = Task { @MainActor [weak self] in
|
||||
try? await Task.sleep(nanoseconds: timeoutNanoseconds)
|
||||
guard !Task.isCancelled, let self else { return }
|
||||
if let pending = self.readyWaiters.removeValue(forKey: waiterID) {
|
||||
pending.continuation.resume(returning: self.networkPermitted)
|
||||
}
|
||||
}
|
||||
self.readyWaiters[waiterID] = ReadyWaiter(
|
||||
continuation: continuation,
|
||||
timeoutTask: timeoutTask
|
||||
)
|
||||
}
|
||||
}
|
||||
} onCancel: {
|
||||
_ = cancellationFlag.trySet()
|
||||
Task { @MainActor in
|
||||
self.cancelReadyWaiter(id: waiterID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func cancelReadyWaiter(id: UUID) {
|
||||
guard let pending = readyWaiters.removeValue(forKey: id) else { return }
|
||||
pending.timeoutTask.cancel()
|
||||
pending.continuation.resume(returning: false)
|
||||
}
|
||||
|
||||
private func resumeAllReadyWaiters() {
|
||||
guard !readyWaiters.isEmpty else { return }
|
||||
let waiters = readyWaiters
|
||||
readyWaiters.removeAll()
|
||||
for waiter in waiters.values {
|
||||
waiter.timeoutTask.cancel()
|
||||
waiter.continuation.resume(returning: true)
|
||||
}
|
||||
return await MainActor.run(body: { self.networkPermitted })
|
||||
}
|
||||
|
||||
// MARK: - Filesystem
|
||||
|
||||
func dataDirectoryURL() -> URL? {
|
||||
nonisolated func dataDirectoryURL() -> URL? {
|
||||
do {
|
||||
let base = try FileManager.default.url(
|
||||
for: .applicationSupportDirectory,
|
||||
@@ -159,8 +213,7 @@ public final class TorManager: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
private func ensureFilesystemLayout() {
|
||||
guard let dir = dataDirectoryURL() else { return }
|
||||
nonisolated private static func ensureFilesystemLayout(at dir: URL) {
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
} catch {
|
||||
@@ -170,40 +223,54 @@ public final class TorManager: ObservableObject {
|
||||
|
||||
// MARK: - Arti Integration
|
||||
|
||||
private func startArti() {
|
||||
guard let dir = dataDirectoryURL()?.path else {
|
||||
private func startArti(generation: Int) {
|
||||
guard let dirURL = dataDirectoryURL() else {
|
||||
isStarting = false
|
||||
lastError = NSError(domain: "TorManager", code: -1, userInfo: [NSLocalizedDescriptionKey: "No data directory"])
|
||||
return
|
||||
}
|
||||
let host = socksHost
|
||||
let port = socksPort
|
||||
|
||||
// Check if already running
|
||||
if arti_is_running() != 0 {
|
||||
SecureLogger.info("TorManager: Arti already running", category: .session)
|
||||
startBootstrapMonitor()
|
||||
return
|
||||
}
|
||||
|
||||
let result = dir.withCString { dptr in
|
||||
arti_start(dptr, UInt16(socksPort))
|
||||
}
|
||||
|
||||
if result != 0 {
|
||||
SecureLogger.error("TorManager: arti_start failed rc=\(result)", category: .session)
|
||||
isStarting = false
|
||||
lastError = NSError(domain: "TorManager", code: Int(result), userInfo: [NSLocalizedDescriptionKey: "Arti start failed"])
|
||||
return
|
||||
}
|
||||
|
||||
SecureLogger.info("TorManager: arti_start OK (SOCKS \(socksHost):\(socksPort))", category: .session)
|
||||
startBootstrapMonitor()
|
||||
|
||||
// Start SOCKS readiness probe fenced to this bootstrap generation so
|
||||
// an in-flight probe cannot mark Tor ready after a shutdown or restart.
|
||||
let generation = bootstrapGeneration
|
||||
// Run directory creation and Arti FFI startup off the main actor so
|
||||
// launch/foreground recovery never stalls UI rendering.
|
||||
Task.detached(priority: .userInitiated) { [weak self] in
|
||||
guard let self else { return }
|
||||
let ready = await self.waitForSocksReady(timeout: 60.0)
|
||||
Self.ensureFilesystemLayout(at: dirURL)
|
||||
|
||||
let alreadyRunning = arti_is_running() != 0
|
||||
if alreadyRunning {
|
||||
SecureLogger.info("TorManager: Arti already running", category: .session)
|
||||
await MainActor.run {
|
||||
guard generation == self.bootstrapGeneration else { return }
|
||||
self.startBootstrapMonitor(generation: generation)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
let result = dirURL.path.withCString { dptr in
|
||||
arti_start(dptr, UInt16(port))
|
||||
}
|
||||
|
||||
if result != 0 {
|
||||
SecureLogger.error("TorManager: arti_start failed rc=\(result)", category: .session)
|
||||
await MainActor.run {
|
||||
guard generation == self.bootstrapGeneration else { return }
|
||||
self.isStarting = false
|
||||
self.lastError = NSError(domain: "TorManager", code: Int(result), userInfo: [NSLocalizedDescriptionKey: "Arti start failed"])
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
SecureLogger.info("TorManager: arti_start OK (SOCKS \(host):\(port))", category: .session)
|
||||
await MainActor.run {
|
||||
guard generation == self.bootstrapGeneration else { return }
|
||||
self.startBootstrapMonitor(generation: generation)
|
||||
}
|
||||
|
||||
// Probe SOCKS readiness off-main, fenced to this bootstrap generation
|
||||
// so an in-flight probe cannot mark Tor ready after shutdown/restart.
|
||||
let ready = await self.waitForSocksReady(port: port, timeout: 60.0)
|
||||
await MainActor.run {
|
||||
guard generation == self.bootstrapGeneration else { return }
|
||||
self.socksReady = ready
|
||||
@@ -217,16 +284,26 @@ public final class TorManager: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
private func waitForSocksReady(timeout: TimeInterval) async -> Bool {
|
||||
nonisolated private func waitForSocksReady(port: Int, timeout: TimeInterval) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
var attempts = 0
|
||||
while Date() < deadline {
|
||||
if await probeSocksOnce() { return true }
|
||||
try? await Task.sleep(nanoseconds: 250_000_000)
|
||||
if arti_is_running() == 0 {
|
||||
return false
|
||||
}
|
||||
if await Self.probeSocksOnce(port: port) {
|
||||
return true
|
||||
}
|
||||
attempts += 1
|
||||
// Probe quickly for the first second, then ease to 1s intervals so
|
||||
// slow or blocked networks do not spam loopback sockets.
|
||||
let sleepNs: UInt64 = attempts < 4 ? 250_000_000 : 1_000_000_000
|
||||
try? await Task.sleep(nanoseconds: sleepNs)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private func probeSocksOnce() async -> Bool {
|
||||
nonisolated private static func probeSocksOnce(port socksPort: Int) async -> Bool {
|
||||
#if canImport(Network)
|
||||
await withCheckedContinuation { cont in
|
||||
let params = NWParameters.tcp
|
||||
@@ -238,12 +315,10 @@ public final class TorManager: ObservableObject {
|
||||
let endpoint = NWEndpoint.hostPort(host: host, port: port)
|
||||
let conn = NWConnection(to: endpoint, using: params)
|
||||
|
||||
var resumed = false
|
||||
let resumeOnce: (Bool) -> Void = { value in
|
||||
if !resumed {
|
||||
resumed = true
|
||||
cont.resume(returning: value)
|
||||
}
|
||||
let resumed = AtomicOnceFlag()
|
||||
let resumeOnce: @Sendable (Bool) -> Void = { value in
|
||||
guard resumed.trySet() else { return }
|
||||
cont.resume(returning: value)
|
||||
}
|
||||
|
||||
conn.stateUpdateHandler = { state in
|
||||
@@ -267,34 +342,55 @@ public final class TorManager: ObservableObject {
|
||||
conn.start(queue: DispatchQueue.global(qos: .utility))
|
||||
}
|
||||
#else
|
||||
_ = socksPort
|
||||
return false
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Bootstrap Monitoring
|
||||
|
||||
private func startBootstrapMonitor() {
|
||||
private func startBootstrapMonitor(generation: Int) {
|
||||
guard !bootstrapMonitorStarted else { return }
|
||||
bootstrapMonitorStarted = true
|
||||
bootstrapGeneration += 1
|
||||
let generation = bootstrapGeneration
|
||||
Task.detached(priority: .utility) { [weak self] in
|
||||
await self?.bootstrapPollLoop(generation: generation)
|
||||
}
|
||||
}
|
||||
|
||||
private func bootstrapPollLoop(generation: Int) async {
|
||||
nonisolated private func bootstrapPollLoop(generation: Int) async {
|
||||
let deadline = Date().addingTimeInterval(75)
|
||||
var didComplete = false
|
||||
while Date() < deadline {
|
||||
guard generation == bootstrapGeneration else { return }
|
||||
let progress = Int(arti_bootstrap_progress())
|
||||
let summary = getBootstrapSummary()
|
||||
var lastPublishedProgress: Int?
|
||||
var lastPublishedSummary: String?
|
||||
|
||||
self.bootstrapProgress = progress
|
||||
self.bootstrapSummary = summary
|
||||
if progress >= 100 { self.isStarting = false }
|
||||
self.recomputeReady()
|
||||
while Date() < deadline {
|
||||
let progress = Int(arti_bootstrap_progress())
|
||||
let summary = Self.readBootstrapSummary()
|
||||
|
||||
if progress != lastPublishedProgress || summary != lastPublishedSummary || progress >= 100 {
|
||||
lastPublishedProgress = progress
|
||||
lastPublishedSummary = summary
|
||||
let stillCurrent: Bool = await MainActor.run {
|
||||
guard generation == self.bootstrapGeneration else { return false }
|
||||
if self.bootstrapProgress != progress {
|
||||
self.bootstrapProgress = progress
|
||||
}
|
||||
if self.bootstrapSummary != summary {
|
||||
self.bootstrapSummary = summary
|
||||
}
|
||||
if progress >= 100, self.isStarting {
|
||||
self.isStarting = false
|
||||
}
|
||||
self.recomputeReady()
|
||||
return true
|
||||
}
|
||||
guard stillCurrent else { return }
|
||||
} else {
|
||||
let stillCurrent: Bool = await MainActor.run {
|
||||
generation == self.bootstrapGeneration
|
||||
}
|
||||
guard stillCurrent else { return }
|
||||
}
|
||||
|
||||
if progress >= 100 {
|
||||
didComplete = true
|
||||
@@ -308,18 +404,20 @@ public final class TorManager: ObservableObject {
|
||||
// blocked network was indistinguishable from a slow one. A deliberate
|
||||
// shutdown mid-bootstrap is not a stall, hence the generation check.
|
||||
if !didComplete {
|
||||
guard generation == bootstrapGeneration else { return }
|
||||
self.isStarting = false
|
||||
self.bootstrapDidStall = true
|
||||
SecureLogger.warning(
|
||||
"TorManager: bootstrap did not complete within its deadline (progress=\(self.bootstrapProgress)); network may be blocking Tor",
|
||||
category: .session
|
||||
)
|
||||
NotificationCenter.default.post(name: .TorBootstrapDidStall, object: nil)
|
||||
await MainActor.run {
|
||||
guard generation == self.bootstrapGeneration else { return }
|
||||
if self.isStarting { self.isStarting = false }
|
||||
if !self.bootstrapDidStall { self.bootstrapDidStall = true }
|
||||
SecureLogger.warning(
|
||||
"TorManager: bootstrap did not complete within its deadline (progress=\(self.bootstrapProgress)); network may be blocking Tor",
|
||||
category: .session
|
||||
)
|
||||
NotificationCenter.default.post(name: .TorBootstrapDidStall, object: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func getBootstrapSummary() -> String {
|
||||
nonisolated private static func readBootstrapSummary() -> String {
|
||||
var buf = [CChar](repeating: 0, count: 256)
|
||||
let len = arti_bootstrap_summary(&buf, Int32(buf.count))
|
||||
if len > 0 {
|
||||
@@ -360,12 +458,10 @@ public final class TorManager: ObservableObject {
|
||||
// iOS will suspend the runtime anyway. On foreground we do a full restart.
|
||||
// Clear isStarting so foreground recovery can proceed if bootstrap was interrupted.
|
||||
SecureLogger.debug("TorManager: goDormantOnBackground() called", category: .session)
|
||||
Task { @MainActor in
|
||||
self.bootstrapGeneration += 1
|
||||
self.isReady = false
|
||||
self.socksReady = false
|
||||
self.isStarting = false
|
||||
}
|
||||
bootstrapGeneration += 1
|
||||
isReady = false
|
||||
socksReady = false
|
||||
isStarting = false
|
||||
}
|
||||
|
||||
public func shutdownCompletely() {
|
||||
@@ -436,7 +532,7 @@ public final class TorManager: ObservableObject {
|
||||
try? FileManager.default.removeItem(at: dir)
|
||||
}
|
||||
|
||||
private func restartArti() async {
|
||||
nonisolated private func restartArti() async {
|
||||
SecureLogger.debug("TorManager: restartArti() starting", category: .session)
|
||||
await MainActor.run {
|
||||
NotificationCenter.default.post(name: .TorWillRestart, object: nil)
|
||||
@@ -452,7 +548,7 @@ public final class TorManager: ObservableObject {
|
||||
|
||||
_ = arti_stop()
|
||||
|
||||
// Wait for stop
|
||||
// Wait for stop off the main actor.
|
||||
var waited = 0
|
||||
while arti_is_running() != 0 && waited < 40 {
|
||||
try? await Task.sleep(nanoseconds: 100_000_000)
|
||||
@@ -462,9 +558,8 @@ public final class TorManager: ObservableObject {
|
||||
await MainActor.run {
|
||||
self.bootstrapMonitorStarted = false
|
||||
self.didStart = false
|
||||
self.startIfNeeded()
|
||||
}
|
||||
|
||||
await MainActor.run { self.startIfNeeded() }
|
||||
}
|
||||
|
||||
private func recomputeReady() {
|
||||
@@ -475,6 +570,7 @@ public final class TorManager: ObservableObject {
|
||||
}
|
||||
isReady = ready
|
||||
if ready {
|
||||
resumeAllReadyWaiters()
|
||||
NotificationCenter.default.post(name: .TorDidBecomeReady, object: nil)
|
||||
}
|
||||
}
|
||||
@@ -519,6 +615,25 @@ public final class TorManager: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
private final class AtomicOnceFlag: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var flag = false
|
||||
|
||||
var isSet: Bool {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return flag
|
||||
}
|
||||
|
||||
func trySet() -> Bool {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
guard !flag else { return false }
|
||||
flag = true
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Start policy configuration
|
||||
extension TorManager {
|
||||
@MainActor
|
||||
|
||||
Reference in new issue
Block a user