Add spatial Place Feed, Home Feed, BLE Gateway feed bridge, local WoT, Tor Blossom media, and 3D Globe beacons (#1934)

* Add spatial Place Feed, Home Feed, BLE Gateway feed bridge, local WoT, Tor Blossom media, and 3D Globe beacons

* Address PR #1934 review findings and Periphery dead-code scan

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
This commit is contained in:
jackandjack authored and GitHub committed 2026-11-28 13:41:13 -10:00
1 parent f20848740b
commit 1c63ae6cab
31 files changed
+19874 -227

No files matched your search

File diff suppressed because it is too large. Load diff
+548 -7
View File
@@ -19,6 +19,7 @@ struct NostrProtocol {
/// Nostr event kinds
enum EventKind: Int {
case metadata = 0 // NIP-01 user profile metadata
case textNote = 1
// BitChat's proprietary private-envelope layers. These reuse the
// NIP-17/NIP-59 kind numbers (14/13/1059) for historical reasons, but
@@ -29,6 +30,8 @@ struct NostrProtocol {
case ephemeralEvent = 20000
case geohashPresence = 20001
case deletion = 5 // NIP-09 event deletion request
case reaction = 7 // NIP-25 reaction
case blossomAuth = 24242 // BUD-01/02 Blossom upload authorization
/// Sealed courier envelope parked on relays under its rotating
/// recipient tag (`#x`). Regular (stored) kind so it survives until
/// its NIP-40 expiration — the whole point is store-and-forward.
@@ -384,17 +387,241 @@ struct NostrProtocol {
return try event.sign(with: schnorrKey)
}
/// Create a persistent location note (kind 1: text note) tagged to a street-level geohash.
/// An optional `expiresAt` adds a NIP-40 expiration tag so honoring relays
/// drop the note in step with a bridged board post's expiry.
/// NIP-10 thread reference extracted from or written to a kind-1 note's
/// `e` and `p` tags.
struct ThreadReference: Equatable, Sendable {
/// Event ID of the thread root post.
let rootEventID: String
/// Event ID of the direct parent when replying to a reply; nil (or
/// equal to `rootEventID`) for a direct reply to the root post.
let replyEventID: String?
/// Pubkey hex of the author being replied to (`p` tag), if known.
let replyAuthorPubkey: String?
init(rootEventID: String, replyEventID: String? = nil, replyAuthorPubkey: String? = nil) {
self.rootEventID = rootEventID.lowercased()
let normalizedReply = replyEventID?.lowercased()
self.replyEventID = (normalizedReply == self.rootEventID) ? nil : normalizedReply
self.replyAuthorPubkey = replyAuthorPubkey?.lowercased()
}
}
/// NIP-92 `imeta` attachment metadata for a Blossom content-addressed blob.
/// Strictly requires HTTPS and a 64-char SHA-256 hash so receivers can
/// verify downloaded bytes before decoding or displaying.
struct MediaAttachment: Equatable, Hashable, Sendable, Identifiable {
let url: URL
let mimeType: String
let sha256Hex: String
let sizeBytes: Int?
let dimensions: String?
var id: String { "\(sha256Hex)|\(url.absoluteString)" }
}
static let maxAttachmentsPerNote = 4
/// Encodes a `MediaAttachment` as a NIP-92 `imeta` tag.
static func imetaTag(for attachment: MediaAttachment) -> [String] {
var fields = [
"imeta",
"url \(attachment.url.absoluteString)",
"m \(attachment.mimeType)",
"x \(attachment.sha256Hex.lowercased())"
]
if let size = attachment.sizeBytes, size > 0 {
fields.append("size \(size)")
}
if let dim = attachment.dimensions?.trimmedOrNilIfEmpty {
fields.append("dim \(dim)")
}
return fields
}
/// Parses up to `maxAttachmentsPerNote` validated NIP-92 `imeta` tags.
/// Rejects non-HTTPS URLs, local/private hosts, and attachments missing a
/// valid 64-character SHA-256 digest (`x`).
static func parseMediaAttachments(from tags: [[String]]) -> [MediaAttachment] {
var attachments: [MediaAttachment] = []
var seenHashes = Set<String>()
for tag in tags where tag.count >= 2 && tag[0].lowercased() == "imeta" {
var urlString: String?
var mimeType = "image/jpeg"
var sha256Hex: String?
var sizeBytes: Int?
var dimensions: String?
for field in tag.dropFirst() {
guard let spaceIdx = field.firstIndex(of: " ") else { continue }
let key = field[..<spaceIdx].lowercased()
let value = String(field[field.index(after: spaceIdx)...]).trimmingCharacters(in: .whitespacesAndNewlines)
guard !value.isEmpty else { continue }
switch key {
case "url":
urlString = value
case "m":
if value.count <= 64 { mimeType = value.lowercased() }
case "x":
let lower = value.lowercased()
if lower.count == 64, isValidHexIdentifier(lower) {
sha256Hex = lower
}
case "size":
if let parsed = Int(value), parsed > 0 { sizeBytes = parsed }
case "dim":
if value.count <= 24 { dimensions = value }
default:
break
}
}
guard let urlString,
let url = validatedRemoteHTTPSURL(urlString),
let sha256Hex,
mimeType.hasPrefix("image/"),
seenHashes.insert(sha256Hex).inserted else {
continue
}
attachments.append(MediaAttachment(
url: url,
mimeType: mimeType,
sha256Hex: sha256Hex,
sizeBytes: sizeBytes,
dimensions: dimensions
))
if attachments.count >= maxAttachmentsPerNote {
break
}
}
return attachments
}
/// Creates a signed BUD-02 Blossom upload authorization event (kind 24242).
static func createBlossomUploadAuthEvent(
sha256Hex: String,
expiration: Date,
senderIdentity: NostrIdentity,
createdAt: Date = Date()
) throws -> NostrEvent {
let normalizedHash = sha256Hex.lowercased()
guard normalizedHash.count == 64, isValidHexIdentifier(normalizedHash) else {
throw NostrError.invalidEvent
}
let tags = [
["t", "upload"],
["x", normalizedHash],
["expiration", String(Int(expiration.timeIntervalSince1970))]
]
let event = NostrEvent(
pubkey: senderIdentity.publicKeyHex,
createdAt: createdAt,
kind: .blossomAuth,
tags: tags,
content: "Upload blob"
)
let schnorrKey = try senderIdentity.schnorrSigningKey()
return try event.sign(with: schnorrKey)
}
static func validatedRemoteHTTPSURL(_ raw: String) -> URL? {
guard raw.count <= 1024,
let url = URL(string: raw),
url.scheme?.lowercased() == "https",
let host = url.host?.lowercased(),
!host.isEmpty,
host != "localhost",
!host.hasSuffix(".localhost"),
!host.hasSuffix(".local"),
!host.hasSuffix(".internal"),
!host.hasPrefix("127."),
!host.hasPrefix("10."),
!host.hasPrefix("192.168."),
host != "::1" else {
return nil
}
return url
}
/// Minimum committed NIP-13 leading-zero bit count required for a note to
/// carry the verified-PoW feed badge or match the PoW feed filter.
static let verifiedPoWThresholdBits = 8
/// Passive read-only NIP-13 proof-of-work validator for inbound events.
/// Returns the committed target difficulty if the event carries a valid
/// `["nonce", <nonce>, <target>]` tag and its `idHex` meets at least that
/// many leading zero bits; otherwise returns 0.
static func validatedPoWDifficulty(idHex: String, tags: [[String]]) -> Int {
guard let nonceTag = tags.first(where: { $0.count >= 3 && $0[0] == "nonce" }),
let committed = Int(nonceTag[2]),
committed > 0, committed <= 256 else {
return 0
}
guard let idData = Data(hexString: idHex), idData.count == 32 else {
return 0
}
var leadingZeros = 0
for byte in idData {
if byte == 0 {
leadingZeros += 8
} else {
leadingZeros += byte.leadingZeroBitCount
break
}
}
return leadingZeros >= committed ? committed : 0
}
/// Create a persistent location note (kind 1: text note) tagged to a geohash.
/// Supports optional NIP-40 expiration, urgency, teleport marker, NIP-10
/// thread reply tags, NIP-92 `imeta` attachments, and extra tags.
static func createGeohashTextNote(
content: String,
geohash: String,
senderIdentity: NostrIdentity,
nickname: String? = nil,
expiresAt: Date? = nil,
urgent: Bool = false
urgent: Bool = false,
replyTo: ThreadReference? = nil,
teleported: Bool = false,
attachments: [MediaAttachment] = [],
createdAt: Date = Date(),
extraTags: [[String]] = []
) throws -> NostrEvent {
var tags = geohashTextNoteTags(
geohash: geohash,
nickname: nickname,
expiresAt: expiresAt,
urgent: urgent,
replyTo: replyTo,
teleported: teleported
)
for attachment in attachments.prefix(maxAttachmentsPerNote) {
tags.append(imetaTag(for: attachment))
}
if !extraTags.isEmpty {
tags.append(contentsOf: extraTags)
}
let event = NostrEvent(
pubkey: senderIdentity.publicKeyHex,
createdAt: createdAt,
kind: .textNote,
tags: tags,
content: content
)
let schnorrKey = try senderIdentity.schnorrSigningKey()
return try event.sign(with: schnorrKey)
}
private static func geohashTextNoteTags(
geohash: String,
nickname: String?,
expiresAt: Date?,
urgent: Bool,
replyTo: ThreadReference?,
teleported: Bool
) -> [[String]] {
var tags = [["g", geohash]]
if let nickname = nickname?.trimmedOrNilIfEmpty {
tags.append(["n", nickname])
@@ -405,9 +632,277 @@ struct NostrProtocol {
if urgent {
tags.append(["t", "urgent"])
}
if teleported {
tags.append(["t", "teleport"])
}
if let replyTo, isValidHexIdentifier(replyTo.rootEventID) {
tags.append(["e", replyTo.rootEventID, "", "root"])
if let directReply = replyTo.replyEventID,
directReply != replyTo.rootEventID,
isValidHexIdentifier(directReply) {
tags.append(["e", directReply, "", "reply"])
}
if let authorPubkey = replyTo.replyAuthorPubkey,
isValidHexIdentifier(authorPubkey) {
tags.append(["p", authorPubkey])
}
}
return tags
}
/// Create a NIP-25 reaction (kind 7) targeting a note inside a geohash feed.
/// Carries the place's `g` tag so the single per-place relay subscription
/// receives both posts and reactions without extra Tor socket overhead.
static func createGeohashReactionEvent(
emoji: String,
targetEventID: String,
targetAuthorPubkey: String?,
geohash: String,
senderIdentity: NostrIdentity,
createdAt: Date = Date()
) throws -> NostrEvent {
let normalizedEmoji = normalizeReactionContent(emoji) ?? "❤️"
var tags = [
["g", geohash],
["e", targetEventID.lowercased()]
]
if let author = targetAuthorPubkey?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(),
isValidHexIdentifier(author) {
tags.append(["p", author])
}
let event = NostrEvent(
pubkey: senderIdentity.publicKeyHex,
createdAt: Date(),
createdAt: createdAt,
kind: .reaction,
tags: tags,
content: normalizedEmoji
)
let schnorrKey = try senderIdentity.schnorrSigningKey()
return try event.sign(with: schnorrKey)
}
/// Parse a NIP-10 thread reference from a kind-1 note's tags.
/// Prefers marked `e` tags (`root` / `reply`, ignoring `mention`); falls
/// back to positional `e` tags when no markers are present.
static func parseThreadReference(from tags: [[String]]) -> ThreadReference? {
var markedRoot: String?
var markedReply: String?
var positionalEventIDs: [String] = []
var replyAuthorPubkey: String?
for tag in tags where tag.count >= 2 {
let key = tag[0].lowercased()
switch key {
case "e":
let candidate = tag[1].trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
guard isValidHexIdentifier(candidate) else { continue }
let marker = tag.count >= 4
? tag[3].trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
: ""
switch marker {
case "root":
if markedRoot == nil { markedRoot = candidate }
case "reply":
markedReply = candidate
case "mention":
continue
default:
positionalEventIDs.append(candidate)
}
case "p":
let candidate = tag[1].trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
if isValidHexIdentifier(candidate) {
replyAuthorPubkey = candidate
}
default:
break
}
}
if let root = markedRoot {
return ThreadReference(
rootEventID: root,
replyEventID: markedReply,
replyAuthorPubkey: replyAuthorPubkey
)
}
if let replyOnly = markedReply {
// Some clients emit only a single "reply" marker on direct replies.
return ThreadReference(
rootEventID: replyOnly,
replyEventID: nil,
replyAuthorPubkey: replyAuthorPubkey
)
}
if let first = positionalEventIDs.first {
let last = positionalEventIDs.count > 1 ? positionalEventIDs.last : nil
return ThreadReference(
rootEventID: first,
replyEventID: last,
replyAuthorPubkey: replyAuthorPubkey
)
}
return nil
}
/// Parse a NIP-25 kind-7 reaction event into its target event ID (first
/// valid `e` tag, ignoring any additional appended `e` tags) and normalized
/// display emoji.
static func parseReactionTarget(from event: NostrEvent) -> (targetEventID: String, emoji: String)? {
guard event.kind == EventKind.reaction.rawValue,
let emoji = normalizeReactionContent(event.content) else {
return nil
}
for tag in event.tags where tag.count >= 2 && tag[0].lowercased() == "e" {
let candidate = tag[1].trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
if isValidHexIdentifier(candidate) {
return (candidate, emoji)
}
}
return nil
}
/// Normalizes NIP-25 reaction content: empty or `"+"` maps to `"❤️"`,
/// `"-"` is ignored, and custom emoji strings are restricted to a single
/// emoji grapheme cluster so arbitrary text cannot render as an emoji chip.
static func normalizeReactionContent(_ raw: String) -> String? {
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.isEmpty || trimmed == "+" {
return "❤️"
}
if trimmed == "-" {
return nil
}
guard trimmed.count == 1, trimmed.utf8.count <= 16 else {
return nil
}
let hasEmojiScalar = trimmed.unicodeScalars.contains { scalar in
scalar.properties.isEmojiPresentation
|| (scalar.properties.isEmoji && !scalar.isASCII)
|| scalar.value == 0xFE0F
}
guard hasEmojiScalar else {
return nil
}
return trimmed
}
/// Sanitized NIP-01 kind-0 profile metadata. Intentionally excludes remote
/// avatar/banner URLs so reading profiles never triggers clearnet image
/// fetches or IP leaks in Stealth Mode.
struct ProfileMetadata: Codable, Equatable, Sendable {
let name: String?
let displayName: String?
let about: String?
let nip05: String?
var preferredName: String? {
displayName?.trimmedOrNilIfEmpty ?? name?.trimmedOrNilIfEmpty
}
private enum CodingKeys: String, CodingKey {
case name
case displayName = "display_name"
case about
case nip05
}
}
/// Defensive upper bound on untrusted kind-0 metadata JSON content.
static let maximumProfileMetadataBytes = 8 * 1024
/// Create a signed NIP-01 kind-0 metadata event for an opt-in persistent
/// Nostr public handle.
static func createMetadataEvent(
profile: ProfileMetadata,
senderIdentity: NostrIdentity,
createdAt: Date = Date()
) throws -> NostrEvent {
var payload: [String: String] = [:]
if let name = sanitizeMetadataField(profile.name, maxLength: 64, allowNewlines: false) {
payload["name"] = name
}
if let displayName = sanitizeMetadataField(profile.displayName, maxLength: 64, allowNewlines: false) {
payload["display_name"] = displayName
}
if let about = sanitizeMetadataField(profile.about, maxLength: 280, allowNewlines: true) {
payload["about"] = about
}
if let nip05 = sanitizeMetadataField(profile.nip05, maxLength: 120, allowNewlines: false) {
payload["nip05"] = nip05
}
let data = try JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys, .withoutEscapingSlashes])
let content = String(data: data, encoding: .utf8) ?? "{}"
let event = NostrEvent(
pubkey: senderIdentity.publicKeyHex,
createdAt: createdAt,
kind: .metadata,
tags: [],
content: content
)
let schnorrKey = try senderIdentity.schnorrSigningKey()
return try event.sign(with: schnorrKey)
}
/// Parse and sanitize a NIP-01 kind-0 profile metadata event.
static func parseMetadataEvent(_ event: NostrEvent) -> ProfileMetadata? {
guard event.kind == EventKind.metadata.rawValue,
event.content.utf8.count <= maximumProfileMetadataBytes,
let data = event.content.data(using: .utf8),
let dict = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
return nil
}
let name = sanitizeMetadataField(dict["name"] as? String, maxLength: 64, allowNewlines: false)
let displayName = sanitizeMetadataField(dict["display_name"] as? String, maxLength: 64, allowNewlines: false)
let about = sanitizeMetadataField(dict["about"] as? String, maxLength: 280, allowNewlines: true)
let nip05 = sanitizeMetadataField(dict["nip05"] as? String, maxLength: 120, allowNewlines: false)
guard name != nil || displayName != nil || about != nil || nip05 != nil else {
return nil
}
return ProfileMetadata(
name: name,
displayName: displayName,
about: about,
nip05: nip05
)
}
/// Create a global (non-geohash) kind-1 text note signed synchronously by a
/// persistent public handle, with optional NIP-10 reply tags and NIP-92 `imeta`.
static func createPublicTextNote(
content: String,
senderIdentity: NostrIdentity,
nickname: String? = nil,
expiresAt: Date? = nil,
replyTo: ThreadReference? = nil,
attachments: [MediaAttachment] = [],
createdAt: Date = Date()
) throws -> NostrEvent {
var tags: [[String]] = []
if let nickname = nickname?.trimmedOrNilIfEmpty {
tags.append(["n", nickname])
}
if let expiresAt {
tags.append(["expiration", String(Int(expiresAt.timeIntervalSince1970))])
}
if let replyTo, isValidHexIdentifier(replyTo.rootEventID) {
tags.append(["e", replyTo.rootEventID, "", "root"])
if let directReply = replyTo.replyEventID,
directReply != replyTo.rootEventID,
isValidHexIdentifier(directReply) {
tags.append(["e", directReply, "", "reply"])
}
if let authorPubkey = replyTo.replyAuthorPubkey,
isValidHexIdentifier(authorPubkey) {
tags.append(["p", authorPubkey])
}
}
for attachment in attachments.prefix(maxAttachmentsPerNote) {
tags.append(imetaTag(for: attachment))
}
let event = NostrEvent(
pubkey: senderIdentity.publicKeyHex,
createdAt: createdAt,
kind: .textNote,
tags: tags,
content: content
@@ -416,18 +911,64 @@ struct NostrProtocol {
return try event.sign(with: schnorrKey)
}
/// Decode either a 64-character hex pubkey or a `npub1...` Bech32 string
/// into canonical lowercase 64-char hex.
static func normalizePubkeyHex(_ raw: String) -> String? {
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return nil }
let lower = trimmed.lowercased()
if lower.hasPrefix("npub1") {
guard let (hrp, data) = try? Bech32.decode(lower),
hrp == "npub",
data.count == 32 else {
return nil
}
return data.hexEncodedString().lowercased()
}
guard lower.count == 64, isValidHexIdentifier(lower) else {
return nil
}
return lower
}
private static func sanitizeMetadataField(_ raw: String?, maxLength: Int, allowNewlines: Bool) -> String? {
guard let raw else { return nil }
let disallowed = allowNewlines
? CharacterSet.controlCharacters.subtracting(.newlines)
: CharacterSet.controlCharacters.union(.newlines)
var cleaned = ""
cleaned.unicodeScalars.append(contentsOf: raw.unicodeScalars.filter { !disallowed.contains($0) })
cleaned = cleaned.trimmingCharacters(in: .whitespacesAndNewlines)
guard !cleaned.isEmpty else { return nil }
return String(cleaned.prefix(maxLength))
}
private static func isValidHexIdentifier(_ value: String) -> Bool {
guard !value.isEmpty, value.count <= 64 else { return false }
return value.utf8.allSatisfy { byte in
(byte >= 0x30 && byte <= 0x39)
|| (byte >= 0x61 && byte <= 0x66)
|| (byte >= 0x41 && byte <= 0x46)
}
}
/// Create a NIP-09 deletion request for one of our own events. Relays that
/// honor NIP-09 drop the referenced event; it must be signed by the same
/// key that signed the original.
static func createDeleteEvent(
ofEventID eventID: String,
senderIdentity: NostrIdentity
senderIdentity: NostrIdentity,
geohash: String? = nil
) throws -> NostrEvent {
var tags: [[String]] = [["e", eventID]]
if let geohash = geohash?.trimmedOrNilIfEmpty {
tags.append(["g", geohash.lowercased()])
}
let event = NostrEvent(
pubkey: senderIdentity.publicKeyHex,
createdAt: Date(),
kind: .deletion,
tags: [["e", eventID]],
tags: tags,
content: ""
)
let schnorrKey = try senderIdentity.schnorrSigningKey()
+36
View File
@@ -91,6 +91,42 @@ struct NostrFilter: Encodable {
return filter
}
// For Place Feed: kind-1 notes/replies and kind-7 NIP-25 reactions on one
// For Place Feed: fetches kind-1 notes/replies, kind-7 NIP-25 reactions,
// and kind-5 NIP-09 deletions in one per-place relay subscription (avoids
// opening extra sockets/REQs over Tor).
static func geohashFeed(_ geohashes: [String], since: Date? = nil, limit: Int = 200) -> NostrFilter {
var filter = NostrFilter()
filter.kinds = [
NostrProtocol.EventKind.textNote.rawValue,
NostrProtocol.EventKind.reaction.rawValue,
NostrProtocol.EventKind.deletion.rawValue
]
filter.since = since?.timeIntervalSince1970.toInt()
filter.tagFilters = ["g": geohashes]
filter.limit = limit
return filter
}
// For Following Home Feed: kind-1 notes from followed pubkeys on default relays.
static func authorNotes(_ pubkeys: [String], since: Date? = nil, limit: Int = 150) -> NostrFilter {
var filter = NostrFilter()
filter.kinds = [NostrProtocol.EventKind.textNote.rawValue]
filter.authors = pubkeys
filter.since = since?.timeIntervalSince1970.toInt()
filter.limit = limit
return filter
}
// For NIP-01 kind-0 profile metadata batch lookups.
static func authorProfiles(_ pubkeys: [String], limit: Int? = nil) -> NostrFilter {
var filter = NostrFilter()
filter.kinds = [NostrProtocol.EventKind.metadata.rawValue]
filter.authors = pubkeys
filter.limit = limit ?? max(pubkeys.count * 2, 20)
return filter
}
// For the mesh bridge: rendezvous messages (kind 20000) and presence
// (kind 20001) tagged `#r` with one or more cells (own + neighbors).
static func bridgeRendezvous(_ cells: [String], since: Date? = nil, limit: Int = 200) -> NostrFilter {
+357
View File
@@ -0,0 +1,357 @@
//
// BlossomMediaService.swift
// bitchat
//
// BUD-01/BUD-02 Blossom media upload and SHA-256-verified image download
// routed fail-closed through TorURLSession when Tor is enabled.
// Strips all EXIF/GPS metadata on upload and validates container dimensions
// + cryptographic SHA-256 digest before rendering any remote image.
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import BitFoundation
import BitLogger
import Foundation
import ImageIO
import Tor
import UniformTypeIdentifiers
#if os(iOS)
import UIKit
#else
import AppKit
#endif
enum BlossomMediaError: Error, LocalizedError, Equatable {
case torNotReady
case networkDisabled
case invalidServerURL
case invalidImage
case payloadTooLarge
case uploadFailed(Int)
case invalidResponse
case hashMismatch
var errorDescription: String? {
switch self {
case .torNotReady:
return "Tor is still connecting"
case .networkDisabled:
return "Network access is currently disabled"
case .invalidServerURL:
return "Invalid Blossom server URL"
case .invalidImage:
return "Could not process image"
case .payloadTooLarge:
return "Media exceeds size limit"
case .uploadFailed(let status):
return "Upload failed (HTTP \(status))"
case .invalidResponse:
return "Invalid Blossom server response"
case .hashMismatch:
return "Downloaded media failed SHA-256 integrity check"
}
}
}
struct BlossomMediaDependencies {
var awaitTorReady: @Sendable () async -> Bool
var isNetworkActivationAllowed: @MainActor () -> Bool
var performRequest: @Sendable (URLRequest, Int) async throws -> (Data, Int)
var now: () -> Date
static let live = BlossomMediaDependencies(
awaitTorReady: {
guard NetworkActivationService.persistedTorPreference() else { return true }
return await TorManager.shared.awaitReady()
},
isNetworkActivationAllowed: {
NetworkActivationService.shared.activationAllowed
},
performRequest: { request, maxBytes in
let session = await MainActor.run { TorURLSession.shared.session }
let (bytes, response) = try await session.bytes(for: request)
let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0
var buffer = Data()
for try await byte in bytes {
if buffer.count >= maxBytes {
throw BlossomMediaError.payloadTooLarge
}
buffer.append(byte)
}
return (buffer, statusCode)
},
now: Date.init
)
}
@MainActor
final class BlossomMediaService {
static let shared = BlossomMediaService()
nonisolated static let defaultServerURLString = "https://blossom.primal.net"
nonisolated static let serverURLKey = "bitchat.blossom.serverURL"
nonisolated static let maxUploadDimension: CGFloat = 1_024
nonisolated static let maxUploadBytes = 512 * 1024
nonisolated static let maxDownloadBytes = 4 * 1024 * 1024
private static let authExpirySeconds: TimeInterval = 5 * 60
private final class VerifiedImageCache: @unchecked Sendable {
private let lock = NSLock()
private var generation: UInt64 = 0
private let cache: NSCache<NSString, ImageDownsampler.PlatformImage> = {
let c = NSCache<NSString, ImageDownsampler.PlatformImage>()
c.countLimit = 32
c.totalCostLimit = 24 * 1024 * 1024
return c
}()
func lookup(_ key: String) -> (image: ImageDownsampler.PlatformImage?, generation: UInt64) {
lock.lock()
defer { lock.unlock() }
return (cache.object(forKey: key as NSString), generation)
}
func store(_ image: ImageDownsampler.PlatformImage, for key: String, cost: Int, expectedGeneration: UInt64) {
lock.lock()
defer { lock.unlock() }
guard generation == expectedGeneration else { return }
cache.setObject(image, forKey: key as NSString, cost: cost)
}
func reset() {
lock.lock()
defer { lock.unlock() }
generation &+= 1
cache.removeAllObjects()
}
}
private let cache = VerifiedImageCache()
private let defaults: UserDefaults
private let dependencies: BlossomMediaDependencies
init(
defaults: UserDefaults = .standard,
dependencies: BlossomMediaDependencies = .live
) {
self.defaults = defaults
self.dependencies = dependencies
}
var serverURLString: String {
get {
defaults.string(forKey: Self.serverURLKey)?.trimmedOrNilIfEmpty ?? Self.defaultServerURLString
}
set {
let trimmed = newValue.trimmed
if trimmed.isEmpty {
defaults.removeObject(forKey: Self.serverURLKey)
} else {
defaults.set(trimmed, forKey: Self.serverURLKey)
}
}
}
func cachedImage(for sha256Hex: String) -> ImageDownsampler.PlatformImage? {
cache.lookup(sha256Hex.lowercased()).image
}
/// Strips all EXIF/GPS metadata by re-rendering a clean JPEG bitmap capped
/// to `maxUploadDimension` and `maxUploadBytes`.
nonisolated static func stripMetadataAndCompressJPEG(
from imageData: Data,
maxDimension: CGFloat = maxUploadDimension
) -> (jpegData: Data, width: Int, height: Int)? {
guard !imageData.isEmpty, imageData.count <= 16 * 1024 * 1024 else { return nil }
let options = [kCGImageSourceShouldCache: false] as CFDictionary
guard let source = CGImageSourceCreateWithData(imageData as CFData, options),
ImageContainerValidator.validateDimensions(
of: source,
maxDimensionPixels: ImageUtils.maxSourceDimensionPixels,
maxTotalPixels: ImageUtils.maxSourceTotalPixels
) == nil else {
return nil
}
let thumbOptions: [CFString: Any] = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceShouldCacheImmediately: false,
kCGImageSourceThumbnailMaxPixelSize: max(1, Int(ceil(maxDimension)))
]
guard let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, thumbOptions as CFDictionary) else {
return nil
}
var quality: CGFloat = 0.80
while quality >= 0.30 {
if let encoded = encodeCleanJPEG(cgImage: cgImage, quality: quality),
encoded.count <= maxUploadBytes {
return (encoded, cgImage.width, cgImage.height)
}
quality -= 0.12
}
return nil
}
nonisolated private static func encodeCleanJPEG(cgImage: CGImage, quality: CGFloat) -> Data? {
let mutable = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(
mutable,
UTType.jpeg.identifier as CFString,
1,
nil
) else {
return nil
}
// Only write compression quality — no EXIF, GPS, TIFF, or MakerNote dictionaries.
let properties = [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary
CGImageDestinationAddImage(destination, cgImage, properties)
guard CGImageDestinationFinalize(destination) else { return nil }
return mutable as Data
}
/// Uploads EXIF-stripped JPEG bytes to the configured Blossom server using
/// a signed BUD-02 kind-24242 auth header over Tor (fail-closed when Tor is on).
func uploadImage(
rawData: Data,
senderIdentity: NostrIdentity
) async throws -> NostrProtocol.MediaAttachment {
guard dependencies.isNetworkActivationAllowed() else {
throw BlossomMediaError.networkDisabled
}
guard await dependencies.awaitTorReady() else {
throw BlossomMediaError.torNotReady
}
guard let baseURL = NostrProtocol.validatedRemoteHTTPSURL(serverURLString) else {
throw BlossomMediaError.invalidServerURL
}
guard let processed = await Task.detached(priority: .userInitiated, operation: {
Self.stripMetadataAndCompressJPEG(from: rawData)
}).value else {
throw BlossomMediaError.invalidImage
}
let sha256Hex = processed.jpegData.sha256Fingerprint()
let now = dependencies.now()
let authEvent = try NostrProtocol.createBlossomUploadAuthEvent(
sha256Hex: sha256Hex,
expiration: now.addingTimeInterval(Self.authExpirySeconds),
senderIdentity: senderIdentity,
createdAt: now
)
let authJSON = try authEvent.jsonString()
let authHeader = "Nostr " + Data(authJSON.utf8).base64EncodedString()
let uploadURL = baseURL.appendingPathComponent("upload")
var request = URLRequest(url: uploadURL)
request.httpMethod = "PUT"
request.httpBody = processed.jpegData
request.timeoutInterval = 30
request.setValue("image/jpeg", forHTTPHeaderField: "Content-Type")
request.setValue(authHeader, forHTTPHeaderField: "Authorization")
let (responseData, statusCode) = try await dependencies.performRequest(request, 64 * 1024)
guard (200...299).contains(statusCode) else {
throw BlossomMediaError.uploadFailed(statusCode)
}
guard let json = try? JSONSerialization.jsonObject(with: responseData) as? [String: Any],
let returnedURLString = json["url"] as? String,
let returnedURL = NostrProtocol.validatedRemoteHTTPSURL(returnedURLString) else {
throw BlossomMediaError.invalidResponse
}
let returnedHash = (json["sha256"] as? String)?.lowercased() ?? sha256Hex
guard returnedHash == sha256Hex else {
throw BlossomMediaError.hashMismatch
}
return NostrProtocol.MediaAttachment(
url: returnedURL,
mimeType: "image/jpeg",
sha256Hex: sha256Hex,
sizeBytes: processed.jpegData.count,
dimensions: "\(processed.width)x\(processed.height)"
)
}
/// Downloads a remote Blossom image over Tor (when enabled), verifies its
/// exact SHA-256 digest against `attachment.sha256Hex`, validates image
/// dimensions, and caches the downsampled result in RAM.
func fetchVerifiedImage(for attachment: NostrProtocol.MediaAttachment) async throws -> ImageDownsampler.PlatformImage {
let key = attachment.sha256Hex.lowercased()
let lookup = cache.lookup(key)
if let cached = lookup.image {
return cached
}
let generation = lookup.generation
guard dependencies.isNetworkActivationAllowed() else {
throw BlossomMediaError.networkDisabled
}
guard await dependencies.awaitTorReady() else {
throw BlossomMediaError.torNotReady
}
guard NostrProtocol.validatedRemoteHTTPSURL(attachment.url.absoluteString) != nil else {
throw BlossomMediaError.invalidServerURL
}
var request = URLRequest(url: attachment.url)
request.httpMethod = "GET"
request.timeoutInterval = 30
let (data, statusCode) = try await dependencies.performRequest(request, Self.maxDownloadBytes)
guard (200...299).contains(statusCode) else {
throw BlossomMediaError.uploadFailed(statusCode)
}
guard data.sha256Fingerprint() == key else {
throw BlossomMediaError.hashMismatch
}
guard let decoded = await Task.detached(priority: .userInitiated, operation: {
Self.decodeDownsampledCGImage(from: data, maxPixelSize: ImageDownsampler.inlineMaxPixelSize)
}).value else {
throw BlossomMediaError.invalidImage
}
let image: ImageDownsampler.PlatformImage
#if os(iOS)
image = UIImage(cgImage: decoded.cgImage)
#else
image = NSImage(
cgImage: decoded.cgImage,
size: NSSize(width: decoded.cgImage.width, height: decoded.cgImage.height)
)
#endif
cache.store(image, for: key, cost: decoded.cost, expectedGeneration: generation)
return image
}
nonisolated private static func decodeDownsampledCGImage(
from data: Data,
maxPixelSize: Int
) -> (cgImage: CGImage, cost: Int)? {
let sourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
guard let source = CGImageSourceCreateWithData(data as CFData, sourceOptions),
ImageContainerValidator.validateDimensions(of: source) == nil else {
return nil
}
let thumbOptions: [CFString: Any] = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceThumbnailMaxPixelSize: maxPixelSize
]
guard let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, thumbOptions as CFDictionary) else {
return nil
}
let cost = max(1, cgImage.width * cgImage.height * 4)
return (cgImage, cost)
}
/// Panic-wipe hook: clears cached decrypted/verified remote images and
/// resets any custom Blossom server preference.
func resetForPanic() {
cache.reset()
defaults.removeObject(forKey: Self.serverURLKey)
}
}
@@ -33,6 +33,41 @@ struct NoticeItem: Identifiable, Equatable {
return false
}
var nostrNote: LocationNotesManager.Note? {
if case .nostr(let note) = source { return note }
return nil
}
var authorSuffix: String? {
switch source {
case .nostr(let note):
return note.authorSuffix
case .board(let post):
return String(post.authorSigningKey.hexEncodedString().suffix(4))
}
}
var authorColorSeed: String {
switch source {
case .nostr(let note):
return note.pubkey
case .board(let post):
return post.authorSigningKey.hexEncodedString()
}
}
var powDifficulty: Int {
nostrNote?.powDifficulty ?? 0
}
var hasVerifiedPoW: Bool {
isBoardPost || powDifficulty >= NostrProtocol.verifiedPoWThresholdBits
}
var isTeleported: Bool {
nostrNote?.isTeleported ?? false
}
init(post: BoardPostPacket) {
id = post.postID.hexEncodedString()
author = post.authorNickname.trimmedOrNilIfEmpty ?? "anon"
+31 -10
View File
@@ -99,9 +99,12 @@ final class GatewayService: ObservableObject {
var relaysConnected: (@MainActor () -> Bool)?
/// The geohash channel the local user is viewing, if any.
var currentGeohash: (@MainActor () -> String?)?
/// Injects a verified carried event into the same inbound pipeline as
/// relay-received events (blocking, rate limits, dedup, rendering).
/// Injects a verified carried ephemeral chat event into the same inbound
/// pipeline as relay-received events (blocking, rate limits, dedup, rendering).
var injectInbound: (@MainActor (NostrEvent) -> Void)?
/// Injects a verified carried feed event (kind-1 post/reply or kind-7
/// reaction) into active Place Feed managers (`LocationNotesPool`).
var injectFeedInbound: (@MainActor (NostrEvent, String) -> Void)?
/// Fired on toggle changes (advertise/withdraw the capability bit and
/// force a re-announce).
var onEnabledChanged: (@MainActor (Bool) -> Void)?
@@ -231,8 +234,8 @@ final class GatewayService: ObservableObject {
// publish or queue: a quota-dropped deposit is never published and,
// being directed, no other peer will ever see it, so showing it would
// diverge our timeline permanently from what reached the channel.
if accepted, currentGeohash?() == carrier.geohash {
injectInbound?(event)
if accepted {
deliverCarriedEvent(event, geohash: carrier.geohash)
}
}
@@ -258,7 +261,7 @@ final class GatewayService: ObservableObject {
/// the mesh, within the airtime budget.
func rebroadcastRelayEvent(_ event: NostrEvent, geohash: String, signatureAlreadyVerified: Bool = false) {
guard isEnabled, broadcastToMesh != nil else { return }
guard event.kind == NostrProtocol.EventKind.ephemeralEvent.rawValue else { return }
guard Self.supportedCarriedKinds.contains(event.kind) else { return }
// Freshness + geohash gate BEFORE spending any budget. A channel
// (re)subscribe backfills up to an hour of history (limit 200), but
// every receiver's `validatedEvent` drops anything older than the
@@ -311,10 +314,18 @@ final class GatewayService: ObservableObject {
// paths injects once (the pipeline's Nostr event-ID cache additionally
// dedups against our own relay subscription).
guard relayEngine.meshBroadcastEventIDs.insert(event.id) else { return }
// Only inject events for the channel we're viewing; the inbound
// pipeline files public messages under the current geohash.
guard currentGeohash?() == carrier.geohash else { return }
injectInbound?(event)
deliverCarriedEvent(event, geohash: carrier.geohash)
}
private func deliverCarriedEvent(_ event: NostrEvent, geohash: String) {
if event.kind == NostrProtocol.EventKind.ephemeralEvent.rawValue {
// Live ephemeral chat only injects for the channel currently viewed.
guard currentGeohash?() == geohash else { return }
injectInbound?(event)
} else if event.kind == NostrProtocol.EventKind.textNote.rawValue
|| event.kind == NostrProtocol.EventKind.reaction.rawValue {
injectFeedInbound?(event, geohash)
}
}
// MARK: - Uplink (sender role: mesh-only peer with no relays)
@@ -360,6 +371,16 @@ final class GatewayService: ObservableObject {
return event
}
/// Event kinds permitted across the BLE <-> Nostr gateway carrier:
/// kind 20000 (ephemeral geohash chat), kind 1 (Place Feed posts & NIP-10
/// replies), and kind 7 (NIP-25 reactions). All other kinds (DMs, profiles,
/// courier drops) are rejected.
static let supportedCarriedKinds: Set<Int> = [
NostrProtocol.EventKind.ephemeralEvent.rawValue,
NostrProtocol.EventKind.textNote.rawValue,
NostrProtocol.EventKind.reaction.rawValue
]
/// The cheap half of `validatedEvent`: parse + size + geohash + kind +
/// `#g` tag + freshness, with NO signature verification. Callers that can
/// dedup or rate-limit on the carried ID run this first so the expensive
@@ -368,7 +389,7 @@ final class GatewayService: ObservableObject {
guard carrier.eventJSON.count <= NostrCarrierPacket.maxEventJSONBytes,
Self.isValidGeohash(carrier.geohash),
let event = carrier.event(),
event.kind == NostrProtocol.EventKind.ephemeralEvent.rawValue,
Self.supportedCarriedKinds.contains(event.kind),
event.tags.contains(where: { $0.count >= 2 && $0[0] == "g" && $0[1] == carrier.geohash }),
relayEngine.isFresh(event) else {
return nil
@@ -123,6 +123,20 @@ final class GeohashChatActivityTracker: ObservableObject {
return best
}
/// Snapshot of currently active geohashes and their recent message counts
/// within the activity window (used by the 3D globe live activity layer).
func activeGeohashCounts() -> [String: Int] {
let cutoff = now().addingTimeInterval(-window)
var counts: [String: Int] = [:]
for (gh, times) in messageTimes {
let activeCount = times.reduce(0) { $1 >= cutoff ? $0 + 1 : $0 }
if activeCount > 0 {
counts[gh] = activeCount
}
}
return counts
}
func clear() {
messageTimes.removeAll()
lastMessages.removeAll()
+593
View File
@@ -0,0 +1,593 @@
//
// HomeFeedManager.swift
// bitchat
//
// Aggregates a Tor-friendly merged Home Feed across:
// 1. Saved Places (bookmarked geohashes, pooled via LocationNotesPool so open
// Place rooms and Home Feed share the same subscriptions).
// 2. Following (a single bounded `authors` kind-1 REQ on default relays,
// avoiding heavy NIP-65 multi-relay fan-out over Tor).
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import BitLogger
import Combine
import Foundation
struct HomeFeedDependencies {
typealias AcquirePlaceManager = @MainActor (_ geohash: String) -> LocationNotesManager
typealias ReleasePlaceManager = @MainActor (_ manager: LocationNotesManager?) -> Void
typealias SubscribeDefaultRelays = @MainActor (_ filter: NostrFilter, _ id: String, _ handler: @escaping (NostrEvent) -> Void, _ onEOSE: (() -> Void)?) -> Void
typealias Unsubscribe = @MainActor (_ id: String) -> Void
typealias SendDefaultRelays = @MainActor (_ event: NostrEvent) -> Void
var acquirePlaceManager: AcquirePlaceManager
var releasePlaceManager: ReleasePlaceManager
var subscribeDefaultRelays: SubscribeDefaultRelays
var unsubscribe: Unsubscribe
var sendDefaultRelays: SendDefaultRelays
var publicIdentity: () throws -> NostrIdentity?
var ensureProfiles: @MainActor (_ pubkeys: [String]) -> Void
var now: () -> Date
static let live = HomeFeedDependencies(
acquirePlaceManager: { LocationNotesPool.shared.acquire($0) },
releasePlaceManager: { LocationNotesPool.shared.release($0) },
subscribeDefaultRelays: { filter, id, handler, onEOSE in
NostrRelayManager.shared.subscribe(
filter: filter,
id: id,
relayUrls: nil,
handler: handler,
onEOSE: onEOSE
)
},
unsubscribe: { NostrRelayManager.shared.unsubscribe(id: $0) },
sendDefaultRelays: { NostrRelayManager.shared.sendEvent($0) },
publicIdentity: { try NostrIdentityBridge.shared.getCurrentNostrIdentity() },
ensureProfiles: { NostrProfileStore.shared.ensureProfiles(for: $0) },
now: Date.init
)
}
/// One deduplicated post in the merged Saved Places + Following Home Feed.
struct HomeFeedItem: Identifiable, Equatable {
let note: LocationNotesManager.Note
/// Non-nil when this post belongs to (or was seen in) a bookmarked place.
let savedPlaceGeohash: String?
/// True when the author is in the user's private follow list or favorites.
let isFromFollowedAuthor: Bool
var id: String { note.id }
var noticeItem: NoticeItem {
NoticeItem(note: note)
}
}
@MainActor
final class HomeFeedManager: ObservableObject {
static let shared = HomeFeedManager()
/// Cap concurrently subscribed Saved Places to keep Tor circuit/socket load bounded.
static let maxSubscribedPlaces = 12
private static let maxFollowingNotesInMemory = 300
@Published private(set) var items: [HomeFeedItem] = []
@Published private(set) var isLoadingFollowing: Bool = false
@Published private(set) var isSending: Bool = false
@Published private(set) var errorMessage: String?
private let dependencies: HomeFeedDependencies
private var placeManagers: [String: LocationNotesManager] = [:]
private var placeCancellables: [String: AnyCancellable] = [:]
private var followingNotes: [LocationNotesManager.Note] = []
private var followingRepliesByRootID: [String: [LocationNotesManager.Note]] = [:]
private var followingNoteIDs = Set<String>()
private var followingSubscriptionID: String?
private var subscribedBookmarks: [String] = []
private var subscribedFollows: [String] = []
private var expiryPruneTimer: Timer?
private var isActive = false
init(dependencies: HomeFeedDependencies = .live) {
self.dependencies = dependencies
}
deinit {
expiryPruneTimer?.invalidate()
if let sub = followingSubscriptionID {
let unsubscribe = dependencies.unsubscribe
Task { @MainActor in
unsubscribe(sub)
}
}
let managers = Array(placeManagers.values)
let release = dependencies.releasePlaceManager
if !managers.isEmpty {
Task { @MainActor in
for manager in managers {
release(manager)
}
}
}
}
// MARK: - Lifecycle
func activate(bookmarks: [String], followedPubkeys: [String]) {
isActive = true
startExpiryPruneTimer()
updateSources(bookmarks: bookmarks, followedPubkeys: followedPubkeys)
}
func updateSources(bookmarks: [String], followedPubkeys: [String]) {
guard isActive else { return }
let normalizedBookmarks = Array(
NSOrderedSet(array: bookmarks.map { $0.lowercased() }.filter { Geohash.isValidGeohash($0) })
.compactMap { $0 as? String }
.prefix(Self.maxSubscribedPlaces)
)
let normalizedFollows = Array(
NSOrderedSet(array: followedPubkeys.compactMap { NostrProtocol.normalizePubkeyHex($0) })
.compactMap { $0 as? String }
)
if normalizedBookmarks != subscribedBookmarks {
reconcilePlaceManagers(targetBookmarks: normalizedBookmarks)
subscribedBookmarks = normalizedBookmarks
}
if normalizedFollows != subscribedFollows {
subscribedFollows = normalizedFollows
resubscribeFollowing(pubkeys: normalizedFollows)
}
rebuildItems()
}
func deactivate() {
isActive = false
stopExpiryPruneTimer()
releaseAllPlaceManagers()
closeFollowingSubscription()
subscribedBookmarks = []
subscribedFollows = []
}
func refresh() {
for manager in placeManagers.values {
manager.refresh()
}
resubscribeFollowing(pubkeys: subscribedFollows)
rebuildItems()
}
func clearError() {
errorMessage = nil
}
// MARK: - Queries
func manager(forGeohash geohash: String) -> LocationNotesManager? {
placeManagers[geohash.lowercased()]
}
func replyCount(for item: HomeFeedItem) -> Int {
var ids = Set<String>()
if let gh = item.savedPlaceGeohash, let manager = placeManagers[gh] {
for r in manager.replies(forRootID: item.id) { ids.insert(r.id) }
}
for r in followingRepliesByRootID[item.id] ?? [] {
ids.insert(r.id)
}
return ids.count
}
func reactions(for item: HomeFeedItem) -> [AggregatedReaction] {
guard let gh = item.savedPlaceGeohash, let manager = placeManagers[gh] else {
return []
}
return manager.reactions(forNoteID: item.id)
}
func totalReactionCount(for item: HomeFeedItem) -> Int {
reactions(for: item).reduce(0) { $0 + $1.count }
}
func isOwn(_ item: HomeFeedItem) -> Bool {
if let gh = item.savedPlaceGeohash,
let manager = placeManagers[gh],
manager.isOwnNote(item.note) {
return true
}
if let ownPubkey = (try? dependencies.publicIdentity())?.publicKeyHex.lowercased(),
item.note.pubkey.lowercased() == ownPubkey {
return true
}
return false
}
func filteredItems(
scope: HomeFeedScope,
sort: PlaceFeedSort,
filter: PlaceFeedFilter,
query: String = ""
) -> [HomeFeedItem] {
let scoped = items.filter { item in
switch scope {
case .all:
return true
case .savedPlaces:
return item.savedPlaceGeohash != nil
case .following:
return item.isFromFollowedAuthor
}
}
let lookup = Dictionary(uniqueKeysWithValues: scoped.map { ($0.id, $0) })
let organizedNotices = PlaceFeedOrganizer.organize(
items: scoped.map(\.noticeItem),
sort: sort,
filter: filter,
query: query,
replyCount: { id in
guard let item = lookup[id] else { return 0 }
return self.replyCount(for: item)
},
reactionCount: { id in
guard let item = lookup[id] else { return 0 }
return self.totalReactionCount(for: item)
},
isVouched: { notice in
guard let note = notice.nostrNote else { return false }
return LocalWebOfTrustService.shared.isTrustedAuthor(note.pubkey)
}
)
return organizedNotices.compactMap { lookup[$0.id] }
}
// MARK: - Publishing & Interactions
/// Publishes a global (non-geohash) kind-1 post signed synchronously with
/// the user's persistent public handle.
@discardableResult
func sendGlobalPost(
content: String,
nickname: String,
expiresAt: Date? = nil
) -> Bool {
guard let trimmed = content.trimmedOrNilIfEmpty else { return false }
guard let identity = try? dependencies.publicIdentity() else {
errorMessage = String(localized: "home_feed.error.handle_required", defaultValue: "Enable your Public Handle to post globally.", comment: "Shown when attempting a global post without a persistent handle")
return false
}
isSending = true
defer { isSending = false }
do {
let event = try NostrProtocol.createPublicTextNote(
content: trimmed,
senderIdentity: identity,
nickname: nickname,
expiresAt: expiresAt,
replyTo: nil,
createdAt: dependencies.now()
)
dependencies.sendDefaultRelays(event)
ingestFollowingEvent(event)
errorMessage = nil
return true
} catch {
errorMessage = error.localizedDescription
return false
}
}
func toggleReaction(emoji: String, on item: HomeFeedItem) {
if let gh = item.savedPlaceGeohash, let manager = placeManagers[gh] {
manager.toggleReaction(emoji: emoji, on: item.note)
}
}
func delete(_ item: HomeFeedItem) {
if let gh = item.savedPlaceGeohash,
let manager = placeManagers[gh],
manager.isOwnNote(item.note) {
manager.delete(note: item.note)
}
if let identity = try? dependencies.publicIdentity(),
item.note.pubkey.lowercased() == identity.publicKeyHex.lowercased() {
if let deletion = try? NostrProtocol.createDeleteEvent(ofEventID: item.id, senderIdentity: identity) {
dependencies.sendDefaultRelays(deletion)
}
followingNotes.removeAll { $0.id == item.id }
rebuildItems()
}
}
/// Panic-wipe hook: tears down all subscriptions, releases pooled managers,
/// and erases cached feed items.
func resetForPanic() {
isSending = false
isActive = false
stopExpiryPruneTimer()
releaseAllPlaceManagers()
closeFollowingSubscription()
followingNotes.removeAll(keepingCapacity: false)
followingRepliesByRootID.removeAll(keepingCapacity: false)
followingNoteIDs.removeAll(keepingCapacity: false)
subscribedBookmarks = []
subscribedFollows = []
items.removeAll(keepingCapacity: false)
isLoadingFollowing = false
errorMessage = nil
}
// MARK: - Internal Subscription Wiring
private func reconcilePlaceManagers(targetBookmarks: [String]) {
let targetSet = Set(targetBookmarks)
for existingKey in Array(placeManagers.keys) where !targetSet.contains(existingKey) {
placeCancellables.removeValue(forKey: existingKey)
let manager = placeManagers.removeValue(forKey: existingKey)
dependencies.releasePlaceManager(manager)
}
for gh in targetBookmarks where placeManagers[gh] == nil {
let manager = dependencies.acquirePlaceManager(gh)
placeManagers[gh] = manager
placeCancellables[gh] = Publishers.Merge3(
manager.$notes.map { _ in () },
manager.$repliesByRootID.map { _ in () },
manager.$reactionsByNoteID.map { _ in () }
)
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.rebuildItems()
}
}
}
private func releaseAllPlaceManagers() {
placeCancellables.removeAll()
let managers = Array(placeManagers.values)
placeManagers.removeAll()
for manager in managers {
dependencies.releasePlaceManager(manager)
}
}
private func closeFollowingSubscription() {
if let sub = followingSubscriptionID {
dependencies.unsubscribe(sub)
followingSubscriptionID = nil
}
isLoadingFollowing = false
}
private func resubscribeFollowing(pubkeys: [String]) {
closeFollowingSubscription()
followingNotes.removeAll()
followingRepliesByRootID.removeAll()
followingNoteIDs.removeAll()
var authors = pubkeys
if let ownHex = (try? dependencies.publicIdentity())?.publicKeyHex.lowercased(),
NostrProfileStore.shared.isPublicHandleEnabled,
!authors.contains(ownHex) {
authors.append(ownHex)
}
guard !authors.isEmpty else { return }
dependencies.ensureProfiles(authors)
isLoadingFollowing = true
let subID = "homefeed-following-\(UUID().uuidString.prefix(8))"
followingSubscriptionID = subID
let filter = NostrFilter.authorNotes(authors, since: nil, limit: 150)
dependencies.subscribeDefaultRelays(filter, subID, { [weak self] event in
self?.ingestFollowingEvent(event)
}, { [weak self] in
self?.isLoadingFollowing = false
})
}
private func ingestFollowingEvent(_ event: NostrEvent) {
guard event.kind == NostrProtocol.EventKind.textNote.rawValue else { return }
let normalizedID = event.id.lowercased()
guard !followingNoteIDs.contains(normalizedID) else { return }
var geohash = ""
var nick: String?
var expiresAt: Date?
var urgent = false
var teleported = false
for tag in event.tags where tag.count >= 2 {
switch tag[0].lowercased() {
case "g":
if geohash.isEmpty { geohash = tag[1].lowercased() }
case "n":
if nick == nil { nick = tag[1] }
case "expiration":
if expiresAt == nil, let secs = TimeInterval(tag[1]) {
expiresAt = Date(timeIntervalSince1970: secs)
}
case "t":
let val = tag[1].lowercased()
if val == "urgent" { urgent = true }
else if val == "teleport" { teleported = true }
default:
break
}
}
let now = dependencies.now()
if let expiresAt, expiresAt <= now { return }
followingNoteIDs.insert(normalizedID)
let latestAccepted = now.addingTimeInterval(TimeInterval(BoardStore.Limits.clockSkewMs) / 1000)
let ts = min(Date(timeIntervalSince1970: TimeInterval(event.created_at)), latestAccepted)
let threadRef = NostrProtocol.parseThreadReference(from: event.tags)
let powDifficulty = NostrProtocol.validatedPoWDifficulty(idHex: event.id, tags: event.tags)
let attachments = NostrProtocol.parseMediaAttachments(from: event.tags)
let note = LocationNotesManager.Note(
id: normalizedID,
pubkey: event.pubkey.lowercased(),
content: event.content,
createdAt: ts,
nickname: nick,
geohash: geohash,
expiresAt: expiresAt,
isUrgent: urgent,
rootEventID: threadRef?.rootEventID,
replyToEventID: threadRef?.replyEventID,
powDifficulty: powDifficulty,
isTeleported: teleported,
attachments: attachments
)
if let rootID = note.rootEventID {
var thread = followingRepliesByRootID[rootID] ?? []
thread.append(note)
thread.sort { $0.createdAt < $1.createdAt }
followingRepliesByRootID[rootID] = thread
} else {
followingNotes.append(note)
followingNotes.sort { $0.createdAt > $1.createdAt }
if followingNotes.count > Self.maxFollowingNotesInMemory {
followingNotes = Array(followingNotes.prefix(Self.maxFollowingNotesInMemory))
}
}
rebuildItems()
}
/// Drops NIP-40 expired entries from the Following cache and triggers a
/// feed rebuild so expired followed posts cannot linger or resurrect
/// expired Saved Place posts.
func pruneExpiredFollowingNotes() {
let now = dependencies.now()
var removedIDs: [String] = []
followingNotes.removeAll { note in
if let expiresAt = note.expiresAt, expiresAt <= now {
removedIDs.append(note.id)
return true
}
return false
}
for (rootID, replies) in followingRepliesByRootID {
let kept = replies.filter { reply in
if let expiresAt = reply.expiresAt, expiresAt <= now {
removedIDs.append(reply.id)
return false
}
return true
}
if kept.isEmpty {
followingRepliesByRootID.removeValue(forKey: rootID)
} else if kept.count != replies.count {
followingRepliesByRootID[rootID] = kept
}
}
if !removedIDs.isEmpty {
for id in removedIDs {
followingNoteIDs.remove(id)
}
rebuildItems()
}
}
private func startExpiryPruneTimer() {
guard expiryPruneTimer == nil else { return }
let timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
Task { @MainActor [weak self] in
self?.pruneExpiredFollowingNotes()
}
}
timer.tolerance = 10.0
expiryPruneTimer = timer
}
private func stopExpiryPruneTimer() {
expiryPruneTimer?.invalidate()
expiryPruneTimer = nil
}
private func rebuildItems() {
let now = dependencies.now()
// Drop any expired following entries before merging so an expired
// saved-place post cannot be resurrected from the Following cache.
var expiredFollowingIDs: [String] = []
followingNotes.removeAll { note in
if let expiresAt = note.expiresAt, expiresAt <= now {
expiredFollowingIDs.append(note.id)
return true
}
return false
}
for id in expiredFollowingIDs {
followingNoteIDs.remove(id)
}
let followedSet = Set(subscribedFollows)
let ownPublicHex = (try? dependencies.publicIdentity())?.publicKeyHex.lowercased()
var mergedByID: [String: HomeFeedItem] = [:]
var authorPubkeys = Set<String>()
// 1. Saved Places notes
for (bookmarkGeohash, manager) in placeManagers {
for note in manager.notes {
if let expiresAt = note.expiresAt, expiresAt <= now { continue }
let pubkey = note.pubkey.lowercased()
authorPubkeys.insert(pubkey)
let isFollowed = followedSet.contains(pubkey) || (ownPublicHex == pubkey)
if let existing = mergedByID[note.id] {
mergedByID[note.id] = HomeFeedItem(
note: existing.note,
savedPlaceGeohash: existing.savedPlaceGeohash ?? bookmarkGeohash,
isFromFollowedAuthor: existing.isFromFollowedAuthor || isFollowed
)
} else {
mergedByID[note.id] = HomeFeedItem(
note: note,
savedPlaceGeohash: bookmarkGeohash,
isFromFollowedAuthor: isFollowed
)
}
}
}
// 2. Following notes (merge into existing place entry when same event ID)
for note in followingNotes {
let pubkey = note.pubkey.lowercased()
authorPubkeys.insert(pubkey)
if let existing = mergedByID[note.id] {
mergedByID[note.id] = HomeFeedItem(
note: existing.note,
savedPlaceGeohash: existing.savedPlaceGeohash,
isFromFollowedAuthor: true
)
} else {
let matchedBookmark = !note.geohash.isEmpty && placeManagers[note.geohash] != nil
? note.geohash
: nil
mergedByID[note.id] = HomeFeedItem(
note: note,
savedPlaceGeohash: matchedBookmark,
isFromFollowedAuthor: true
)
}
}
if !authorPubkeys.isEmpty {
dependencies.ensureProfiles(Array(authorPubkeys))
}
items = mergedByID.values.sorted { lhs, rhs in
if lhs.note.isUrgent != rhs.note.isUrgent { return lhs.note.isUrgent }
if lhs.note.createdAt != rhs.note.createdAt { return lhs.note.createdAt > rhs.note.createdAt }
return lhs.id < rhs.id
}
}
}
@@ -0,0 +1,86 @@
//
// LocalWebOfTrustService.swift
// bitchat
//
// Bridges bitchat's physical in-person verification & transitive VouchAttestation
// graph (SecureIdentityStateManager + FavoritesPersistenceService) onto Nostr
// feed authors so users can filter feeds by real-world physical trust.
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import BitFoundation
import Foundation
/// Physical Web-of-Trust status for a Nostr feed author, derived strictly from
/// local in-person QR/Noise verification and signed VouchAttestations.
enum FeedAuthorTrust: Equatable, Sendable {
/// Directly verified in person via Noise/QR fingerprint.
case verified
/// Transitively vouched for via signed VouchAttestation by ≥1 peer we verified.
case vouched(voucherCount: Int)
/// Not linked to a locally verified or vouched mesh identity.
case none
var isTrusted: Bool {
switch self {
case .verified, .vouched:
return true
case .none:
return false
}
}
}
@MainActor
final class LocalWebOfTrustService {
static let shared = LocalWebOfTrustService()
private var identityManager: SecureIdentityStateManagerProtocol?
private let noiseKeyLookup: @MainActor (_ nostrPubkeyHex: String) -> Data?
private let isVerifiedFingerprintOverride: ((_ fingerprint: String) -> Bool)?
private let validVoucherCountOverride: ((_ fingerprint: String) -> Int)?
init(
identityManager: SecureIdentityStateManagerProtocol? = nil,
noiseKeyLookup: (@MainActor (_ nostrPubkeyHex: String) -> Data?)? = nil,
isVerifiedFingerprint: ((_ fingerprint: String) -> Bool)? = nil,
validVoucherCount: ((_ fingerprint: String) -> Int)? = nil
) {
self.identityManager = identityManager
self.noiseKeyLookup = noiseKeyLookup ?? { pubkey in
FavoritesPersistenceService.shared.noisePublicKey(forNostrPubkey: pubkey)
}
self.isVerifiedFingerprintOverride = isVerifiedFingerprint
self.validVoucherCountOverride = validVoucherCount
}
func configure(identityManager: SecureIdentityStateManagerProtocol) {
self.identityManager = identityManager
}
func trust(forNostrPubkey nostrPubkeyHex: String) -> FeedAuthorTrust {
guard let noiseKey = noiseKeyLookup(nostrPubkeyHex.lowercased()) else {
return .none
}
let fingerprint = noiseKey.sha256Fingerprint()
let verified = isVerifiedFingerprintOverride?(fingerprint)
?? identityManager?.isVerified(fingerprint: fingerprint)
?? false
if verified {
return .verified
}
let vouchers = validVoucherCountOverride?(fingerprint)
?? identityManager?.validVouchers(for: fingerprint).count
?? 0
if vouchers > 0 {
return .vouched(voucherCount: vouchers)
}
return .none
}
func isTrustedAuthor(_ nostrPubkeyHex: String) -> Bool {
trust(forNostrPubkey: nostrPubkeyHex).isTrusted
}
}
+711 -109
View File
@@ -27,6 +27,18 @@ struct LocationNotesDependencies {
/// "loaded, empty" from "still connecting (Tor warming up)" when EOSE
/// fires without data. Defaults to true so tests keep legacy behavior.
var anyRelayConnected: @MainActor (_ relayUrls: [String]) -> Bool = { _ in true }
/// Persistent primary Nostr identity used only when the user opts into
/// posting with their public handle (`.publicHandle`).
var publicIdentity: () throws -> NostrIdentity? = { nil }
/// Publishes an event to the default relay set so followers also receive
/// place posts signed with `.publicHandle`.
var sendToDefaultRelays: @MainActor (_ event: NostrEvent) -> Void = { _ in }
/// Hands a locally signed kind-1/kind-7 event to a nearby BLE gateway peer
/// when internet relays are unreachable.
var uplinkViaMesh: @MainActor (_ event: NostrEvent, _ geohash: String) -> Bool = { _, _ in false }
/// Rebroadcasts an inbound relay kind-1/kind-7 event onto the local BLE mesh
/// when this device has Gateway Mode enabled.
var rebroadcastToMesh: @MainActor (_ event: NostrEvent, _ geohash: String) -> Void = { _, _ in }
private static let idBridge = NostrIdentityBridge.shared
@@ -78,12 +90,28 @@ struct LocationNotesDependencies {
},
anyRelayConnected: { relayUrls in
NostrRelayManager.shared.isAnyRelayConnected(among: relayUrls)
},
publicIdentity: {
try idBridge.getCurrentNostrIdentity()
},
sendToDefaultRelays: { event in
NostrRelayManager.shared.sendEvent(event)
},
uplinkViaMesh: { event, geohash in
GatewayService.shared.uplinkViaMesh(event: event, geohash: geohash)
},
rebroadcastToMesh: { event, geohash in
GatewayService.shared.rebroadcastRelayEvent(
event,
geohash: geohash,
signatureAlreadyVerified: true
)
}
)
}
/// Persistent location notes (Nostr kind 1) scoped to a building-level geohash (precision 8).
/// Subscribes to and publishes notes for a given geohash and provides a send API.
/// Persistent location notes and Place Feed (Nostr kind 1 posts/NIP-10 replies
/// + kind 7 NIP-25 reactions) scoped to a geohash and its 8 immediate neighbors.
@MainActor
final class LocationNotesManager: ObservableObject {
enum State: Equatable {
@@ -110,6 +138,16 @@ final class LocationNotesManager: ObservableObject {
let expiresAt: Date?
/// Carries a `["t","urgent"]` tag (parity with urgent board posts).
let isUrgent: Bool
/// NIP-10 thread root event ID when this note is a reply; nil for top-level posts.
let rootEventID: String?
/// NIP-10 direct parent event ID when replying to a reply; nil for root posts or direct replies to root.
let replyToEventID: String?
/// Validated NIP-13 proof-of-work difficulty (leading zero bits committed and met).
let powDifficulty: Int
/// Carries `["t","teleport"]` when published remotely rather than on-site.
let isTeleported: Bool
/// Validated NIP-92 `imeta` Blossom media attachments (HTTPS + SHA-256).
let attachments: [NostrProtocol.MediaAttachment]
init(
id: String,
@@ -119,7 +157,12 @@ final class LocationNotesManager: ObservableObject {
nickname: String?,
geohash: String,
expiresAt: Date? = nil,
isUrgent: Bool = false
isUrgent: Bool = false,
rootEventID: String? = nil,
replyToEventID: String? = nil,
powDifficulty: Int = 0,
isTeleported: Bool = false,
attachments: [NostrProtocol.MediaAttachment] = []
) {
self.id = id
self.pubkey = pubkey
@@ -129,10 +172,20 @@ final class LocationNotesManager: ObservableObject {
self.geohash = geohash
self.expiresAt = expiresAt
self.isUrgent = isUrgent
self.rootEventID = rootEventID?.lowercased()
let normalizedReply = replyToEventID?.lowercased()
self.replyToEventID = (normalizedReply == self.rootEventID) ? nil : normalizedReply
self.powDifficulty = max(0, powDifficulty)
self.isTeleported = isTeleported
self.attachments = attachments
}
var authorSuffix: String { String(pubkey.suffix(4)) }
var shortAuthorName: String { nickname?.trimmedOrNilIfEmpty ?? "anon" }
var hasVerifiedPoW: Bool { powDifficulty >= NostrProtocol.verifiedPoWThresholdBits }
var displayName: String {
let suffix = String(pubkey.suffix(4))
let suffix = authorSuffix
if let nick = nickname?.trimmedOrNilIfEmpty {
return "\(nick)#\(suffix)"
}
@@ -140,21 +193,56 @@ final class LocationNotesManager: ObservableObject {
}
}
@Published private(set) var notes: [Note] = [] // reverse-chron sorted
private static func reactionTargetKey(targetID: String, emoji: String) -> String {
"\(targetID)\u{0}\(emoji)"
}
/// Top-level posts, newest first.
@Published private(set) var notes: [Note] = []
/// NIP-10 replies grouped by `rootEventID`, sorted chronologically (oldest -> newest).
@Published private(set) var repliesByRootID: [String: [Note]] = [:]
/// Aggregated NIP-25 reactions keyed by target event ID.
@Published private(set) var reactionsByNoteID: [String: [AggregatedReaction]] = [:]
@Published private(set) var geohash: String
@Published private(set) var initialLoadComplete: Bool = false
@Published private(set) var state: State = .loading
@Published private(set) var errorMessage: String?
/// Public key of our per-geohash Nostr identity; identifies our own notes.
/// True while an outgoing NIP-13 PoW mining task is running.
@Published private(set) var isSending: Bool = false
/// Public key of our per-geohash Nostr identity; identifies our own notes and reactions.
private var ownPubkey: String?
/// Public key of our persistent primary Nostr identity (when available), so
/// notes posted under `.publicHandle` are also recognized as ours for delete/highlight.
private var ownPublicPubkey: String?
private var subscriptionID: String?
private var noteIDs = Set<String>() // O(1) duplicate detection
private var noteIDs = Set<String>() // O(1) duplicate detection for kind-1 notes & replies
private var reactionEventIDs = Set<String>() // O(1) dedup for kind-7 reactions
/// targetEventID -> emoji -> Set<authorPubkey>
private var reactionActorsByTarget: [String: [String: Set<String>]] = [:]
/// targetEventID -> insertion order of emojis for stable UI pills
private var reactionEmojiOrderByTarget: [String: [String]] = [:]
/// Latest own kind-7 reaction event ID per (target, emoji) key so toggling off can emit NIP-09 delete.
private var ownReactionEventIDs: [String: String] = [:]
/// Maps kind-7 reaction event ID -> (targetID, emoji, actorPubkey) so inbound NIP-09 deletions can retract reactions.
private var reactionMetaByEventID: [String: (targetID: String, emoji: String, actorPubkey: String)] = [:]
/// Event IDs retracted by verified NIP-09 kind-5 deletions (prevents out-of-order replay resurrection).
private var deletedEventIDs = Set<String>()
private var directoryUpdateCancellable: AnyCancellable?
private var networkAvailableCancellable: AnyCancellable?
private var expiryPruneTimer: Timer?
private var connectivityRetryTimer: Timer?
private let dependencies: LocationNotesDependencies
private let maxNotesInMemory = 500 // Defensive cap (relay limit is 200)
private let maxRepliesPerThread = 200
private let maxTrackedReactionEvents = 2_000
/// Short 4-char hex suffix of our unlinkable per-place pubkey, for composer attribution.
var ownIdentitySuffix: String? {
ownPubkey.map { String($0.suffix(4)) }
}
private enum Strings {
static let noRelays = String(localized: "location_notes.error.no_relays", comment: "Shown when no geo relays are available near the selected location")
@@ -175,7 +263,8 @@ final class LocationNotesManager: ObservableObject {
if !Geohash.isValidGeohash(norm) {
SecureLogger.warning("LocationNotesManager: invalid geohash '\(norm)' (expected 1-12 valid base32 chars)", category: .session)
}
ownPubkey = (try? dependencies.deriveIdentity(norm))?.publicKeyHex
ownPubkey = (try? dependencies.deriveIdentity(norm))?.publicKeyHex.lowercased()
ownPublicPubkey = (try? dependencies.publicIdentity())?.publicKeyHex.lowercased()
subscribe()
// The relay directory may load after init (remote fetch over Tor);
// retry automatically instead of staying stuck on "no relays".
@@ -219,26 +308,56 @@ final class LocationNotesManager: ObservableObject {
}
}
/// Drops notes whose NIP-40 expiry has passed. Their ids stay in
// MARK: - Thread & Reaction Queries
/// Chronological (oldest -> newest) NIP-10 replies for a root post.
func replies(forRootID rootID: String) -> [Note] {
repliesByRootID[rootID.lowercased()] ?? []
}
func replyCount(forRootID rootID: String) -> Int {
repliesByRootID[rootID.lowercased()]?.count ?? 0
}
func reactions(forNoteID noteID: String) -> [AggregatedReaction] {
reactionsByNoteID[noteID.lowercased()] ?? []
}
func totalReactionCount(forNoteID noteID: String) -> Int {
reactions(forNoteID: noteID).reduce(0) { $0 + $1.count }
}
/// Drops notes and replies whose NIP-40 expiry has passed. Their ids stay in
/// `noteIDs` so a relay replay cannot resurrect them.
func pruneExpiredNotes() {
let now = dependencies.now()
let expired = notes.contains { note in
if let expiresAt = note.expiresAt { return expiresAt <= now }
return false
if notes.contains(where: { $0.expiresAt.map { $0 <= now } ?? false }) {
notes.removeAll { note in
if let expiresAt = note.expiresAt { return expiresAt <= now }
return false
}
}
guard expired else { return }
notes.removeAll { note in
if let expiresAt = note.expiresAt { return expiresAt <= now }
return false
var updatedReplies = repliesByRootID
var repliesChanged = false
for (rootID, thread) in repliesByRootID {
if thread.contains(where: { $0.expiresAt.map { $0 <= now } ?? false }) {
let remaining = thread.filter { reply in
if let expiresAt = reply.expiresAt { return expiresAt > now }
return true
}
if remaining.isEmpty {
updatedReplies.removeValue(forKey: rootID)
} else {
updatedReplies[rootID] = remaining
}
repliesChanged = true
}
}
if repliesChanged {
repliesByRootID = updatedReplies
}
}
// A manager's geohash is fixed for its lifetime: instances are pooled
// per geohash (`LocationNotesPool`), so retargeting one in place would
// corrupt the pool's keying and refcounts. Release the manager and
// acquire the new cell instead.
func refresh() {
if let sub = subscriptionID {
dependencies.unsubscribe(sub)
@@ -249,7 +368,13 @@ final class LocationNotesManager: ObservableObject {
initialLoadComplete = false
errorMessage = nil
notes.removeAll()
repliesByRootID.removeAll()
reactionsByNoteID.removeAll()
noteIDs.removeAll()
reactionEventIDs.removeAll()
reactionActorsByTarget.removeAll()
reactionEmojiOrderByTarget.removeAll()
ownReactionEventIDs.removeAll()
subscribe()
}
@@ -280,70 +405,18 @@ final class LocationNotesManager: ObservableObject {
subscriptionID = subID
initialLoadComplete = false
// Subscribe to center + 8 neighbors (± 1 grid)
// Subscribe to center + 8 neighbors (± 1 grid) for kind-1 notes/replies
// and kind-7 NIP-25 reactions in one REQ to preserve Tor socket budget.
let neighbors = Geohash.neighbors(of: geohash)
let allGeohashes = [geohash] + neighbors
let filter = NostrFilter.geohashNotes(allGeohashes, since: nil, limit: 200)
let filter = NostrFilter.geohashFeed(allGeohashes, since: nil, limit: 200)
// Build a set of valid geohashes for tag matching (includes all 9 cells)
let validGeohashes = Set(allGeohashes.map { $0.lowercased() })
dependencies.subscribe(filter, subID, relays, { [weak self] event in
guard let self = self else { return }
guard event.kind == NostrProtocol.EventKind.textNote.rawValue 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 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 = now
.addingTimeInterval(TimeInterval(BoardStore.Limits.clockSkewMs) / 1000)
let ts = min(Date(timeIntervalSince1970: TimeInterval(event.created_at)), latestAccepted)
let note = Note(id: event.id, pubkey: event.pubkey, content: event.content, createdAt: ts, nickname: nick, geohash: matchedGeohash, expiresAt: expiresAt, isUrgent: urgent)
self.insertNoteSorted(note)
self.enforceMemoryCap()
if self.state != .ready {
self.state = .ready
}
self.ingestInboundEvent(event, validGeohashes: validGeohashes, fromGateway: false)
}, { [weak self] in
guard let self = self else { return }
self.initialLoadComplete = true
@@ -360,8 +433,264 @@ final class LocationNotesManager: ObservableObject {
})
}
/// Inserts a note in descending `createdAt` order via binary search
/// ($O(\log N)$ compare instead of re-sorting the entire array per note).
/// Injects a Schnorr-verified kind-1 or kind-7 event carried over BLE by a
/// nearby Gateway peer. Never re-broadcasts back to the mesh (loop rule 1).
func ingestCarriedEvent(_ event: NostrEvent) {
let validGeohashes = Set(([geohash] + Geohash.neighbors(of: geohash)).map { $0.lowercased() })
ingestInboundEvent(event, validGeohashes: validGeohashes, fromGateway: true)
}
private func ingestInboundEvent(_ event: NostrEvent, validGeohashes: Set<String>, fromGateway: Bool) {
switch event.kind {
case NostrProtocol.EventKind.textNote.rawValue:
if let matchedGeohash = ingestTextNote(event, validGeohashes: validGeohashes), !fromGateway {
dependencies.rebroadcastToMesh(event, matchedGeohash)
}
case NostrProtocol.EventKind.reaction.rawValue:
if let matchedGeohash = ingestReaction(event, validGeohashes: validGeohashes), !fromGateway {
dependencies.rebroadcastToMesh(event, matchedGeohash)
}
case NostrProtocol.EventKind.deletion.rawValue:
ingestDeletion(event)
default:
return
}
}
@discardableResult
private func ingestTextNote(_ event: NostrEvent, validGeohashes: Set<String>) -> String? {
let normalizedID = event.id.lowercased()
guard !noteIDs.contains(normalizedID), !deletedEventIDs.contains(normalizedID) else { return nil }
// Single pass over tags: match any of our 9 cells + extract nick/expiration/urgent/teleport.
var matchedGeohash: String?
var nick: String?
var expiresAt: Date?
var urgent = false
var teleported = 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":
let value = tag[1].lowercased()
if value == "urgent" {
urgent = true
} else if value == "teleport" {
teleported = true
}
default:
break
}
}
guard let matchedGeohash else { return nil }
// NIP-40: relays are not required to enforce expiration — drop
// expired notes client-side so 24h dead drops actually vanish.
let now = dependencies.now()
if let expiresAt, expiresAt <= now { return nil }
recordNoteID(normalizedID)
// 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 = now
.addingTimeInterval(TimeInterval(BoardStore.Limits.clockSkewMs) / 1000)
let ts = min(Date(timeIntervalSince1970: TimeInterval(event.created_at)), latestAccepted)
let threadRef = NostrProtocol.parseThreadReference(from: event.tags)
let powDifficulty = NostrProtocol.validatedPoWDifficulty(idHex: event.id, tags: event.tags)
let attachments = NostrProtocol.parseMediaAttachments(from: event.tags)
let note = Note(
id: normalizedID,
pubkey: event.pubkey.lowercased(),
content: event.content,
createdAt: ts,
nickname: nick,
geohash: matchedGeohash,
expiresAt: expiresAt,
isUrgent: urgent,
rootEventID: threadRef?.rootEventID,
replyToEventID: threadRef?.replyEventID,
powDifficulty: powDifficulty,
isTeleported: teleported,
attachments: attachments
)
if let rootID = note.rootEventID {
insertReplySorted(note, forRootID: rootID)
} else {
insertNoteSorted(note)
enforceMemoryCap()
}
if state != .ready {
state = .ready
}
return matchedGeohash
}
@discardableResult
private func ingestReaction(_ event: NostrEvent, validGeohashes: Set<String>) -> String? {
let normalizedEventID = event.id.lowercased()
guard !reactionEventIDs.contains(normalizedEventID),
!deletedEventIDs.contains(normalizedEventID) else {
return nil
}
// Require the reaction to belong to one of our 9 subscribed cells.
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 nil
}
guard let parsed = NostrProtocol.parseReactionTarget(from: event) else { return nil }
recordReactionEventID(normalizedEventID)
let authorPubkey = event.pubkey.lowercased()
applyReaction(
targetID: parsed.targetEventID,
emoji: parsed.emoji,
actorPubkey: authorPubkey,
eventID: normalizedEventID
)
return matchedGeohash
}
/// Processes an inbound NIP-09 kind-5 deletion event. Verifies that the
/// deletion author matches the original reaction or note author before
/// retracting the reaction or removing the note.
private func ingestDeletion(_ event: NostrEvent) {
let deleterPubkey = event.pubkey.lowercased()
for tag in event.tags where tag.count >= 2 && tag[0].lowercased() == "e" {
let targetID = tag[1].trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
guard targetID.count == 64 else { continue }
// 1. Retract a tracked kind-7 reaction if signed by the same author.
if let meta = reactionMetaByEventID[targetID] {
guard meta.actorPubkey == deleterPubkey else { continue }
deletedEventIDs.insert(targetID)
reactionMetaByEventID.removeValue(forKey: targetID)
removeReaction(targetID: meta.targetID, emoji: meta.emoji, actorPubkey: meta.actorPubkey)
let ownKey = Self.reactionTargetKey(targetID: meta.targetID, emoji: meta.emoji)
if ownReactionEventIDs[ownKey] == targetID {
ownReactionEventIDs.removeValue(forKey: ownKey)
}
continue
}
// 2. Remove a top-level note or reply if signed by the same author.
if let noteIndex = notes.firstIndex(where: { $0.id == targetID }) {
guard notes[noteIndex].pubkey.lowercased() == deleterPubkey else { continue }
deletedEventIDs.insert(targetID)
notes.remove(at: noteIndex)
continue
}
for (rootID, replies) in repliesByRootID {
if let replyIndex = replies.firstIndex(where: { $0.id == targetID }) {
guard replies[replyIndex].pubkey.lowercased() == deleterPubkey else { break }
deletedEventIDs.insert(targetID)
var updated = replies
updated.remove(at: replyIndex)
if updated.isEmpty {
repliesByRootID.removeValue(forKey: rootID)
} else {
repliesByRootID[rootID] = updated
}
break
}
}
}
}
private func removeReaction(targetID: String, emoji: String, actorPubkey: String) {
let normalizedTarget = targetID.lowercased()
guard var byEmoji = reactionActorsByTarget[normalizedTarget],
var actors = byEmoji[emoji] else {
return
}
actors.remove(actorPubkey)
if actors.isEmpty {
byEmoji.removeValue(forKey: emoji)
} else {
byEmoji[emoji] = actors
}
if byEmoji.isEmpty {
reactionActorsByTarget.removeValue(forKey: normalizedTarget)
} else {
reactionActorsByTarget[normalizedTarget] = byEmoji
}
rebuildAggregatedReactions(forTargetID: normalizedTarget)
}
private func isOwnPubkey(_ pubkeyHex: String) -> Bool {
let lower = pubkeyHex.lowercased()
if let ownPubkey, lower == ownPubkey.lowercased() { return true }
if let ownPublicPubkey, lower == ownPublicPubkey.lowercased() { return true }
return false
}
private func applyReaction(targetID: String, emoji: String, actorPubkey: String, eventID: String) {
let normalizedTarget = targetID.lowercased()
reactionMetaByEventID[eventID] = (targetID: normalizedTarget, emoji: emoji, actorPubkey: actorPubkey)
var byEmoji = reactionActorsByTarget[normalizedTarget, default: [:]]
var actors = byEmoji[emoji, default: []]
let inserted = actors.insert(actorPubkey).inserted
byEmoji[emoji] = actors
reactionActorsByTarget[normalizedTarget] = byEmoji
if inserted {
var order = reactionEmojiOrderByTarget[normalizedTarget, default: []]
if !order.contains(emoji) {
order.append(emoji)
reactionEmojiOrderByTarget[normalizedTarget] = order
}
}
if isOwnPubkey(actorPubkey) {
ownReactionEventIDs[Self.reactionTargetKey(targetID: normalizedTarget, emoji: emoji)] = eventID
}
rebuildAggregatedReactions(forTargetID: normalizedTarget)
}
private func rebuildAggregatedReactions(forTargetID targetID: String) {
guard let byEmoji = reactionActorsByTarget[targetID], !byEmoji.isEmpty else {
reactionsByNoteID.removeValue(forKey: targetID)
return
}
let order = reactionEmojiOrderByTarget[targetID] ?? Array(byEmoji.keys)
let aggregated: [AggregatedReaction] = order.compactMap { emoji in
guard let actors = byEmoji[emoji], !actors.isEmpty else { return nil }
let includesMe = actors.contains { isOwnPubkey($0) }
return AggregatedReaction(
emoji: emoji,
count: actors.count,
includesCurrentUser: includesMe
)
}
if aggregated.isEmpty {
reactionsByNoteID.removeValue(forKey: targetID)
} else {
reactionsByNoteID[targetID] = aggregated
}
}
/// Inserts a top-level note in descending `createdAt` order via binary search.
private func insertNoteSorted(_ note: Note) {
var low = 0
var high = notes.count
@@ -376,15 +705,50 @@ final class LocationNotesManager: ObservableObject {
notes.insert(note, at: low)
}
/// Inserts a NIP-10 reply in ascending `createdAt` order (oldest -> newest).
private func insertReplySorted(_ reply: Note, forRootID rootID: String) {
var thread = repliesByRootID[rootID] ?? []
var low = 0
var high = thread.count
while low < high {
let mid = (low + high) / 2
if thread[mid].createdAt <= reply.createdAt {
low = mid + 1
} else {
high = mid
}
}
thread.insert(reply, at: low)
if thread.count > maxRepliesPerThread {
thread = Array(thread.suffix(maxRepliesPerThread))
}
repliesByRootID[rootID] = thread
}
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))
// Keep all currently visible note & reply IDs so active items never duplicate.
var liveIDs = Set(notes.map(\.id))
for thread in repliesByRootID.values {
liveIDs.formUnion(thread.map(\.id))
}
noteIDs = liveIDs.union([id])
}
}
private func recordReactionEventID(_ id: String) {
reactionEventIDs.insert(id)
if reactionEventIDs.count > maxTrackedReactionEvents {
let ownIDs = Set(ownReactionEventIDs.values)
reactionEventIDs = ownIDs.union([id])
reactionMetaByEventID = reactionMetaByEventID.filter { reactionEventIDs.contains($0.key) }
}
if deletedEventIDs.count > maxTrackedReactionEvents {
deletedEventIDs.removeAll(keepingCapacity: false)
}
}
/// 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.
@@ -415,10 +779,18 @@ final class LocationNotesManager: ObservableObject {
refresh()
}
/// Send a location note for the current geohash using the per-geohash
/// identity, optionally expiring via NIP-40 (dead drops pass 24h; the
/// composer's ∞ option passes nil) and optionally tagged urgent.
func send(content: String, nickname: String, expiresAt: Date? = nil, urgent: Bool = false) {
// MARK: - Publishing (Posts, NIP-10 Replies, NIP-25 Reactions)
/// Send a location note synchronously for the current geohash using the
/// per-geohash identity (preserved for NoticesView and existing tests).
func send(
content: String,
nickname: String,
expiresAt: Date? = nil,
urgent: Bool = false,
teleported: Bool = false,
replyTo: NostrProtocol.ThreadReference? = nil
) {
guard let trimmed = content.trimmedOrNilIfEmpty else { return }
let relays = dependencies.relayLookup(geohash, TransportConfig.nostrGeoRelayCount)
guard !relays.isEmpty else {
@@ -429,45 +801,242 @@ final class LocationNotesManager: ObservableObject {
}
do {
let id = try dependencies.deriveIdentity(geohash)
ownPubkey = id.publicKeyHex.lowercased()
let event = try NostrProtocol.createGeohashTextNote(
content: trimmed,
geohash: geohash,
senderIdentity: id,
nickname: nickname,
expiresAt: expiresAt,
urgent: urgent
urgent: urgent,
replyTo: replyTo,
teleported: teleported,
createdAt: dependencies.now()
)
dependencies.sendEvent(event, relays)
// Optimistic local-echo
let echo = Note(
id: event.id,
pubkey: id.publicKeyHex,
publishAndEcho(
event: event,
relays: relays,
content: trimmed,
createdAt: Date(timeIntervalSince1970: TimeInterval(event.created_at)),
nickname: nickname,
geohash: geohash,
expiresAt: expiresAt,
isUrgent: urgent
urgent: urgent,
teleported: teleported,
replyTo: replyTo
)
self.noteIDs.insert(event.id)
self.notes.insert(echo, at: 0)
self.enforceMemoryCap()
self.state = .ready
self.errorMessage = nil
} catch {
SecureLogger.error("LocationNotesManager: failed to send note: \(error)", category: .session)
errorMessage = Strings.failedToSend(error.localizedDescription)
}
}
/// Whether the note was published by this device's identity for the
/// current geohash (and can therefore be deleted with NIP-09).
func isOwnNote(_ note: Note) -> Bool {
guard let ownPubkey else { return false }
return note.pubkey == ownPubkey
/// Signs synchronously and publishes a kind-1 Place Feed post or NIP-10
/// reply. Supports dual-posture identity: `.placePersona` (unlinkable
/// per-geohash key, default) or `.publicHandle` (persistent primary key,
/// published to both geo relays and default relays), with automatic BLE
/// gateway uplink when internet relays are unreachable.
@discardableResult
func sendFeedPost(
content: String,
nickname: String,
expiresAt: Date? = nil,
urgent: Bool = false,
teleported: Bool = false,
replyTo: NostrProtocol.ThreadReference? = nil,
identityMode: PostingIdentityMode = .placePersona,
attachments: [NostrProtocol.MediaAttachment] = []
) -> Bool {
guard let trimmed = content.trimmedOrNilIfEmpty else { return false }
let relays = dependencies.relayLookup(geohash, TransportConfig.nostrGeoRelayCount)
let identity: NostrIdentity
do {
switch identityMode {
case .placePersona:
identity = try dependencies.deriveIdentity(geohash)
ownPubkey = identity.publicKeyHex.lowercased()
case .publicHandle:
guard let persistent = try dependencies.publicIdentity() else {
throw NostrError.cryptographicFailure
}
identity = persistent
ownPublicPubkey = persistent.publicKeyHex.lowercased()
}
} catch {
SecureLogger.error("LocationNotesManager: failed to derive identity: \(error)", category: .session)
errorMessage = Strings.failedToSend(error.localizedDescription)
return false
}
let mirrorToDefaultRelays = (identityMode == .publicHandle)
isSending = true
defer { isSending = false }
do {
let event = try NostrProtocol.createGeohashTextNote(
content: trimmed,
geohash: geohash,
senderIdentity: identity,
nickname: nickname,
expiresAt: expiresAt,
urgent: urgent,
replyTo: replyTo,
teleported: teleported,
attachments: attachments,
createdAt: dependencies.now()
)
let uplinked = !dependencies.anyRelayConnected(relays)
&& dependencies.uplinkViaMesh(event, geohash)
guard !relays.isEmpty || uplinked else {
state = .noRelays
errorMessage = Strings.noRelays
return false
}
if mirrorToDefaultRelays {
dependencies.sendToDefaultRelays(event)
}
publishAndEcho(
event: event,
relays: relays,
content: trimmed,
nickname: nickname,
expiresAt: expiresAt,
urgent: urgent,
teleported: teleported,
replyTo: replyTo,
attachments: attachments
)
return true
} catch {
SecureLogger.error("LocationNotesManager: failed to send feed note: \(error)", category: .session)
errorMessage = Strings.failedToSend(error.localizedDescription)
return false
}
}
/// Requests NIP-09 deletion of one of our own notes and removes it locally.
private func publishAndEcho(
event: NostrEvent,
relays: [String],
content: String,
nickname: String,
expiresAt: Date?,
urgent: Bool,
teleported: Bool,
replyTo: NostrProtocol.ThreadReference?,
attachments: [NostrProtocol.MediaAttachment] = []
) {
if !relays.isEmpty {
dependencies.sendEvent(event, relays)
}
let normalizedID = event.id.lowercased()
let powDifficulty = NostrProtocol.validatedPoWDifficulty(idHex: event.id, tags: event.tags)
let echo = Note(
id: normalizedID,
pubkey: event.pubkey.lowercased(),
content: content,
createdAt: Date(timeIntervalSince1970: TimeInterval(event.created_at)),
nickname: nickname,
geohash: geohash,
expiresAt: expiresAt,
isUrgent: urgent,
rootEventID: replyTo?.rootEventID,
replyToEventID: replyTo?.replyEventID,
powDifficulty: powDifficulty,
isTeleported: teleported,
attachments: attachments
)
recordNoteID(normalizedID)
if let rootID = echo.rootEventID {
insertReplySorted(echo, forRootID: rootID)
} else {
insertNoteSorted(echo)
enforceMemoryCap()
}
state = .ready
errorMessage = nil
}
/// Toggles a NIP-25 emoji reaction on a note. Adding publishes a kind-7
/// reaction (with automatic BLE gateway uplink when relays are offline);
/// removing sends a geohash-tagged NIP-09 deletion of our own kind-7 event.
@discardableResult
func toggleReaction(emoji: String, on note: Note) -> Bool {
guard let normalizedEmoji = NostrProtocol.normalizeReactionContent(emoji) else {
return false
}
let relays = dependencies.relayLookup(geohash, TransportConfig.nostrGeoRelayCount)
do {
let identity = try dependencies.deriveIdentity(geohash)
let ownHex = identity.publicKeyHex.lowercased()
ownPubkey = ownHex
let targetID = note.id.lowercased()
let key = Self.reactionTargetKey(targetID: targetID, emoji: normalizedEmoji)
let byEmoji = reactionActorsByTarget[targetID, default: [:]]
let actors = byEmoji[normalizedEmoji, default: []]
if actors.contains(ownHex) {
guard !relays.isEmpty else {
state = .noRelays
errorMessage = Strings.noRelays
return false
}
// Toggle off: remove locally and emit geohash-tagged NIP-09 deletion.
removeReaction(targetID: targetID, emoji: normalizedEmoji, actorPubkey: ownHex)
if let reactionEventID = ownReactionEventIDs.removeValue(forKey: key) {
reactionMetaByEventID.removeValue(forKey: reactionEventID)
deletedEventIDs.insert(reactionEventID)
let deletion = try NostrProtocol.createDeleteEvent(
ofEventID: reactionEventID,
senderIdentity: identity,
geohash: geohash
)
dependencies.sendEvent(deletion, relays)
}
return true
} else {
let reactionEvent = try NostrProtocol.createGeohashReactionEvent(
emoji: normalizedEmoji,
targetEventID: targetID,
targetAuthorPubkey: note.pubkey,
geohash: geohash,
senderIdentity: identity,
createdAt: dependencies.now()
)
let hasConnectedRelays = !relays.isEmpty && dependencies.anyRelayConnected(relays)
let uplinked = !hasConnectedRelays && dependencies.uplinkViaMesh(reactionEvent, geohash)
guard hasConnectedRelays || uplinked || !relays.isEmpty else {
state = .noRelays
errorMessage = Strings.noRelays
return false
}
if !relays.isEmpty {
dependencies.sendEvent(reactionEvent, relays)
}
let reactionID = reactionEvent.id.lowercased()
recordReactionEventID(reactionID)
applyReaction(
targetID: targetID,
emoji: normalizedEmoji,
actorPubkey: ownHex,
eventID: reactionID
)
return true
}
} catch {
SecureLogger.error("LocationNotesManager: failed to toggle reaction: \(error)", category: .session)
errorMessage = Strings.failedToSend(error.localizedDescription)
return false
}
}
/// Whether the note was published by either this device's per-geohash
/// identity or its persistent public handle (and can be deleted with NIP-09).
func isOwnNote(_ note: Note) -> Bool {
isOwnPubkey(note.pubkey)
}
/// Requests NIP-09 deletion of one of our own notes (top-level or reply) and removes it locally.
@discardableResult
func delete(note: Note) -> Bool {
guard isOwnNote(note) else { return false }
@@ -478,11 +1047,34 @@ final class LocationNotesManager: ObservableObject {
return false
}
do {
let identity = try dependencies.deriveIdentity(geohash)
let deletion = try NostrProtocol.createDeleteEvent(ofEventID: note.id, senderIdentity: identity)
let usedPublicHandle = ownPublicPubkey.map { note.pubkey.lowercased() == $0.lowercased() } ?? false
let identity: NostrIdentity
if usedPublicHandle, let persistent = try dependencies.publicIdentity() {
identity = persistent
} else {
identity = try dependencies.deriveIdentity(geohash)
}
let deletion = try NostrProtocol.createDeleteEvent(
ofEventID: note.id,
senderIdentity: identity,
geohash: geohash
)
dependencies.sendEvent(deletion, relays)
if usedPublicHandle {
dependencies.sendToDefaultRelays(deletion)
}
// Keep the id in noteIDs so a relay replay can't resurrect it.
notes.removeAll { $0.id == note.id }
if let rootID = note.rootEventID {
var thread = repliesByRootID[rootID] ?? []
thread.removeAll { $0.id == note.id }
if thread.isEmpty {
repliesByRootID.removeValue(forKey: rootID)
} else {
repliesByRootID[rootID] = thread
}
} else {
notes.removeAll { $0.id == note.id }
}
return true
} catch {
SecureLogger.error("LocationNotesManager: failed to delete note: \(error)", category: .session)
@@ -548,16 +1140,26 @@ final class LocationNotesManager: ObservableObject {
}
/// Panic-wipe hook: cancel relay subscriptions, stop timers, and erase
/// in-memory notes and pre-panic public key state.
/// in-memory notes, threads, reactions, and key state.
func resetForPanic() {
isSending = false
cancel()
expiryPruneTimer?.invalidate()
expiryPruneTimer = nil
directoryUpdateCancellable = nil
networkAvailableCancellable = nil
notes.removeAll(keepingCapacity: false)
repliesByRootID.removeAll(keepingCapacity: false)
reactionsByNoteID.removeAll(keepingCapacity: false)
noteIDs.removeAll(keepingCapacity: false)
reactionEventIDs.removeAll(keepingCapacity: false)
reactionActorsByTarget.removeAll(keepingCapacity: false)
reactionEmojiOrderByTarget.removeAll(keepingCapacity: false)
ownReactionEventIDs.removeAll(keepingCapacity: false)
reactionMetaByEventID.removeAll(keepingCapacity: false)
deletedEventIDs.removeAll(keepingCapacity: false)
ownPubkey = nil
ownPublicPubkey = nil
initialLoadComplete = false
}
}
+25
View File
@@ -59,6 +59,31 @@ final class LocationNotesPool {
}
}
/// Delivers a BLE-gateway-carried kind-1 or kind-7 event into any active
/// pooled manager whose 9-cell grid covers `geohash`.
func injectCarriedEvent(_ event: NostrEvent, geohash: String) {
let target = geohash.lowercased()
for entry in entries.values {
let manager = entry.manager
if manager.geohash == target || Geohash.neighbors(of: manager.geohash).contains(target) {
manager.ingestCarriedEvent(event)
}
}
}
/// Snapshot of currently loaded note counts per pooled geohash (used by
/// the 3D globe activity layer).
func activeNoteCounts() -> [String: Int] {
var counts: [String: Int] = [:]
for (gh, entry) in entries {
let count = entry.manager.notes.count
if count > 0 {
counts[gh] = count
}
}
return counts
}
/// Panic-wipe hook: cancel subscriptions, wipe in-memory notes/identities,
/// and drop every pooled manager.
func resetForPanic() {
+320
View File
@@ -0,0 +1,320 @@
//
// NostrFollowsStore.swift
// bitchat
//
// Private, local-only follow list stored in Keychain (never published as a
// public kind-3 graph) merged with Nostr pubkeys already exchanged with
// favorite peers via FavoritesPersistenceService.
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import BitFoundation
import BitLogger
import Combine
import Foundation
#if os(iOS)
import UIKit
#endif
@MainActor
final class NostrFollowsStore: ObservableObject {
struct FollowedAuthor: Codable, Equatable, Identifiable {
let pubkeyHex: String
var alias: String?
let followedAt: Date
var id: String { pubkeyHex }
var npub: String? {
guard let data = Data(hexString: pubkeyHex), data.count == 32 else { return nil }
return try? Bech32.encode(hrp: "npub", data: data)
}
}
static let shared = NostrFollowsStore()
static let maxExplicitFollows = 250
private static let keychainService = "chat.bitchat.nostr.follows"
private static let storageKey = "followed-authors"
@Published private(set) var explicitFollows: [FollowedAuthor] = []
@Published private(set) var favoriteFollowPubkeys: Set<String> = []
@Published private(set) var allFollowedPubkeys: [String] = []
private let keychain: KeychainManagerProtocol
private let favoritesProvider: () -> [FavoritesPersistenceService.FavoriteRelationship]
private var favoritesCancellable: AnyCancellable?
#if os(iOS)
private var unlockObserver: NSObjectProtocol?
#endif
/// True when the initial keychain read failed due to a transient error
/// (e.g. locked boot) rather than `.itemNotFound`. While true, writes are
/// deferred and replayed once the Keychain becomes readable so existing
/// follows are never clobbered.
private var loadUnavailable = false
private var pendingFollows: [String: FollowedAuthor] = [:]
private var pendingUnfollows: Set<String> = []
init(
keychain: KeychainManagerProtocol = KeychainManager.makeDefault(),
favoritesService: FavoritesPersistenceService? = nil,
favoritesProvider: (() -> [FavoritesPersistenceService.FavoriteRelationship])? = nil
) {
self.keychain = keychain
if let favoritesProvider {
self.favoritesProvider = favoritesProvider
} else {
let service = favoritesService ?? .shared
self.favoritesProvider = { Array(service.favorites.values) }
self.favoritesCancellable = service.$favorites
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.refreshMergedFollows()
}
}
loadExplicitFollows()
refreshMergedFollows()
#if os(iOS)
unlockObserver = NotificationCenter.default.addObserver(
forName: UIApplication.protectedDataDidBecomeAvailableNotification,
object: nil,
queue: .main
) { [weak self] _ in
Task { @MainActor [weak self] in
self?.retryDeferredLoad()
}
}
#endif
}
#if os(iOS)
deinit {
if let unlockObserver {
NotificationCenter.default.removeObserver(unlockObserver)
}
}
#endif
/// Re-attempts reading the Keychain follow list after a locked-boot failure
/// and replays any queued follow/unfollow mutations without clobbering.
func retryDeferredLoad() {
guard loadUnavailable else { return }
loadExplicitFollows()
guard !loadUnavailable else { return }
var mutated = false
if !pendingUnfollows.isEmpty {
let unfollows = pendingUnfollows
pendingUnfollows.removeAll(keepingCapacity: false)
let before = explicitFollows.count
explicitFollows.removeAll { unfollows.contains($0.pubkeyHex) }
if explicitFollows.count != before { mutated = true }
}
if !pendingFollows.isEmpty {
let queued = pendingFollows.values.sorted { $0.followedAt < $1.followedAt }
pendingFollows.removeAll(keepingCapacity: false)
for entry in queued {
if let index = explicitFollows.firstIndex(where: { $0.pubkeyHex == entry.pubkeyHex }) {
if let alias = entry.alias, explicitFollows[index].alias != alias {
explicitFollows[index].alias = alias
mutated = true
}
} else if explicitFollows.count < Self.maxExplicitFollows {
explicitFollows.insert(entry, at: 0)
mutated = true
}
}
}
if mutated {
saveExplicitFollows()
}
refreshMergedFollows()
}
/// Follow a Nostr author by 64-char hex pubkey or `npub1...`.
@discardableResult
func follow(_ pubkeyOrNpub: String, alias: String? = nil) -> Bool {
if loadUnavailable {
retryDeferredLoad()
}
guard let hex = NostrProtocol.normalizePubkeyHex(pubkeyOrNpub) else {
return false
}
let cleanAlias = alias?.trimmedOrNilIfEmpty
if let index = explicitFollows.firstIndex(where: { $0.pubkeyHex == hex }) {
if let cleanAlias, explicitFollows[index].alias != cleanAlias {
explicitFollows[index].alias = cleanAlias
if loadUnavailable {
pendingFollows[hex] = explicitFollows[index]
pendingUnfollows.remove(hex)
} else {
saveExplicitFollows()
}
}
return true
}
guard explicitFollows.count < Self.maxExplicitFollows else {
return false
}
let entry = FollowedAuthor(pubkeyHex: hex, alias: cleanAlias, followedAt: Date())
explicitFollows.insert(entry, at: 0)
if loadUnavailable {
pendingFollows[hex] = entry
pendingUnfollows.remove(hex)
} else {
saveExplicitFollows()
}
refreshMergedFollows()
return true
}
/// Remove an explicitly followed pubkey.
func unfollow(_ pubkeyHex: String) {
if loadUnavailable {
retryDeferredLoad()
}
let normalized = NostrProtocol.normalizePubkeyHex(pubkeyHex) ?? pubkeyHex.lowercased()
let before = explicitFollows.count
explicitFollows.removeAll { $0.pubkeyHex == normalized }
if loadUnavailable {
pendingFollows.removeValue(forKey: normalized)
pendingUnfollows.insert(normalized)
refreshMergedFollows()
return
}
guard explicitFollows.count != before else { return }
saveExplicitFollows()
refreshMergedFollows()
}
@discardableResult
func toggleFollow(_ pubkeyHex: String, alias: String? = nil) -> Bool {
let normalized = NostrProtocol.normalizePubkeyHex(pubkeyHex) ?? pubkeyHex.lowercased()
if isExplicitlyFollowing(normalized) {
unfollow(normalized)
return false
}
return follow(normalized, alias: alias)
}
func isExplicitlyFollowing(_ pubkeyHex: String) -> Bool {
let normalized = pubkeyHex.lowercased()
return explicitFollows.contains { $0.pubkeyHex == normalized }
}
/// True if followed explicitly OR via a favorited peer's exchanged Nostr pubkey.
func isFollowing(_ pubkeyHex: String) -> Bool {
let normalized = pubkeyHex.lowercased()
return isExplicitlyFollowing(normalized) || favoriteFollowPubkeys.contains(normalized)
}
func localAlias(for pubkeyHex: String) -> String? {
let normalized = pubkeyHex.lowercased()
if let explicit = explicitFollows.first(where: { $0.pubkeyHex == normalized })?.alias?.trimmedOrNilIfEmpty {
return explicit
}
for rel in favoritesProvider() where rel.isFavorite {
if let raw = rel.peerNostrPublicKey,
NostrProtocol.normalizePubkeyHex(raw) == normalized,
let nick = rel.peerNickname.trimmedOrNilIfEmpty,
nick != "Unknown" {
return nick
}
}
return nil
}
func refreshMergedFollows() {
var favSet = Set<String>()
for rel in favoritesProvider() where rel.isFavorite {
if let raw = rel.peerNostrPublicKey,
let hex = NostrProtocol.normalizePubkeyHex(raw) {
favSet.insert(hex)
}
}
favoriteFollowPubkeys = favSet
var seen = Set<String>()
var merged: [String] = []
for entry in explicitFollows {
if seen.insert(entry.pubkeyHex).inserted {
merged.append(entry.pubkeyHex)
}
}
for fav in favSet.sorted() {
if seen.insert(fav).inserted {
merged.append(fav)
}
}
if merged.count > Self.maxExplicitFollows {
merged = Array(merged.prefix(Self.maxExplicitFollows))
}
allFollowedPubkeys = merged
}
/// Panic-wipe hook: erase all explicitly followed pubkeys from memory and Keychain.
func resetForPanic() {
loadUnavailable = false
pendingFollows.removeAll(keepingCapacity: false)
pendingUnfollows.removeAll(keepingCapacity: false)
explicitFollows.removeAll(keepingCapacity: false)
favoriteFollowPubkeys.removeAll(keepingCapacity: false)
allFollowedPubkeys.removeAll(keepingCapacity: false)
keychain.delete(key: Self.storageKey, service: Self.keychainService)
}
// MARK: - Persistence
private func loadExplicitFollows() {
let data: Data
switch keychain.loadWithResult(key: Self.storageKey, service: Self.keychainService) {
case .success(let loadedData):
loadUnavailable = false
data = loadedData
case .itemNotFound:
loadUnavailable = false
return
case .deviceLocked, .authenticationFailed, .accessDenied, .otherError:
loadUnavailable = true
SecureLogger.warning("NostrFollowsStore: keychain read unavailable at launch; deferring writes to prevent overwrite", category: .security)
return
}
do {
let decoded = try JSONDecoder().decode([FollowedAuthor].self, from: data)
var seen = Set<String>()
explicitFollows = decoded.compactMap { entry in
guard let hex = NostrProtocol.normalizePubkeyHex(entry.pubkeyHex),
seen.insert(hex).inserted else {
return nil
}
return FollowedAuthor(
pubkeyHex: hex,
alias: entry.alias?.trimmedOrNilIfEmpty,
followedAt: entry.followedAt
)
}
} catch {
SecureLogger.error("NostrFollowsStore: failed to decode follows: \(error)", category: .session)
}
}
private func saveExplicitFollows() {
guard !loadUnavailable else {
SecureLogger.warning("NostrFollowsStore: skipping keychain save while initial load is unavailable", category: .security)
return
}
do {
let data = try JSONEncoder().encode(explicitFollows)
keychain.save(
key: Self.storageKey,
data: data,
service: Self.keychainService,
accessible: nil
)
} catch {
SecureLogger.error("NostrFollowsStore: failed to encode follows: \(error)", category: .session)
}
}
}
+360
View File
@@ -0,0 +1,360 @@
//
// NostrProfileStore.swift
// bitchat
//
// Manages:
// 1. The user's optional persistent Nostr public handle (NIP-01 kind 0),
// disabled by default so per-place unlinkable personas remain the default.
// 2. A bounded in-memory cache of remote kind-0 profiles fetched in batched,
// Tor-friendly REQs on the default relay set.
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import BitFoundation
import BitLogger
import Combine
import Foundation
#if os(iOS)
import UIKit
#endif
struct NostrProfileStoreDependencies {
typealias Subscribe = @MainActor (_ filter: NostrFilter, _ id: String, _ handler: @escaping (NostrEvent) -> Void, _ onEOSE: (() -> Void)?) -> Void
typealias Unsubscribe = @MainActor (_ id: String) -> Void
typealias SendEvent = @MainActor (_ event: NostrEvent) -> Void
var subscribe: Subscribe
var unsubscribe: Unsubscribe
var sendEvent: SendEvent
var currentIdentity: () throws -> NostrIdentity?
var now: () -> Date
/// Whether at least one default relay is currently connected. Used on EOSE
/// to distinguish a real empty response from a pre-Tor connectivity timeout.
var isAnyDefaultRelayConnected: @MainActor () -> Bool = { true }
static let live = NostrProfileStoreDependencies(
subscribe: { filter, id, handler, onEOSE in
NostrRelayManager.shared.subscribe(
filter: filter,
id: id,
relayUrls: nil,
handler: handler,
onEOSE: onEOSE
)
},
unsubscribe: { id in
NostrRelayManager.shared.unsubscribe(id: id)
},
sendEvent: { event in
NostrRelayManager.shared.sendEvent(event)
},
currentIdentity: {
try NostrIdentityBridge.shared.getCurrentNostrIdentity()
},
now: Date.init,
isAnyDefaultRelayConnected: {
NostrRelayManager.shared.isConnected
}
)
}
@MainActor
final class NostrProfileStore: ObservableObject {
struct OwnPublicProfile: Codable, Equatable, Sendable {
var isEnabled: Bool = false
var displayName: String = ""
var about: String = ""
var nip05: String = ""
var metadata: NostrProtocol.ProfileMetadata {
NostrProtocol.ProfileMetadata(
name: displayName.trimmedOrNilIfEmpty,
displayName: displayName.trimmedOrNilIfEmpty,
about: about.trimmedOrNilIfEmpty,
nip05: nip05.trimmedOrNilIfEmpty
)
}
}
struct CachedProfile: Equatable {
let metadata: NostrProtocol.ProfileMetadata
let createdAt: Int
}
static let shared = NostrProfileStore()
private static let keychainService = "chat.bitchat.nostr.profile"
private static let storageKey = "own-public-profile"
private static let maxCachedProfiles = 500
private static let fetchCooldownSeconds: TimeInterval = 10 * 60
@Published private(set) var ownProfile: OwnPublicProfile = OwnPublicProfile()
@Published private(set) var profiles: [String: CachedProfile] = [:]
private let keychain: KeychainManagerProtocol
private let dependencies: NostrProfileStoreDependencies
private var fetchOrder: [String] = []
private var lastRequestedAt: [String: Date] = [:]
private var activeSubscriptionIDs: Set<String> = []
private var pendingRetryPubkeys: Set<String> = []
private var connectivityRetryTimer: Timer?
private var loadUnavailable = false
#if os(iOS)
private var unlockObserver: NSObjectProtocol?
#endif
init(
keychain: KeychainManagerProtocol = KeychainManager.makeDefault(),
dependencies: NostrProfileStoreDependencies = .live
) {
self.keychain = keychain
self.dependencies = dependencies
loadOwnProfile()
#if os(iOS)
unlockObserver = NotificationCenter.default.addObserver(
forName: UIApplication.protectedDataDidBecomeAvailableNotification,
object: nil,
queue: .main
) { [weak self] _ in
Task { @MainActor [weak self] in
self?.retryDeferredLoad()
}
}
#endif
}
deinit {
connectivityRetryTimer?.invalidate()
#if os(iOS)
if let unlockObserver {
NotificationCenter.default.removeObserver(unlockObserver)
}
#endif
let subs = activeSubscriptionIDs
let unsubscribe = dependencies.unsubscribe
if !subs.isEmpty {
Task { @MainActor in
for id in subs {
unsubscribe(id)
}
}
}
}
private func retryDeferredLoad() {
guard loadUnavailable else { return }
loadOwnProfile()
}
// MARK: - Own Opt-In Public Handle
var isPublicHandleEnabled: Bool {
ownProfile.isEnabled
}
func ownPublicIdentity() -> NostrIdentity? {
try? dependencies.currentIdentity()
}
var ownPublicNpub: String? {
ownPublicIdentity()?.npub
}
/// Saves the user's opt-in public profile locally (Keychain) and, when
/// enabled, signs and publishes a NIP-01 kind-0 event to default relays.
@discardableResult
func saveAndPublishOwnProfile(_ updated: OwnPublicProfile) -> Bool {
if loadUnavailable {
retryDeferredLoad()
}
ownProfile = updated
saveOwnProfile()
guard updated.isEnabled else {
return true
}
guard let identity = ownPublicIdentity() else {
return false
}
do {
let now = dependencies.now()
let event = try NostrProtocol.createMetadataEvent(
profile: updated.metadata,
senderIdentity: identity,
createdAt: now
)
dependencies.sendEvent(event)
ingestMetadataEvent(event)
return true
} catch {
SecureLogger.error("NostrProfileStore: failed to publish kind-0 metadata: \(error)", category: .session)
return false
}
}
func disablePublicHandle() {
var updated = ownProfile
updated.isEnabled = false
ownProfile = updated
saveOwnProfile()
}
// MARK: - Remote Profile Lookup & Cache
func profile(for pubkeyHex: String) -> NostrProtocol.ProfileMetadata? {
profiles[pubkeyHex.lowercased()]?.metadata
}
func displayName(for pubkeyHex: String, fallbackNickname: String?) -> String {
if let preferred = profile(for: pubkeyHex)?.preferredName {
return preferred
}
return fallbackNickname?.trimmedOrNilIfEmpty ?? "anon"
}
/// Batches missing pubkeys into a single short-lived kind-0 REQ on default
/// relays and auto-closes on EOSE to keep Tor relay usage minimal.
func ensureProfiles(for pubkeys: [String]) {
let now = dependencies.now()
var toFetch: [String] = []
var seen = Set<String>()
for raw in pubkeys {
guard let hex = NostrProtocol.normalizePubkeyHex(raw),
seen.insert(hex).inserted else {
continue
}
if let last = lastRequestedAt[hex],
now.timeIntervalSince(last) < Self.fetchCooldownSeconds {
continue
}
lastRequestedAt[hex] = now
toFetch.append(hex)
if toFetch.count >= 64 { break }
}
guard !toFetch.isEmpty else { return }
let subID = "profiles-\(UUID().uuidString.prefix(8))"
activeSubscriptionIDs.insert(subID)
var receivedPubkeys = Set<String>()
let filter = NostrFilter.authorProfiles(toFetch)
dependencies.subscribe(filter, subID, { [weak self] event in
receivedPubkeys.insert(event.pubkey.lowercased())
self?.ingestMetadataEvent(event)
}, { [weak self] in
guard let self else { return }
self.activeSubscriptionIDs.remove(subID)
self.dependencies.unsubscribe(subID)
// When Tor or default relays are still disconnected, NostrRelayManager's
// 10s EOSE fallback fires before any relay responded. Clear the cooldown
// for unreceived pubkeys and retry once connectivity comes up.
if !self.dependencies.isAnyDefaultRelayConnected() {
let unreceived = toFetch.filter { !receivedPubkeys.contains($0) }
for key in unreceived {
self.lastRequestedAt.removeValue(forKey: key)
self.pendingRetryPubkeys.insert(key)
}
if !self.pendingRetryPubkeys.isEmpty {
self.scheduleConnectivityRetry()
}
}
})
}
private func scheduleConnectivityRetry() {
guard connectivityRetryTimer == nil else { return }
let timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] _ in
Task { @MainActor [weak self] in
guard let self else { return }
guard !self.pendingRetryPubkeys.isEmpty else {
self.connectivityRetryTimer?.invalidate()
self.connectivityRetryTimer = nil
return
}
guard self.dependencies.isAnyDefaultRelayConnected() else { return }
let retryList = Array(self.pendingRetryPubkeys)
self.pendingRetryPubkeys.removeAll(keepingCapacity: false)
self.connectivityRetryTimer?.invalidate()
self.connectivityRetryTimer = nil
self.ensureProfiles(for: retryList)
}
}
timer.tolerance = 1.0
connectivityRetryTimer = timer
}
func ingestMetadataEvent(_ event: NostrEvent) {
guard let metadata = NostrProtocol.parseMetadataEvent(event) else { return }
let pubkey = event.pubkey.lowercased()
if let existing = profiles[pubkey], existing.createdAt > event.created_at {
return
}
profiles[pubkey] = CachedProfile(metadata: metadata, createdAt: event.created_at)
if !fetchOrder.contains(pubkey) {
fetchOrder.append(pubkey)
if fetchOrder.count > Self.maxCachedProfiles {
let evicted = fetchOrder.removeFirst()
profiles.removeValue(forKey: evicted)
}
}
}
/// Panic-wipe hook: close active profile REQs, clear cached profiles, and
/// delete the opt-in public profile from Keychain.
func resetForPanic() {
connectivityRetryTimer?.invalidate()
connectivityRetryTimer = nil
pendingRetryPubkeys.removeAll(keepingCapacity: false)
loadUnavailable = false
for subID in activeSubscriptionIDs {
dependencies.unsubscribe(subID)
}
activeSubscriptionIDs.removeAll(keepingCapacity: false)
profiles.removeAll(keepingCapacity: false)
fetchOrder.removeAll(keepingCapacity: false)
lastRequestedAt.removeAll(keepingCapacity: false)
ownProfile = OwnPublicProfile()
keychain.delete(key: Self.storageKey, service: Self.keychainService)
}
// MARK: - Persistence
private func loadOwnProfile() {
let data: Data
switch keychain.loadWithResult(key: Self.storageKey, service: Self.keychainService) {
case .success(let loadedData):
loadUnavailable = false
data = loadedData
case .itemNotFound:
loadUnavailable = false
return
case .deviceLocked, .authenticationFailed, .accessDenied, .otherError:
loadUnavailable = true
SecureLogger.warning("NostrProfileStore: keychain read unavailable at launch; deferring writes to prevent overwrite", category: .security)
return
}
if let decoded = try? JSONDecoder().decode(OwnPublicProfile.self, from: data) {
ownProfile = decoded
}
}
private func saveOwnProfile() {
guard !loadUnavailable else {
SecureLogger.warning("NostrProfileStore: skipping keychain save while initial load is unavailable", category: .security)
return
}
do {
let data = try JSONEncoder().encode(ownProfile)
keychain.save(
key: Self.storageKey,
data: data,
service: Self.keychainService,
accessible: nil
)
} catch {
SecureLogger.error("NostrProfileStore: failed to save own profile: \(error)", category: .session)
}
}
}
+144
View File
@@ -0,0 +1,144 @@
//
// PlaceFeedModel.swift
// bitchat
//
// Pure sorting, filtering, and search organizer for the Place Feed, plus
// the Chat / Feed mode enum shared by active Place rooms.
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
/// Active surface inside a Place room (`Places` tab).
enum PlaceRoomMode: String, CaseIterable, Identifiable {
case chat
case feed
var id: String { rawValue }
}
/// Top-level surface inside the Places tab (`Explore` directory vs. merged `Feed` home stream).
enum PlacesTabMode: String, CaseIterable, Identifiable {
case explore
case feed
var id: String { rawValue }
}
/// Scope filter inside the Home Feed stream.
enum HomeFeedScope: String, CaseIterable, Identifiable {
case all
case savedPlaces
case following
var id: String { rawValue }
}
/// Cryptographic identity posture used when publishing a post or reply.
enum PostingIdentityMode: String, CaseIterable, Identifiable {
/// Default: deterministic, unlinkable per-geohash key (`HMAC(deviceSeed, geohash)`).
case placePersona
/// Opt-in: persistent primary Nostr identity (`kind 0` public handle) so followers can follow across places.
case publicHandle
var id: String { rawValue }
}
/// Sort order for the Place Feed timeline.
enum PlaceFeedSort: String, CaseIterable, Identifiable {
case latest
case top
var id: String { rawValue }
}
/// Signal filter for the Place Feed timeline.
enum PlaceFeedFilter: String, CaseIterable, Identifiable {
case all
case localOnly
case verifiedPoW
case vouched
var id: String { rawValue }
}
/// Deterministic organizer for merged Nostr + mesh-board Place Feed items.
enum PlaceFeedOrganizer {
/// Engagement score used by `.top` sort. Gives higher weight to discussion
/// (replies), then reactions, plus a small bonus for validated NIP-13 PoW.
static func engagementScore(
for item: NoticeItem,
replyCount: Int,
reactionCount: Int
) -> Int {
let powBonus = item.powDifficulty >= NostrProtocol.verifiedPoWThresholdBits ? 2 : 0
return reactionCount * 2 + replyCount * 3 + powBonus
}
static func organize(
items: [NoticeItem],
sort: PlaceFeedSort,
filter: PlaceFeedFilter,
query: String = "",
replyCount: (String) -> Int = { _ in 0 },
reactionCount: (String) -> Int = { _ in 0 },
isVouched: (NoticeItem) -> Bool = { _ in false }
) -> [NoticeItem] {
let trimmedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)
let filtered = items.filter { item in
switch filter {
case .all:
break
case .localOnly:
if item.isTeleported { return false }
case .verifiedPoW:
if !item.hasVerifiedPoW { return false }
case .vouched:
if !isVouched(item) { return false }
}
if !trimmedQuery.isEmpty {
let matchesContent = item.content.localizedCaseInsensitiveContains(trimmedQuery)
let matchesAuthor = item.author.localizedCaseInsensitiveContains(trimmedQuery)
if !matchesContent && !matchesAuthor {
return false
}
}
return true
}
return filtered.sorted { lhs, rhs in
if lhs.isUrgent != rhs.isUrgent {
return lhs.isUrgent
}
switch sort {
case .latest:
if lhs.createdAt != rhs.createdAt {
return lhs.createdAt > rhs.createdAt
}
return lhs.id < rhs.id
case .top:
let lhsScore = engagementScore(
for: lhs,
replyCount: replyCount(lhs.id),
reactionCount: reactionCount(lhs.id)
)
let rhsScore = engagementScore(
for: rhs,
replyCount: replyCount(rhs.id),
reactionCount: reactionCount(rhs.id)
)
if lhsScore != rhsScore {
return lhsScore > rhsScore
}
if lhs.createdAt != rhs.createdAt {
return lhs.createdAt > rhs.createdAt
}
return lhs.id < rhs.id
}
}
}
}
+4
View File
@@ -2108,8 +2108,12 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel
// wiped device comes back with it off, like a fresh install.
PTTSettings.reset()
NearbyNotesCounter.shared.resetForPanic()
HomeFeedManager.shared.resetForPanic()
LocationNotesPool.shared.resetForPanic()
LocationNotesDependencies.clearCachedIdentitiesForPanic()
NostrFollowsStore.shared.resetForPanic()
NostrProfileStore.shared.resetForPanic()
BlossomMediaService.shared.resetForPanic()
WaveformCache.shared.resetForPanic()
ImageDownsampler.resetForPanic()
CashuTokenDecoder.resetForPanic()
@@ -97,6 +97,7 @@ final class ChatViewModelBootstrapper {
private extension ChatViewModelBootstrapper {
func wireServiceGraph() {
LocalWebOfTrustService.shared.configure(identityManager: viewModel.identityManager)
viewModel.privateChatManager.conversationStore = viewModel.conversations
viewModel.privateChatManager.unifiedPeerService = viewModel.unifiedPeerService
viewModel.unifiedPeerService.messageRouter = viewModel.messageRouter
@@ -382,6 +383,9 @@ private extension ChatViewModelBootstrapper {
gateway.injectInbound = { [weak viewModel] event in
viewModel?.handleNostrEvent(event)
}
gateway.injectFeedInbound = { event, geohash in
LocationNotesPool.shared.injectCarriedEvent(event, geohash: geohash)
}
// The capability bit is advertised ONLY while the toggle is on; a
// change forces a re-announce so peers learn promptly.
gateway.onEnabledChanged = { [weak bleService] enabled in
@@ -0,0 +1,128 @@
//
// BlossomMediaAttachmentView.swift
// bitchat
//
// Renders a NIP-92 Blossom media attachment inside feed cards with SHA-256
// verification and Stealth/Tor tap-to-load gating so scrolling never initiates
// passive external HTTP requests.
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import SwiftUI
struct BlossomMediaAttachmentView: View {
let attachment: NostrProtocol.MediaAttachment
let requiresTapToLoad: Bool
@ThemedPalette private var palette
@State private var loadedImage: ImageDownsampler.PlatformImage?
@State private var isLoading = false
@State private var loadError: String?
init(
attachment: NostrProtocol.MediaAttachment,
requiresTapToLoad: Bool = PrivacyModeSettings.currentMode() == .stealth
|| NetworkActivationService.persistedTorPreference()
) {
self.attachment = attachment
self.requiresTapToLoad = requiresTapToLoad
}
var body: some View {
Group {
if let image = loadedImage {
platformSwiftUIImage(image)
.resizable()
.scaledToFill()
.frame(maxWidth: .infinity)
.frame(maxHeight: 240)
.clipped()
.clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: 10, style: .continuous)
.stroke(palette.cardBorder, lineWidth: 1)
)
} else {
Button(action: startLoad) {
HStack(spacing: 10) {
if isLoading {
ProgressView()
.frame(width: 22, height: 22)
} else {
Image(systemName: loadError != nil ? "exclamationmark.triangle" : "photo.badge.checkmark")
.font(.system(size: 16, weight: .semibold))
.foregroundColor(loadError != nil ? palette.alertRed : palette.locationAccent)
}
VStack(alignment: .leading, spacing: 2) {
Text(
loadError ?? (
requiresTapToLoad
? String(localized: "place_feed.media.tap_to_load_tor", defaultValue: "Tap to load image over Tor", comment: "Button prompting user to explicitly load a remote Blossom image in Stealth/Tor mode")
: String(localized: "place_feed.media.loading", defaultValue: "Loading verified image…", comment: "Status while downloading and SHA-256 verifying a remote Blossom image")
)
)
.bitchatFont(size: 12, weight: .semibold)
.foregroundColor(palette.primary)
.lineLimit(1)
Text(verbatim: "\(attachment.url.host ?? "blossom") · sha256:\(attachment.sha256Hex.prefix(8))…")
.bitchatFont(size: 10)
.foregroundColor(palette.secondary)
.lineLimit(1)
}
Spacer(minLength: 4)
}
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
.background(palette.secondary.opacity(0.08))
.overlay(
RoundedRectangle(cornerRadius: 10, style: .continuous)
.stroke(palette.cardBorder, lineWidth: 1)
)
.clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
}
.buttonStyle(.plain)
.disabled(isLoading)
}
}
.onAppear {
if let cached = BlossomMediaService.shared.cachedImage(for: attachment.sha256Hex) {
loadedImage = cached
} else if !requiresTapToLoad {
startLoad()
}
}
}
private func startLoad() {
guard !isLoading, loadedImage == nil else { return }
isLoading = true
loadError = nil
Task {
do {
let image = try await BlossomMediaService.shared.fetchVerifiedImage(for: attachment)
await MainActor.run {
self.loadedImage = image
self.isLoading = false
}
} catch {
await MainActor.run {
self.loadError = error.localizedDescription
self.isLoading = false
}
}
}
}
private func platformSwiftUIImage(_ image: ImageDownsampler.PlatformImage) -> Image {
#if os(iOS)
Image(uiImage: image)
#else
Image(nsImage: image)
#endif
}
}
+105 -29
View File
@@ -27,6 +27,7 @@ struct ContentHeaderView: View {
var onSelectTab: ((AppRootTab) -> Void)? = nil
var onBack: (() -> Void)? = nil
var placeTitle: String? = nil
var placeMode: Binding<PlaceRoomMode>? = nil
var isSearchActive: Bool = false
var onToggleSearch: (() -> Void)? = nil
var onOpenWalkieTalkie: (() -> Void)? = nil
@@ -145,6 +146,10 @@ struct ContentHeaderView: View {
.modifier(PulsingOpacityModifier(active: someoneSpeaking))
}
if let placeMode {
placeModeToggle(selection: placeMode)
}
if let onToggleSearch {
TopBarIconButton(
systemImage: "magnifyingglass",
@@ -155,39 +160,75 @@ struct ContentHeaderView: View {
}
if case .location(let channel) = locationChannelsModel.selectedChannel {
TopBarIconButton(
systemImage: locationChannelsModel.isBookmarked(channel.geohash) ? "bookmark.fill" : "bookmark",
accessibilityLabel: String(
format: String(localized: "content.accessibility.toggle_bookmark", comment: "Accessibility label for toggling a geohash bookmark"),
locale: .current,
channel.geohash
),
color: locationChannelsModel.isBookmarked(channel.geohash) ? palette.locationAccent : palette.secondary,
action: { locationChannelsModel.toggleBookmark(channel.geohash) }
)
if placeMode != nil {
Menu {
Button {
locationChannelsModel.toggleBookmark(channel.geohash)
} label: {
Label(
String(
format: String(localized: "content.accessibility.toggle_bookmark", comment: "Accessibility label for toggling a geohash bookmark"),
locale: .current,
channel.geohash
),
systemImage: locationChannelsModel.isBookmarked(channel.geohash) ? "bookmark.fill" : "bookmark"
)
}
Button {
requestHeaderShare(forGeohash: channel.geohash)
} label: {
Label(
String(localized: "channel.share.action", defaultValue: "share channel", comment: "Accessibility label for sharing the active location channel"),
systemImage: "square.and.arrow.up"
)
}
} label: {
Image(systemName: "ellipsis")
.font(.system(size: ChromeMetrics.iconSize, weight: .medium))
.foregroundColor(locationChannelsModel.isBookmarked(channel.geohash) ? palette.locationAccent : palette.secondary)
.frame(width: ChromeMetrics.iconTapSize, height: ChromeMetrics.iconTapSize)
.contentShape(Rectangle())
}
.menuStyle(.borderlessButton)
.menuIndicator(.hidden)
.buttonStyle(.plain)
} else {
TopBarIconButton(
systemImage: locationChannelsModel.isBookmarked(channel.geohash) ? "bookmark.fill" : "bookmark",
accessibilityLabel: String(
format: String(localized: "content.accessibility.toggle_bookmark", comment: "Accessibility label for toggling a geohash bookmark"),
locale: .current,
channel.geohash
),
color: locationChannelsModel.isBookmarked(channel.geohash) ? palette.locationAccent : palette.secondary,
action: { locationChannelsModel.toggleBookmark(channel.geohash) }
)
TopBarIconButton(
systemImage: "square.and.arrow.up",
accessibilityLabel: String(localized: "channel.share.action", defaultValue: "share channel", comment: "Accessibility label for sharing the active location channel"),
color: palette.secondary,
action: { requestHeaderShare(forGeohash: channel.geohash) }
)
TopBarIconButton(
systemImage: "square.and.arrow.up",
accessibilityLabel: String(localized: "channel.share.action", defaultValue: "share channel", comment: "Accessibility label for sharing the active location channel"),
color: palette.secondary,
action: { requestHeaderShare(forGeohash: channel.geohash) }
)
}
}
TopBarIconButton(
systemImage: scopeHasNotices || unseenNoticesCount > 0 ? "pin.fill" : "pin",
accessibilityLabel: String(localized: "content.accessibility.notices", defaultValue: "Notices", comment: "Accessibility label for the notices button"),
color: scopeHasNotices || unseenNoticesCount > 0 ? Color.orange : palette.secondary,
badgeCount: unseenNoticesCount,
action: {
if case .location(let channel) = locationChannelsModel.selectedChannel {
boardAlertsModel.markSeen(forScopes: [channel.geohash])
} else {
boardAlertsModel.markSeen(forScopes: [""])
if placeMode == nil {
TopBarIconButton(
systemImage: scopeHasNotices || unseenNoticesCount > 0 ? "pin.fill" : "pin",
accessibilityLabel: String(localized: "content.accessibility.notices", defaultValue: "Notices", comment: "Accessibility label for the notices button"),
color: scopeHasNotices || unseenNoticesCount > 0 ? Color.orange : palette.secondary,
badgeCount: unseenNoticesCount,
action: {
if case .location(let channel) = locationChannelsModel.selectedChannel {
boardAlertsModel.markSeen(forScopes: [channel.geohash])
} else {
boardAlertsModel.markSeen(forScopes: [""])
}
appChromeModel.presentNotices()
}
appChromeModel.presentNotices()
}
)
)
}
if case .location = locationChannelsModel.selectedChannel {
Button {
@@ -277,6 +318,41 @@ struct ContentHeaderView: View {
}
}
private func placeModeToggle(selection: Binding<PlaceRoomMode>) -> some View {
HStack(spacing: 2) {
ForEach(PlaceRoomMode.allCases) { mode in
let isSelected = selection.wrappedValue == mode
Button {
withAnimation(.easeInOut(duration: 0.16)) {
selection.wrappedValue = mode
}
} label: {
Text(
mode == .chat
? String(localized: "place_feed.mode.chat", defaultValue: "Chat", comment: "Segment label for real-time chat inside a Place room")
: String(localized: "place_feed.mode.feed", defaultValue: "Feed", comment: "Segment label for the persistent Place Feed inside a Place room")
)
.bitchatFont(size: 12, weight: isSelected ? .semibold : .medium)
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(isSelected ? palette.accent : Color.clear)
.foregroundColor(isSelected ? palette.accentForeground : palette.secondary)
.clipShape(Capsule())
.contentShape(Rectangle())
}
.buttonStyle(.plain)
}
}
.padding(2)
.background(palette.cardBackground)
.overlay(
Capsule().stroke(palette.cardBorder, lineWidth: 1)
)
.clipShape(Capsule())
.accessibilityElement(children: .contain)
.accessibilityLabel(String(localized: "place_feed.accessibility.mode_picker", defaultValue: "Place view mode", comment: "Accessibility label for the Chat / Feed mode switcher in a Place room"))
}
private func requestHeaderShare(forGeohash geohash: String) {
if ChannelShare.shouldWarn(forGeohash: geohash) {
pendingShareGeohash = geohash
+92 -33
View File
@@ -206,6 +206,7 @@ struct ContentView: View {
@State private var selectedTab: AppRootTab
@State private var activePlaceChannel: GeohashChannel? = nil
@State private var activePlaceTitle: String? = nil
@State private var activePlaceMode: PlaceRoomMode = .chat
@State private var showAddFriendSheet = false
@State private var showCreateGroupSheet = false
@State private var showOnboardingSheet = false
@@ -711,7 +712,7 @@ struct ContentView: View {
)
case .nearby:
mainContent(onBack: nil, placeTitle: nil)
mainContent(onBack: nil, placeTitle: nil, placeChannel: nil)
case .places:
PlacesTabView(
@@ -726,12 +727,17 @@ struct ContentView: View {
)
mainContent(
onBack: {
activePlaceMode = .chat
activePlaceChannel = nil
activePlaceTitle = nil
},
placeTitle: placeName
placeTitle: placeName,
placeChannel: channel
)
}
.onChange(of: activePlaceChannel) { _ in
activePlaceMode = .chat
}
case .settings:
AppInfoView(
@@ -760,53 +766,101 @@ struct ContentView: View {
/// Older OS versions without `.contentMargins` keep single-level
/// `.safeAreaInset` so programmatic `scrollTo` targets still clear the bar.
@ViewBuilder
private func mainContent(onBack: (() -> Void)?, placeTitle: String?) -> some View {
private func mainContent(
onBack: (() -> Void)?,
placeTitle: String?,
placeChannel: GeohashChannel?
) -> some View {
let isShowingPlaceFeed = placeChannel != nil && activePlaceMode == .feed
let modeBinding: Binding<PlaceRoomMode>? = placeChannel != nil ? $activePlaceMode : nil
if usesGlassLayout {
if #available(iOS 17.0, macOS 14.0, *) {
publicMessageList
.overlay(alignment: .top) {
headerView(onBack: onBack, placeTitle: placeTitle)
Group {
if let placeChannel, isShowingPlaceFeed {
PlaceFeedView(
channel: placeChannel,
senderNickname: appChromeModel.nickname,
board: appChromeModel.boardManager,
isTeleported: locationChannelsModel.teleported,
searchQuery: isPublicSearchPresented ? publicSearchQuery : "",
topContentInset: glassTopContentInset,
usesOverlayChrome: true
)
} else {
publicMessageList
}
}
.overlay(alignment: .top) {
headerView(onBack: onBack, placeTitle: placeTitle, placeMode: modeBinding)
.onGeometryChange(for: CGFloat.self) { proxy in
proxy.size.height
} action: { height in
if abs(topChromeHeight - height) > 0.5 {
topChromeHeight = height
}
}
}
.overlay(alignment: .bottom) {
if selectedPrivatePeerID == nil && !isShowingPlaceFeed {
composerView
.onGeometryChange(for: CGFloat.self) { proxy in
proxy.size.height
} action: { height in
if abs(topChromeHeight - height) > 0.5 {
topChromeHeight = height
if abs(bottomChromeHeight - height) > 0.5 {
bottomChromeHeight = height
}
}
}
.overlay(alignment: .bottom) {
if selectedPrivatePeerID == nil {
composerView
.onGeometryChange(for: CGFloat.self) { proxy in
proxy.size.height
} action: { height in
if abs(bottomChromeHeight - height) > 0.5 {
bottomChromeHeight = height
}
}
}
}
}
} else {
publicMessageList
.safeAreaInset(edge: .top, spacing: 0) {
headerView(onBack: onBack, placeTitle: placeTitle)
Group {
if let placeChannel, isShowingPlaceFeed {
PlaceFeedView(
channel: placeChannel,
senderNickname: appChromeModel.nickname,
board: appChromeModel.boardManager,
isTeleported: locationChannelsModel.teleported,
searchQuery: isPublicSearchPresented ? publicSearchQuery : "",
topContentInset: 0,
usesOverlayChrome: false
)
} else {
publicMessageList
}
.safeAreaInset(edge: .bottom, spacing: 0) {
if selectedPrivatePeerID == nil {
composerView
}
}
.safeAreaInset(edge: .top, spacing: 0) {
headerView(onBack: onBack, placeTitle: placeTitle, placeMode: modeBinding)
}
.safeAreaInset(edge: .bottom, spacing: 0) {
if selectedPrivatePeerID == nil && !isShowingPlaceFeed {
composerView
}
}
}
} else {
VStack(spacing: 0) {
headerView(onBack: onBack, placeTitle: placeTitle)
headerView(onBack: onBack, placeTitle: placeTitle, placeMode: modeBinding)
publicMessageList
.background(palette.background)
if let placeChannel, isShowingPlaceFeed {
PlaceFeedView(
channel: placeChannel,
senderNickname: appChromeModel.nickname,
board: appChromeModel.boardManager,
isTeleported: locationChannelsModel.teleported,
searchQuery: isPublicSearchPresented ? publicSearchQuery : "",
topContentInset: 0,
usesOverlayChrome: false
)
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
publicMessageList
.background(palette.background)
.frame(maxWidth: .infinity, maxHeight: .infinity)
if selectedPrivatePeerID == nil {
composerView
if selectedPrivatePeerID == nil {
composerView
}
}
}
}
@@ -826,7 +880,11 @@ struct ContentView: View {
return matches[idx]
}
private func headerView(onBack: (() -> Void)?, placeTitle: String?) -> some View {
private func headerView(
onBack: (() -> Void)?,
placeTitle: String?,
placeMode: Binding<PlaceRoomMode>?
) -> some View {
let matches = publicSearchMatches
return VStack(spacing: 0) {
ContentHeaderView(
@@ -835,6 +893,7 @@ struct ContentView: View {
onSelectTab: selectRootTab,
onBack: onBack,
placeTitle: placeTitle,
placeMode: placeMode,
isSearchActive: isPublicSearchPresented,
onToggleSearch: {
withAnimation(.easeInOut(duration: 0.18)) {
+42 -6
View File
@@ -12,6 +12,7 @@ import SwiftUI
/// the crosshair is the selection; zooming changes precision, and the +/- buttons step
/// precision while framing the cell.
struct GeohashPickerView: View {
let activityBeacons: [GlobeActivityBeacon]
let onSelect: (String) -> Void
let onCancel: () -> Void
@@ -35,9 +36,11 @@ struct GeohashPickerView: View {
init(
initialGeohash: String?,
nearbyGeohashes: [String] = [],
activityBeacons: [GlobeActivityBeacon] = [],
onSelect: @escaping (String) -> Void,
onCancel: @escaping () -> Void
) {
self.activityBeacons = activityBeacons
self.onSelect = onSelect
self.onCancel = onCancel
let target = Self.initialTarget(initialGeohash: initialGeohash, nearbyGeohashes: nearbyGeohashes)
@@ -67,8 +70,13 @@ struct GeohashPickerView: View {
.ignoresSafeArea()
if let world {
GlobeView(state: state, colors: globeColors, world: world)
.ignoresSafeArea()
GlobeView(
state: state,
colors: globeColors,
world: world,
activityBeacons: activityBeacons
)
.ignoresSafeArea()
}
VStack(spacing: 0) {
@@ -106,10 +114,25 @@ struct GeohashPickerView: View {
private var bottomControls: some View {
HStack(spacing: 10) {
VStack(alignment: .leading, spacing: 2) {
Text(verbatim: hasSelection ? "#\(state.selectedGeohash)" : Strings.noSelection)
.bitchatFont(size: 16, weight: .bold)
.foregroundColor(palette.primary)
.lineLimit(1)
HStack(spacing: 6) {
Text(verbatim: hasSelection ? "#\(state.selectedGeohash)" : Strings.noSelection)
.bitchatFont(size: 16, weight: .bold)
.foregroundColor(palette.primary)
.lineLimit(1)
if let activeCount = matchingActivityCount, activeCount > 0 {
HStack(spacing: 3) {
Image(systemName: "flame.fill")
.font(.system(size: 10, weight: .semibold))
Text(verbatim: "\(activeCount)")
.bitchatFont(size: 11, weight: .semibold)
}
.foregroundColor(.orange)
.padding(.horizontal, 6)
.padding(.vertical, 2)
.background(Color.orange.opacity(0.16))
.clipShape(Capsule())
}
}
if hasSelection {
Text(verbatim: "\(GeohashCoverage.level(forLength: state.precision).displayName) · \(GeohashCoverage.string(forPrecision: state.precision))")
.bitchatFont(size: 11)
@@ -175,6 +198,19 @@ struct GeohashPickerView: View {
private var hasSelection: Bool { !state.selectedGeohash.isEmpty }
/// Total live activity in or directly inside the crosshair's selected geohash cell.
private var matchingActivityCount: Int? {
guard hasSelection else { return nil }
let selected = state.selectedGeohash.lowercased()
let total = activityBeacons.reduce(0) { sum, beacon in
if beacon.geohash == selected || beacon.geohash.hasPrefix(selected) || selected.hasPrefix(beacon.geohash) {
return sum + beacon.activityCount
}
return sum
}
return total > 0 ? total : nil
}
// MARK: - Globe palette
/// Fixed land/ocean tones shared with the Android picker; the accent follows the
+130 -1
View File
@@ -29,6 +29,56 @@ struct GlobeColors: Equatable {
let star: Color
}
/// Live spatial activity marker projected onto the 3D globe (active chat/feed
/// places and bookmarked Saved Places).
struct GlobeActivityBeacon: Equatable, Sendable, Identifiable {
let geohash: String
let lat: Double
let lon: Double
/// Recent chat messages + feed notes observed in this cell.
let activityCount: Int
let isBookmarked: Bool
var id: String { geohash }
init(geohash: String, activityCount: Int, isBookmarked: Bool = false) {
let norm = geohash.lowercased()
let center = Geohash.decodeCenter(norm)
self.geohash = norm
self.lat = center.lat
self.lon = center.lon
self.activityCount = max(0, activityCount)
self.isBookmarked = isBookmarked
}
static func buildBeacons(
chatCounts: [String: Int],
noteCounts: [String: Int],
bookmarks: [String]
) -> [GlobeActivityBeacon] {
var combined: [String: Int] = [:]
for (gh, count) in chatCounts where Geohash.isValidGeohash(gh) && count > 0 {
combined[gh.lowercased(), default: 0] += count
}
for (gh, count) in noteCounts where Geohash.isValidGeohash(gh) && count > 0 {
combined[gh.lowercased(), default: 0] += count
}
let bookmarkSet = Set(bookmarks.map { $0.lowercased() }.filter(Geohash.isValidGeohash))
for gh in bookmarkSet where combined[gh] == nil {
combined[gh] = 0
}
return combined
.map { gh, count in
GlobeActivityBeacon(
geohash: gh,
activityCount: count,
isBookmarked: bookmarkSet.contains(gh)
)
}
.sorted { ($0.activityCount, $0.geohash) > ($1.activityCount, $1.geohash) }
}
}
/// Interactive orthographic globe: drag to spin (with inertia), pinch to zoom, tap to
/// focus, double tap to zoom in. The selected geohash is always the cell under the
/// crosshair at the screen center.
@@ -37,6 +87,7 @@ struct GlobeView: View {
@ObservedObject private var camera: GlobeCameraState
let colors: GlobeColors
let world: GlobeWorldData
let activityBeacons: [GlobeActivityBeacon]
@Environment(\.displayScale) private var displayScale
@Environment(\.appTheme) private var theme
@@ -46,11 +97,17 @@ struct GlobeView: View {
@State private var selectionFeedback = UISelectionFeedbackGenerator()
#endif
init(state: GlobeState, colors: GlobeColors, world: GlobeWorldData) {
init(
state: GlobeState,
colors: GlobeColors,
world: GlobeWorldData,
activityBeacons: [GlobeActivityBeacon] = []
) {
self.state = state
self._camera = ObservedObject(wrappedValue: state.camera)
self.colors = colors
self.world = world
self.activityBeacons = activityBeacons
}
var body: some View {
@@ -69,6 +126,7 @@ struct GlobeView: View {
detail: state.frameDetail,
colors: colors,
world: world,
activityBeacons: activityBeacons,
pixel: 1 / max(displayScale, 1),
fontDesign: theme.bodyFontDesign
)
@@ -230,6 +288,7 @@ private struct GlobeRenderer {
let detail: GlobeMotionDetail.Frame
let colors: GlobeColors
let world: GlobeWorldData
let activityBeacons: [GlobeActivityBeacon]
/// One device pixel in points; hairline widths are specified in pixels.
let pixel: Double
let fontDesign: Font.Design
@@ -370,6 +429,7 @@ private struct GlobeRenderer {
// Dots follow the zoom at every detail level; only their labels wait for rest.
drawCities(in: &context, projector: projector, cx: cx, cy: cy, r: r, size: size)
drawActivityBeacons(in: &context, projector: projector, cx: cx, cy: cy, r: r, size: size)
// The grid is drawn at every detail level, including while dragging.
if !selectedGeohash.isEmpty {
@@ -379,6 +439,75 @@ private struct GlobeRenderer {
}
}
private func drawActivityBeacons(
in context: inout GraphicsContext,
projector: GlobeMath.PreparedProjector,
cx: Double,
cy: Double,
r: Double,
size: CGSize
) {
guard !activityBeacons.isEmpty else { return }
for beacon in activityBeacons {
let projected = projector.project(GlobeMath.Terms(lat: beacon.lat, lon: beacon.lon))
guard projected.cosC > 0.05 else { continue }
let sx = cx + projected.x * r
let sy = cy - projected.y * r
guard sx >= -24, sx <= Double(size.width) + 24,
sy >= -24, sy <= Double(size.height) + 24 else {
continue
}
let isActive = beacon.activityCount > 0
let haloRadius: Double = isActive
? min(18.0, 8.0 + log2(Double(beacon.activityCount) + 1.0) * 3.0)
: 7.0
let coreRadius: Double = isActive ? 3.5 : 2.5
let beaconColor: Color = isActive ? Color.orange : colors.accent
let haloRect = CGRect(
x: sx - haloRadius,
y: sy - haloRadius,
width: haloRadius * 2,
height: haloRadius * 2
)
context.fill(
Path(ellipseIn: haloRect),
with: .radialGradient(
Gradient(stops: [
.init(color: beaconColor.opacity(isActive ? 0.55 : 0.35), location: 0),
.init(color: beaconColor.opacity(0.0), location: 1)
]),
center: CGPoint(x: sx, y: sy),
startRadius: 0,
endRadius: haloRadius
)
)
let coreRect = CGRect(
x: sx - coreRadius,
y: sy - coreRadius,
width: coreRadius * 2,
height: coreRadius * 2
)
context.fill(Path(ellipseIn: coreRect), with: .color(beaconColor))
if beacon.isBookmarked {
let ringRadius = coreRadius + 2.5
let ringRect = CGRect(
x: sx - ringRadius,
y: sy - ringRadius,
width: ringRadius * 2,
height: ringRadius * 2
)
context.stroke(
Path(ellipseIn: ringRect),
with: .color(colors.accent.opacity(0.85)),
lineWidth: 1.2 * pixel
)
}
}
}
private var visibleCells: [String] {
var cells = [selectedGeohash]
for neighbor in Geohash.neighbors(of: selectedGeohash) where !cells.contains(neighbor) {
+510
View File
@@ -0,0 +1,510 @@
//
// HomeFeedView.swift
// bitchat
//
// Merged Home Feed across Saved Places (bookmarked geohashes via
// LocationNotesPool) and Followed authors (private Keychain follow list +
// favorited mesh peers' Nostr keys), with opt-in global kind-1 posting.
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import SwiftUI
struct HomeFeedView: View {
let senderNickname: String
let topContentInset: CGFloat
let usesOverlayChrome: Bool
let onSelectPlace: (String, String?) -> Void
let onExplorePlaces: () -> Void
let onOpenProfileSheet: () -> Void
/// Optional injected manager for tests and previews.
@ObservedObject var feedManager: HomeFeedManager
@EnvironmentObject private var locationChannelsModel: LocationChannelsModel
@ObservedObject private var followsStore = NostrFollowsStore.shared
@ObservedObject private var profileStore = NostrProfileStore.shared
@Environment(\.dynamicTypeSize) private var dynamicTypeSize
@ThemedPalette private var palette
@State private var scope: HomeFeedScope = .all
@State private var sort: PlaceFeedSort = .latest
@State private var filter: PlaceFeedFilter = .all
@State private var draft = ""
@State private var selectedThread: ThreadSelection?
@State private var bottomComposerHeight: CGFloat = 0
private struct ThreadSelection: Identifiable {
let note: LocationNotesManager.Note
let geohash: String
let manager: LocationNotesManager
var id: String { note.id }
}
@MainActor
init(
senderNickname: String,
topContentInset: CGFloat = 0,
usesOverlayChrome: Bool = false,
onSelectPlace: @escaping (String, String?) -> Void,
onExplorePlaces: @escaping () -> Void,
onOpenProfileSheet: @escaping () -> Void,
feedManager: HomeFeedManager? = nil
) {
self.senderNickname = senderNickname
self.topContentInset = topContentInset
self.usesOverlayChrome = usesOverlayChrome
self.onSelectPlace = onSelectPlace
self.onExplorePlaces = onExplorePlaces
self.onOpenProfileSheet = onOpenProfileSheet
self.feedManager = feedManager ?? .shared
}
private var visibleItems: [HomeFeedItem] {
feedManager.filteredItems(scope: scope, sort: sort, filter: filter)
}
private var hasAnySources: Bool {
!locationChannelsModel.bookmarks.isEmpty
|| !followsStore.allFollowedPubkeys.isEmpty
|| profileStore.isPublicHandleEnabled
}
private var maxDraftLines: Int {
dynamicTypeSize.isAccessibilitySize ? 5 : 3
}
private var sendEnabled: Bool {
let trimmed = draft.trimmed
return profileStore.isPublicHandleEnabled
&& !trimmed.isEmpty
&& trimmed.utf8.count <= BoardWireConstants.contentMaxBytes
&& !feedManager.isSending
}
var body: some View {
contentLayout
.onAppear {
feedManager.activate(
bookmarks: locationChannelsModel.bookmarks,
followedPubkeys: followsStore.allFollowedPubkeys
)
}
.onChange(of: locationChannelsModel.bookmarks) { bookmarks in
feedManager.updateSources(
bookmarks: bookmarks,
followedPubkeys: followsStore.allFollowedPubkeys
)
}
.onChange(of: followsStore.allFollowedPubkeys) { follows in
feedManager.updateSources(
bookmarks: locationChannelsModel.bookmarks,
followedPubkeys: follows
)
}
.onDisappear {
if feedManager === HomeFeedManager.shared {
feedManager.deactivate()
}
}
.sheet(item: $selectedThread) { selection in
PlaceThreadSheet(
rootNote: selection.note,
geohash: selection.geohash,
senderNickname: senderNickname,
isTeleported: false,
manager: selection.manager
)
}
}
@ViewBuilder
private var contentLayout: some View {
if usesOverlayChrome {
if #available(iOS 17.0, macOS 14.0, *) {
scrollList
.contentMargins(.top, topContentInset, for: .scrollContent)
.contentMargins(.top, topContentInset, for: .scrollIndicators)
.contentMargins(.bottom, max(bottomComposerHeight, 84), for: .scrollContent)
.contentMargins(.bottom, max(bottomComposerHeight, 84), for: .scrollIndicators)
.overlay(alignment: .bottom) {
composerBar
.background(
GeometryReader { proxy in
Color.clear.preference(key: HomeComposerHeightKey.self, value: proxy.size.height)
}
)
}
.onPreferenceChange(HomeComposerHeightKey.self) { height in
if abs(bottomComposerHeight - height) > 0.5 {
bottomComposerHeight = height
}
}
} else {
scrollList
.safeAreaInset(edge: .bottom, spacing: 0) {
composerBar
}
}
} else {
VStack(spacing: 0) {
scrollList
composerBar
}
}
}
private var scrollList: some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: 10) {
scopeAndFilterBar
if feedManager.isLoadingFollowing && visibleItems.isEmpty {
HStack(spacing: 10) {
ProgressView()
Text(String(localized: "location_notes.loading_notes"))
.bitchatFont(size: 12)
.foregroundColor(palette.secondary)
Spacer()
}
.padding(.vertical, 6)
}
if let error = feedManager.errorMessage {
ThemedCard {
HStack(spacing: 6) {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundColor(palette.alertRed)
Text(error)
.bitchatFont(size: 12)
.foregroundColor(palette.primary)
Spacer()
}
Button(String(localized: "location_notes.action.dismiss")) {
feedManager.clearError()
}
.bitchatFont(size: 12, weight: .semibold)
.foregroundColor(palette.accent)
.buttonStyle(.plain)
}
}
if visibleItems.isEmpty {
emptyStateCard
} else {
ForEach(visibleItems) { item in
let placeLabel = item.savedPlaceGeohash.map { gh -> String in
if let name = locationChannelsModel.bookmarkNames[gh]?.trimmedOrNilIfEmpty {
return "\(name) · #\(gh)"
}
return "#\(gh)"
}
let isOwn = feedManager.isOwn(item)
let authorHex = item.note.pubkey
PlaceFeedPostCard(
item: item.noticeItem,
isOwn: isOwn,
replyCount: feedManager.replyCount(for: item),
reactions: feedManager.reactions(for: item),
placeBadgeLabel: placeLabel,
isFollowingAuthor: followsStore.isFollowing(authorHex),
onTapPlace: item.savedPlaceGeohash.map { gh in
{
onSelectPlace(gh, locationChannelsModel.bookmarkNames[gh])
}
},
onToggleFollow: isOwn ? nil : {
let alias = profileStore.displayName(
for: authorHex,
fallbackNickname: item.note.nickname
)
followsStore.toggleFollow(authorHex, alias: alias)
},
onOpenThread: {
if let gh = item.savedPlaceGeohash,
let manager = feedManager.manager(forGeohash: gh) {
selectedThread = ThreadSelection(
note: item.note,
geohash: gh,
manager: manager
)
}
},
onToggleReaction: { emoji in
feedManager.toggleReaction(emoji: emoji, on: item)
},
onDelete: {
feedManager.delete(item)
}
)
}
}
}
.padding(.horizontal, 14)
.padding(.vertical, 10)
}
.scrollDismissesKeyboard(.interactively)
.refreshable {
feedManager.refresh()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(ThemedRootBackground())
}
private var scopeAndFilterBar: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 6) {
ForEach(HomeFeedScope.allCases) { option in
let isSelected = scope == option
Button {
scope = option
} label: {
Text(scopeTitle(option))
.bitchatFont(size: 12, weight: isSelected ? .semibold : .medium)
.padding(.horizontal, 10)
.padding(.vertical, 5)
.background(isSelected ? palette.accent : palette.cardBackground)
.foregroundColor(isSelected ? palette.accentForeground : palette.secondary)
.overlay(
Capsule().stroke(isSelected ? Color.clear : palette.cardBorder, lineWidth: 1)
)
.clipShape(Capsule())
}
.buttonStyle(.plain)
}
Rectangle()
.fill(palette.divider)
.frame(width: 1, height: 16)
.padding(.horizontal, 2)
ForEach(PlaceFeedSort.allCases) { option in
let isSelected = sort == option
Button {
sort = option
} label: {
Text(
option == .latest
? String(localized: "place_feed.sort.latest", defaultValue: "Latest", comment: "Sort option showing newest posts first")
: String(localized: "place_feed.sort.top", defaultValue: "Top", comment: "Sort option ranking posts by engagement")
)
.bitchatFont(size: 12, weight: isSelected ? .semibold : .medium)
.padding(.horizontal, 9)
.padding(.vertical, 5)
.background(isSelected ? palette.locationAccent.opacity(0.18) : palette.cardBackground)
.foregroundColor(isSelected ? palette.locationAccent : palette.secondary)
.overlay(
Capsule().stroke(isSelected ? palette.locationAccent.opacity(0.45) : palette.cardBorder, lineWidth: 1)
)
.clipShape(Capsule())
}
.buttonStyle(.plain)
}
Button {
filter = (filter == .vouched) ? .all : .vouched
} label: {
let isSelected = filter == .vouched
HStack(spacing: 4) {
Image(systemName: "checkmark.seal.fill")
.font(.system(size: 10, weight: .semibold))
Text(String(localized: "place_feed.filter.vouched", defaultValue: "Vouched", comment: "Filter option showing posts from in-person verified or vouched authors"))
.bitchatFont(size: 12, weight: isSelected ? .semibold : .medium)
}
.padding(.horizontal, 9)
.padding(.vertical, 5)
.background(isSelected ? palette.locationAccent.opacity(0.18) : palette.cardBackground)
.foregroundColor(isSelected ? palette.locationAccent : palette.secondary)
.overlay(
Capsule().stroke(isSelected ? palette.locationAccent.opacity(0.45) : palette.cardBorder, lineWidth: 1)
)
.clipShape(Capsule())
}
.buttonStyle(.plain)
if locationChannelsModel.userTorEnabled {
HStack(spacing: 3) {
Image(systemName: "shield.lefthalf.filled")
.font(.system(size: 10, weight: .semibold))
Text(String(localized: "place_feed.badge.tor", defaultValue: "Tor", comment: "Tor indicator badge"))
.bitchatFont(size: 11, weight: .semibold)
}
.foregroundColor(palette.locationAccent)
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(palette.locationAccent.opacity(0.12))
.clipShape(Capsule())
}
}
.padding(.vertical, 2)
}
}
private var emptyStateCard: some View {
VStack(spacing: 12) {
Image(systemName: hasAnySources ? "text.bubble" : "globe.americas.fill")
.font(.system(size: 24, weight: .medium))
.foregroundColor(palette.secondary)
.frame(width: 52, height: 52)
.background(palette.cardBackground)
.clipShape(Circle())
Text(
hasAnySources
? String(localized: "home_feed.empty.quiet_title", defaultValue: "Quiet across your feed", comment: "Empty state title when Saved Places and Following have no posts yet")
: String(localized: "home_feed.empty.setup_title", defaultValue: "Build your spatial feed", comment: "Empty state title when user has no Saved Places or Following accounts")
)
.bitchatFont(size: 15, weight: .semibold)
.foregroundColor(palette.primary)
Text(
hasAnySources
? String(localized: "home_feed.empty.quiet_subtitle", defaultValue: "Posts from your saved places and followed accounts will appear here.", comment: "Empty state subtitle when feed has sources but no posts yet")
: String(localized: "home_feed.empty.setup_subtitle", defaultValue: "Bookmark places on the globe or follow people privately by npub to build a unified timeline.", comment: "Empty state subtitle explaining how to populate Home Feed")
)
.bitchatFont(size: 13)
.foregroundColor(palette.secondary)
.multilineTextAlignment(.center)
HStack(spacing: 10) {
Button(action: onExplorePlaces) {
Text(String(localized: "home_feed.action.explore_places", defaultValue: "Explore Places", comment: "Button switching to Places directory"))
.bitchatFont(size: 13, weight: .semibold)
.padding(.horizontal, 14)
.padding(.vertical, 8)
.background(palette.accent)
.foregroundColor(palette.accentForeground)
.clipShape(Capsule())
}
.buttonStyle(.plain)
Button(action: onOpenProfileSheet) {
Text(String(localized: "home_feed.action.manage_following", defaultValue: "Following & Handle", comment: "Button opening Public Handle and Following sheet"))
.bitchatFont(size: 13, weight: .semibold)
.padding(.horizontal, 14)
.padding(.vertical, 8)
.background(palette.cardBackground)
.foregroundColor(palette.primary)
.overlay(Capsule().stroke(palette.cardBorder, lineWidth: 1))
.clipShape(Capsule())
}
.buttonStyle(.plain)
}
.padding(.top, 4)
}
.frame(maxWidth: .infinity)
.padding(.vertical, 44)
.padding(.horizontal, 24)
}
@ViewBuilder
private var composerBar: some View {
if profileStore.isPublicHandleEnabled {
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 6) {
Button(action: onOpenProfileSheet) {
HStack(spacing: 4) {
Image(systemName: "person.crop.circle.fill")
.font(.system(size: 11))
.foregroundColor(palette.accent)
let handle = profileStore.ownProfile.displayName.trimmedOrNilIfEmpty ?? senderNickname
Text(
String(
format: String(localized: "place_feed.composer.posting_as", defaultValue: "Posting as %@", comment: "Label showing active posting identity"),
locale: .current,
"@\(handle)"
)
)
.bitchatFont(size: 11, weight: .medium)
.foregroundColor(palette.secondary)
}
}
.buttonStyle(.plain)
Spacer()
}
.padding(.horizontal, 12)
HStack(alignment: .bottom, spacing: 8) {
TextField(
String(localized: "home_feed.composer.placeholder", defaultValue: "Post to your followers…", comment: "Placeholder for global Home Feed post composer"),
text: $draft,
axis: .vertical
)
.textFieldStyle(.plain)
.bitchatFont(size: 15)
.foregroundColor(palette.primary)
.lineLimit(1...maxDraftLines)
.padding(.vertical, 8)
.padding(.horizontal, 10)
.themedInputBackground()
.frame(maxWidth: .infinity, alignment: .leading)
Button(action: submitGlobalPost) {
if feedManager.isSending {
ProgressView()
.frame(width: 32, height: 32)
} else {
Image(systemName: "arrow.up.circle.fill")
.font(.system(size: 26, weight: .medium))
.foregroundColor(sendEnabled ? palette.accent : palette.secondary.opacity(0.4))
.frame(width: 32, height: 32)
}
}
.buttonStyle(.plain)
.disabled(!sendEnabled)
.accessibilityLabel(String(localized: "place_feed.action.post", defaultValue: "Post", comment: "Submit post button"))
}
.padding(.horizontal, 8)
.padding(.bottom, 6)
}
.padding(.top, 8)
.themedChromePanel(edge: .bottom)
} else {
Button(action: onOpenProfileSheet) {
HStack(spacing: 8) {
Image(systemName: "person.crop.circle.badge.plus")
.font(.system(size: 15, weight: .semibold))
.foregroundColor(palette.accent)
Text(String(localized: "home_feed.composer.enable_handle_cta", defaultValue: "Enable Public Handle to post globally", comment: "CTA bar shown in Home Feed when user has not opted into a persistent public handle"))
.bitchatFont(size: 13, weight: .medium)
.foregroundColor(palette.primary)
Spacer()
Image(systemName: "chevron.right")
.font(.system(size: 12, weight: .semibold))
.foregroundColor(palette.secondary)
}
.padding(.horizontal, 14)
.padding(.vertical, 12)
}
.buttonStyle(.plain)
.themedChromePanel(edge: .bottom)
}
}
private func submitGlobalPost() {
guard let content = draft.trimmedOrNilIfEmpty else { return }
let handle = profileStore.ownProfile.displayName.trimmedOrNilIfEmpty ?? senderNickname
if feedManager.sendGlobalPost(content: content, nickname: handle) {
draft = ""
}
}
private func scopeTitle(_ option: HomeFeedScope) -> String {
switch option {
case .all:
return String(localized: "place_feed.filter.all", defaultValue: "All", comment: "Show all feed items")
case .savedPlaces:
return String(localized: "home_feed.scope.saved_places", defaultValue: "Saved Places", comment: "Scope pill filtering Home Feed to bookmarked places")
case .following:
return String(localized: "home_feed.scope.following", defaultValue: "Following", comment: "Scope pill filtering Home Feed to followed accounts")
}
}
}
private struct HomeComposerHeightKey: PreferenceKey {
static let defaultValue: CGFloat = 0
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = max(value, nextValue())
}
}
File diff suppressed because it is too large. Load diff
+349
View File
@@ -0,0 +1,349 @@
//
// PlaceThreadSheet.swift
// bitchat
//
// Thread sheet for a Place Feed kind-1 root post, displaying chronological
// NIP-10 replies, NIP-25 emoji reactions, and a NIP-13 PoW-mined reply composer.
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import SwiftUI
struct PlaceThreadSheet: View {
let rootNote: LocationNotesManager.Note
let geohash: String
let senderNickname: String
let isTeleported: Bool
@ObservedObject var manager: LocationNotesManager
@Environment(\.dismiss) private var dismiss
@Environment(\.colorScheme) private var colorScheme
@Environment(\.dynamicTypeSize) private var dynamicTypeSize
@ThemedPalette private var palette
@State private var replyDraft = ""
/// Optional nested reply target inside the thread (nil replies directly to rootNote).
@State private var replyTarget: LocationNotesManager.Note?
private var replies: [LocationNotesManager.Note] {
manager.replies(forRootID: rootNote.id)
}
private var maxDraftLines: Int {
dynamicTypeSize.isAccessibilitySize ? 5 : 3
}
private var sendEnabled: Bool {
let trimmed = replyDraft.trimmed
return !trimmed.isEmpty && trimmed.utf8.count <= BoardWireConstants.contentMaxBytes && !manager.isSending
}
private var replyCountHeader: String {
if replies.count == 1 {
return String(localized: "place_feed.thread.replies_one", defaultValue: "1 reply", comment: "Header count when a Place Feed thread has 1 reply")
}
return String(
format: String(localized: "place_feed.thread.replies_many", defaultValue: "%lld replies", comment: "Header count when a Place Feed thread has multiple replies"),
locale: .current,
replies.count
)
}
var body: some View {
VStack(spacing: 0) {
ThemedSheetHeader(
title: String(localized: "place_feed.thread.title", defaultValue: "Thread", comment: "Title of the Place Feed thread sheet"),
subtitle: "#\(geohash)",
onClose: { dismiss() }
)
ScrollView {
LazyVStack(alignment: .leading, spacing: 12) {
// Root post card
PlaceFeedPostCard(
item: NoticeItem(note: rootNote),
isOwn: manager.isOwnNote(rootNote),
replyCount: replies.count,
reactions: manager.reactions(forNoteID: rootNote.id),
onOpenThread: { replyTarget = nil },
onToggleReaction: { emoji in
manager.toggleReaction(emoji: emoji, on: rootNote)
},
onDelete: {
if manager.delete(note: rootNote) {
dismiss()
}
}
)
// Section divider / reply count
if !replies.isEmpty {
ThemedSectionLabel(text: replyCountHeader.uppercased())
.padding(.horizontal, 4)
.padding(.top, 2)
ForEach(replies) { reply in
replyRow(reply)
}
} else {
Text(String(localized: "place_feed.thread.no_replies", defaultValue: "No replies yet — start the conversation.", comment: "Empty state inside a Place Feed thread with zero replies"))
.bitchatFont(size: 13)
.foregroundColor(palette.secondary)
.frame(maxWidth: .infinity, alignment: .center)
.padding(.vertical, 28)
}
}
.padding(.horizontal, 16)
.padding(.vertical, 12)
}
.scrollDismissesKeyboard(.interactively)
.frame(maxWidth: .infinity, maxHeight: .infinity)
composer
}
.themedSurface()
#if os(macOS)
.frame(minWidth: 420, idealWidth: 460, minHeight: 560, idealHeight: 660)
#endif
.themedSheetBackground()
}
private func replyRow(_ reply: LocationNotesManager.Note) -> some View {
let isOwn = manager.isOwnNote(reply)
let authorColor = isOwn
? PeerColorContrast.selfColor(isDark: colorScheme == .dark)
: Color(peerSeed: reply.pubkey, isDark: colorScheme == .dark)
let reactions = manager.reactions(forNoteID: reply.id)
let parentReply = reply.replyToEventID.flatMap { parentID in
replies.first(where: { $0.id == parentID })
}
return HStack(alignment: .top, spacing: 10) {
Rectangle()
.fill(palette.divider)
.frame(width: 2)
.padding(.leading, 8)
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 5) {
Text(verbatim: "@\(reply.shortAuthorName)")
.bitchatFont(size: 13, weight: .semibold)
.foregroundColor(authorColor)
.lineLimit(1)
Text(verbatim: "#\(reply.authorSuffix)")
.bitchatFont(size: 11)
.foregroundColor(palette.secondary)
.lineLimit(1)
Text(verbatim: "·")
.bitchatFont(size: 11)
.foregroundColor(palette.secondary)
Text(PlaceFeedTimestamp.text(for: reply.createdAt))
.bitchatFont(size: 11)
.foregroundColor(palette.secondary)
.lineLimit(1)
if reply.isTeleported {
Image(systemName: "globe")
.font(.system(size: 10))
.foregroundColor(palette.accentBlue)
}
if reply.hasVerifiedPoW {
Image(systemName: "bolt.shield.fill")
.font(.system(size: 10))
.foregroundColor(palette.secondary)
}
Spacer(minLength: 4)
if isOwn {
Button {
manager.delete(note: reply)
} label: {
Image(systemName: "trash")
.font(.system(size: 12, weight: .medium))
.foregroundColor(palette.secondary)
.frame(width: 26, height: 26)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.accessibilityLabel(String(localized: "board.action.delete", defaultValue: "delete", comment: "Delete own reply"))
}
}
if let parentReply {
Text(
String(
format: String(localized: "place_feed.composer.replying_to", defaultValue: "Replying to @%@", comment: "Indicator showing which author a nested reply targets"),
locale: .current,
parentReply.shortAuthorName
)
)
.bitchatFont(size: 11)
.foregroundColor(palette.accent)
}
Text(reply.content)
.bitchatFont(size: 14)
.foregroundColor(palette.primary)
.fixedSize(horizontal: false, vertical: true)
HStack(spacing: 6) {
Button {
replyTarget = reply
} label: {
HStack(spacing: 3) {
Image(systemName: "arrowshape.turn.up.left")
.font(.system(size: 11, weight: .medium))
Text(String(localized: "place_feed.action.reply", defaultValue: "Reply", comment: "Reply to a comment in a thread"))
.bitchatFont(size: 11, weight: .medium)
}
.foregroundColor(palette.secondary)
.padding(.horizontal, 7)
.padding(.vertical, 3)
.background(palette.secondary.opacity(0.08))
.clipShape(Capsule())
}
.buttonStyle(.plain)
ForEach(reactions) { reaction in
Button {
manager.toggleReaction(emoji: reaction.emoji, on: reply)
} label: {
HStack(spacing: 3) {
Text(verbatim: reaction.emoji)
.font(.system(size: 11))
Text(verbatim: "\(reaction.count)")
.bitchatFont(size: 11, weight: .semibold)
}
.foregroundColor(reaction.includesCurrentUser ? palette.accent : palette.secondary)
.padding(.horizontal, 7)
.padding(.vertical, 3)
.background(
reaction.includesCurrentUser
? palette.accent.opacity(0.16)
: palette.secondary.opacity(0.08)
)
.clipShape(Capsule())
}
.buttonStyle(.plain)
}
Menu {
ForEach(MessageInteractionCodec.quickReactionPalette, id: \.self) { emoji in
Button {
manager.toggleReaction(emoji: emoji, on: reply)
} label: {
Text(verbatim: emoji)
}
}
} label: {
Image(systemName: "face.smiling")
.font(.system(size: 12, weight: .medium))
.foregroundColor(palette.secondary)
.frame(width: 24, height: 22)
.background(palette.secondary.opacity(0.08))
.clipShape(Capsule())
}
.menuStyle(.borderlessButton)
.menuIndicator(.hidden)
.accessibilityLabel(String(localized: "place_feed.action.react", defaultValue: "React", comment: "React to a thread reply"))
Spacer(minLength: 0)
}
.padding(.top, 2)
}
.padding(12)
.frame(maxWidth: .infinity, alignment: .leading)
.background(palette.cardBackground)
.overlay(
RoundedRectangle(cornerRadius: palette.cardRadius, style: .continuous)
.stroke(palette.cardBorder, lineWidth: 1)
)
.clipShape(RoundedRectangle(cornerRadius: palette.cardRadius, style: .continuous))
}
}
private var composer: some View {
VStack(alignment: .leading, spacing: 6) {
if let target = replyTarget {
HStack(spacing: 6) {
Text(
String(
format: String(localized: "place_feed.composer.replying_to", defaultValue: "Replying to @%@", comment: "Indicator showing which author a nested reply targets"),
locale: .current,
target.shortAuthorName
)
)
.bitchatFont(size: 11, weight: .medium)
.foregroundColor(palette.accent)
Spacer()
Button {
replyTarget = nil
} label: {
Image(systemName: "xmark.circle.fill")
.font(.system(size: 14))
.foregroundColor(palette.secondary)
}
.buttonStyle(.plain)
.accessibilityLabel(String(localized: "common.cancel", defaultValue: "Cancel", comment: "Clear nested reply target"))
}
.padding(.horizontal, 12)
}
HStack(alignment: .bottom, spacing: 8) {
TextField(
String(localized: "place_feed.composer.reply_placeholder", defaultValue: "Write a reply…", comment: "Placeholder text for the Place Feed thread reply composer"),
text: $replyDraft,
axis: .vertical
)
.textFieldStyle(.plain)
.bitchatFont(size: 15)
.foregroundColor(palette.primary)
.lineLimit(1...maxDraftLines)
.padding(.vertical, 8)
.padding(.horizontal, 10)
.themedInputBackground()
.frame(maxWidth: .infinity, alignment: .leading)
Button(action: submitReply) {
if manager.isSending {
ProgressView()
.frame(width: 32, height: 32)
} else {
Image(systemName: "arrow.up.circle.fill")
.font(.system(size: 26, weight: .medium))
.foregroundColor(sendEnabled ? palette.accent : palette.secondary.opacity(0.4))
.frame(width: 32, height: 32)
}
}
.buttonStyle(.plain)
.disabled(!sendEnabled)
.accessibilityLabel(String(localized: "place_feed.action.reply", defaultValue: "Reply", comment: "Submit reply button"))
}
.padding(.horizontal, 8)
.padding(.bottom, 6)
}
.padding(.top, 8)
.themedChromePanel(edge: .bottom)
}
private func submitReply() {
guard let content = replyDraft.trimmedOrNilIfEmpty else { return }
let target = replyTarget ?? rootNote
let reference = NostrProtocol.ThreadReference(
rootEventID: rootNote.id,
replyEventID: target.id == rootNote.id ? nil : target.id,
replyAuthorPubkey: target.pubkey
)
if manager.sendFeedPost(
content: content,
nickname: senderNickname,
expiresAt: nil,
urgent: false,
teleported: isTeleported,
replyTo: reference
) {
replyDraft = ""
replyTarget = nil
}
}
}
+108 -24
View File
@@ -35,7 +35,10 @@ struct PlacesTabView<RoomContent: View>: View {
@State private var showSharePrecisionWarning = false
@State private var activeSharePayload: ChannelSharePayload?
@State private var showLocalPlaceNotes = false
@State private var tabMode: PlacesTabMode = .explore
@State private var showPublicProfileSheet = false
@ObservedObject private var nearbyNotes = NearbyNotesCounter.shared
@ObservedObject private var profileStore = NostrProfileStore.shared
var body: some View {
Group {
@@ -93,6 +96,9 @@ struct PlacesTabView<RoomContent: View>: View {
)
.environmentObject(locationChannelsModel)
}
.sheet(isPresented: $showPublicProfileSheet) {
PublicProfileSheet(defaultNickname: appChromeModel.nickname)
}
#if os(iOS)
.fullScreenCover(isPresented: $showGlobePicker, onDismiss: applyPickedGeohash) {
globePicker
@@ -112,42 +118,81 @@ struct PlacesTabView<RoomContent: View>: View {
onSelect: onSelectTab
)
} trailing: {
EmptyView()
placesTabModeToggle
TopBarIconButton(
systemImage: profileStore.isPublicHandleEnabled ? "person.crop.circle.fill" : "person.crop.circle",
accessibilityLabel: String(localized: "public_profile.title", defaultValue: "Identity & Following", comment: "Button opening the Public Handle and Private Following sheet"),
color: profileStore.isPublicHandleEnabled ? palette.accent : palette.secondary,
action: { showPublicProfileSheet = true }
)
}
.stealthTripleTapPanicWipe {
appChromeModel.requestPanicWipe()
}
let scrollBody = ScrollView {
VStack(alignment: .leading, spacing: 20) {
if appChromeModel.torBlocked {
ConnectivityStatusBanner(issue: .torBlocked)
let scrollBody = Group {
if tabMode == .feed {
HomeFeedView(
senderNickname: appChromeModel.nickname,
topContentInset: ChromeMetrics.barHeight + 10,
usesOverlayChrome: theme.usesGlassChrome,
onSelectPlace: { gh, title in
let level = GeohashCoverage.level(forLength: gh.count)
let channel = GeohashChannel(level: level, geohash: gh)
let inRegional = locationChannelsModel.availableChannels.contains { $0.geohash == gh }
locationChannelsModel.markTeleported(for: gh, !inRegional && !locationChannelsModel.availableChannels.isEmpty)
activeLocationTitle = title
activeLocationChannel = channel
locationChannelsModel.select(.location(channel))
},
onExplorePlaces: {
withAnimation(.easeInOut(duration: 0.16)) {
tabMode = .explore
}
},
onOpenProfileSheet: {
showPublicProfileSheet = true
}
)
} else {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
if appChromeModel.torBlocked {
ConnectivityStatusBanner(issue: .torBlocked)
}
locationPermissionCard
localPlaceNotesCard
nearbyPlacesSection
if let suggestion = QuickJoinSuggestion.current() {
quickJoinCard(suggestion)
}
if !locationChannelsModel.bookmarks.isEmpty {
bookmarksSection(locationChannelsModel.bookmarks)
}
teleportSection
}
.padding(16)
}
locationPermissionCard
localPlaceNotesCard
nearbyPlacesSection
if let suggestion = QuickJoinSuggestion.current() {
quickJoinCard(suggestion)
}
if !locationChannelsModel.bookmarks.isEmpty {
bookmarksSection(locationChannelsModel.bookmarks)
}
teleportSection
}
.padding(16)
}
return Group {
if theme.usesGlassChrome {
if #available(iOS 17.0, macOS 14.0, *) {
scrollBody
.contentMargins(.top, ChromeMetrics.barHeight + 10, for: .scrollContent)
.contentMargins(.top, ChromeMetrics.barHeight + 10, for: .scrollIndicators)
.overlay(alignment: .top) { topBar }
if tabMode == .feed {
scrollBody
.overlay(alignment: .top) { topBar }
} else {
scrollBody
.contentMargins(.top, ChromeMetrics.barHeight + 10, for: .scrollContent)
.contentMargins(.top, ChromeMetrics.barHeight + 10, for: .scrollIndicators)
.overlay(alignment: .top) { topBar }
}
} else {
VStack(spacing: 0) {
topBar
@@ -165,6 +210,39 @@ struct PlacesTabView<RoomContent: View>: View {
.background(ThemedRootBackground())
}
private var placesTabModeToggle: some View {
HStack(spacing: 2) {
ForEach(PlacesTabMode.allCases) { mode in
let isSelected = tabMode == mode
Button {
withAnimation(.easeInOut(duration: 0.16)) {
tabMode = mode
}
} label: {
Text(
mode == .explore
? String(localized: "places.mode.explore", defaultValue: "Explore", comment: "Segment label for Places directory and globe")
: String(localized: "place_feed.mode.feed", defaultValue: "Feed", comment: "Segment label for Home Feed")
)
.bitchatFont(size: 12, weight: isSelected ? .semibold : .medium)
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(isSelected ? palette.accent : Color.clear)
.foregroundColor(isSelected ? palette.accentForeground : palette.secondary)
.clipShape(Capsule())
.contentShape(Rectangle())
}
.buttonStyle(.plain)
}
}
.padding(2)
.background(palette.cardBackground)
.overlay(
Capsule().stroke(palette.cardBorder, lineWidth: 1)
)
.clipShape(Capsule())
}
@ViewBuilder
private var locationPermissionCard: some View {
switch locationChannelsModel.permissionState {
@@ -558,9 +636,15 @@ struct PlacesTabView<RoomContent: View>: View {
}
return customGeohash.trimmed.lowercased()
}()
let beacons = GlobeActivityBeacon.buildBeacons(
chatCounts: GeohashChatActivityTracker.shared.activeGeohashCounts(),
noteCounts: LocationNotesPool.shared.activeNoteCounts(),
bookmarks: locationChannelsModel.bookmarks
)
return GeohashPickerView(
initialGeohash: initial,
nearbyGeohashes: locationChannelsModel.availableChannels.map(\.geohash),
activityBeacons: beacons,
onSelect: { geohash in
pickedGeohash = geohash
showGlobePicker = false
+352
View File
@@ -0,0 +1,352 @@
//
// PublicProfileSheet.swift
// bitchat
//
// Manages the opt-in persistent Nostr Public Handle (NIP-01 kind 0) and the
// private, Keychain-backed Following list (never broadcast as public kind 3).
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import SwiftUI
struct PublicProfileSheet: View {
@ObservedObject private var profileStore = NostrProfileStore.shared
@ObservedObject private var followsStore = NostrFollowsStore.shared
@Environment(\.dismiss) private var dismiss
@Environment(\.colorScheme) private var colorScheme
@ThemedPalette private var palette
@State private var isEnabled = false
@State private var displayName = ""
@State private var about = ""
@State private var nip05 = ""
@State private var copiedNpub = false
@State private var savedBanner = false
@State private var followInput = ""
@State private var followError: String?
let defaultNickname: String
var body: some View {
VStack(spacing: 0) {
ThemedSheetHeader(
title: String(localized: "public_profile.title", defaultValue: "Identity & Following", comment: "Title of the Public Handle and Private Following management sheet"),
onClose: { dismiss() }
)
ScrollView {
VStack(alignment: .leading, spacing: 20) {
publicHandleSection
followingSection
}
.padding(16)
}
.scrollDismissesKeyboard(.interactively)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.themedSurface()
#if os(macOS)
.frame(minWidth: 420, idealWidth: 460, minHeight: 580, idealHeight: 680)
#endif
.themedSheetBackground()
.onAppear {
loadDraftFromStore()
}
}
private var publicHandleSection: some View {
VStack(alignment: .leading, spacing: 8) {
ThemedSectionLabel(
text: String(localized: "public_profile.section.handle", defaultValue: "PUBLIC HANDLE (OPT-IN)", comment: "Section header for the optional persistent Nostr handle").uppercased()
)
ThemedCard(spacing: 12) {
Toggle(isOn: $isEnabled) {
VStack(alignment: .leading, spacing: 3) {
Text(String(localized: "public_profile.toggle.title", defaultValue: "Enable Public Handle", comment: "Toggle enabling a persistent Nostr kind-0 public handle"))
.bitchatFont(size: 15, weight: .semibold)
.foregroundColor(palette.primary)
Text(String(localized: "public_profile.toggle.subtitle", defaultValue: "By default, place posts use unlinkable per-place keys. Enable a persistent handle only when you want followers across places.", comment: "Privacy explanation contrasting per-place keys with opt-in public handle"))
.bitchatFont(size: 12)
.foregroundColor(palette.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
.toggleStyle(.switch)
.onChange(of: isEnabled) { enabled in
if !enabled {
profileStore.disablePublicHandle()
savedBanner = false
} else if displayName.trimmed.isEmpty {
displayName = defaultNickname
}
}
if isEnabled {
Rectangle()
.fill(palette.divider)
.frame(height: 1)
if let npub = profileStore.ownPublicNpub {
HStack(spacing: 8) {
Text(verbatim: abbreviatedNpub(npub))
.bitchatFont(size: 12, weight: .medium)
.foregroundColor(palette.secondary)
.lineLimit(1)
Spacer()
Button {
ClipboardHelper.copy(npub)
copiedNpub = true
DispatchQueue.main.asyncAfter(deadline: .now() + 1.8) {
copiedNpub = false
}
} label: {
Label(
copiedNpub
? String(localized: "public_profile.action.copied", defaultValue: "Copied", comment: "Confirmation after copying npub")
: String(localized: "public_profile.action.copy_npub", defaultValue: "Copy npub", comment: "Button copying the user's npub to clipboard"),
systemImage: copiedNpub ? "checkmark" : "doc.on.doc"
)
.bitchatFont(size: 12, weight: .semibold)
.foregroundColor(palette.accent)
}
.buttonStyle(.plain)
}
}
VStack(alignment: .leading, spacing: 8) {
TextField(
String(localized: "public_profile.field.name", defaultValue: "Display name", comment: "Placeholder for kind-0 display name"),
text: $displayName
)
.textFieldStyle(.plain)
.bitchatFont(size: 14)
.foregroundColor(palette.primary)
.padding(.horizontal, 10)
.padding(.vertical, 8)
.themedInputBackground()
TextField(
String(localized: "public_profile.field.about", defaultValue: "Short bio (optional)", comment: "Placeholder for kind-0 bio"),
text: $about,
axis: .vertical
)
.textFieldStyle(.plain)
.bitchatFont(size: 14)
.foregroundColor(palette.primary)
.lineLimit(1...3)
.padding(.horizontal, 10)
.padding(.vertical, 8)
.themedInputBackground()
TextField(
String(localized: "public_profile.field.nip05", defaultValue: "NIP-05 handle (e.g. name@domain.com)", comment: "Placeholder for optional NIP-05 identifier"),
text: $nip05
)
.textFieldStyle(.plain)
.bitchatFont(size: 14)
.foregroundColor(palette.primary)
#if os(iOS)
.textInputAutocapitalization(.never)
.autocorrectionDisabled(true)
.keyboardType(.emailAddress)
#endif
.padding(.horizontal, 10)
.padding(.vertical, 8)
.themedInputBackground()
}
HStack {
Button(action: publishProfile) {
Text(String(localized: "public_profile.action.publish", defaultValue: "Save & Publish Profile", comment: "Button saving and publishing NIP-01 kind-0 profile metadata"))
.bitchatFont(size: 14, weight: .semibold)
.frame(maxWidth: .infinity)
.padding(.vertical, 9)
.background(palette.accent)
.foregroundColor(palette.accentForeground)
.clipShape(RoundedRectangle(cornerRadius: palette.buttonRadius, style: .continuous))
}
.buttonStyle(.plain)
}
if savedBanner {
Text(String(localized: "public_profile.status.published", defaultValue: "Profile published to relays.", comment: "Confirmation shown after kind-0 metadata event is published"))
.bitchatFont(size: 12)
.foregroundColor(palette.locationAccent)
}
}
}
}
}
private var followingSection: some View {
VStack(alignment: .leading, spacing: 8) {
ThemedSectionLabel(
text: String(localized: "public_profile.section.following", defaultValue: "FOLLOWING (PRIVATE)", comment: "Section header for private local-only following list").uppercased()
)
ThemedCard(spacing: 12) {
Text(String(localized: "public_profile.following.privacy_note", defaultValue: "Stored only in your device Keychain and never published as a public follow list. Mutual mesh favorites with Nostr keys are included automatically.", comment: "Privacy explanation for local-only following list"))
.bitchatFont(size: 12)
.foregroundColor(palette.secondary)
.fixedSize(horizontal: false, vertical: true)
HStack(spacing: 8) {
TextField(
String(localized: "public_profile.following.placeholder", defaultValue: "npub1… or hex pubkey", comment: "Placeholder for adding a Nostr pubkey to follow"),
text: $followInput
)
.textFieldStyle(.plain)
.bitchatFont(size: 13)
.foregroundColor(palette.primary)
#if os(iOS)
.textInputAutocapitalization(.never)
.autocorrectionDisabled(true)
#endif
.padding(.horizontal, 10)
.padding(.vertical, 7)
.themedInputBackground()
Button(action: addFollow) {
Text(String(localized: "public_profile.action.follow", defaultValue: "Follow", comment: "Button to follow a Nostr author"))
.bitchatFont(size: 13, weight: .semibold)
.padding(.horizontal, 12)
.padding(.vertical, 7)
.background(palette.accent)
.foregroundColor(palette.accentForeground)
.clipShape(RoundedRectangle(cornerRadius: palette.buttonRadius, style: .continuous))
}
.buttonStyle(.plain)
.disabled(followInput.trimmed.isEmpty)
}
if let followError {
Text(followError)
.bitchatFont(size: 12)
.foregroundColor(palette.alertRed)
}
if !followsStore.explicitFollows.isEmpty {
Rectangle()
.fill(palette.divider)
.frame(height: 1)
VStack(alignment: .leading, spacing: 10) {
ForEach(followsStore.explicitFollows) { entry in
followedRow(entry)
}
}
} else if followsStore.favoriteFollowPubkeys.isEmpty {
Text(String(localized: "public_profile.following.empty", defaultValue: "No followed accounts yet.", comment: "Empty state when user follows zero Nostr pubkeys"))
.bitchatFont(size: 13)
.foregroundColor(palette.secondary)
}
if !followsStore.favoriteFollowPubkeys.isEmpty {
Text(
String(
format: String(localized: "public_profile.following.favorites_included", defaultValue: "+ %lld favorited mesh peers with Nostr keys", comment: "Caption showing count of favorited mesh peers automatically included in Following"),
locale: .current,
followsStore.favoriteFollowPubkeys.count
)
)
.bitchatFont(size: 11)
.foregroundColor(palette.secondary)
}
}
}
}
private func followedRow(_ entry: NostrFollowsStore.FollowedAuthor) -> some View {
let name = profileStore.displayName(
for: entry.pubkeyHex,
fallbackNickname: entry.alias
)
let nip05 = profileStore.profile(for: entry.pubkeyHex)?.nip05
let color = Color(peerSeed: entry.pubkeyHex, isDark: colorScheme == .dark)
return HStack(spacing: 10) {
Text(verbatim: String(name.prefix(1)).uppercased())
.bitchatFont(size: 12, weight: .bold)
.foregroundColor(color)
.frame(width: 28, height: 28)
.background(color.opacity(0.15))
.clipShape(Circle())
VStack(alignment: .leading, spacing: 1) {
Text(verbatim: name)
.bitchatFont(size: 14, weight: .semibold)
.foregroundColor(palette.primary)
.lineLimit(1)
if let nip05, !nip05.isEmpty {
Text(verbatim: nip05)
.bitchatFont(size: 11)
.foregroundColor(palette.locationAccent)
.lineLimit(1)
} else if let npub = entry.npub {
Text(verbatim: abbreviatedNpub(npub))
.bitchatFont(size: 11)
.foregroundColor(palette.secondary)
.lineLimit(1)
}
}
Spacer(minLength: 4)
Button {
followsStore.unfollow(entry.pubkeyHex)
} label: {
Text(String(localized: "public_profile.action.unfollow", defaultValue: "Unfollow", comment: "Button removing a pubkey from the private follow list"))
.bitchatFont(size: 12, weight: .medium)
.foregroundColor(palette.secondary)
.padding(.horizontal, 9)
.padding(.vertical, 4)
.background(palette.secondary.opacity(0.12))
.clipShape(Capsule())
}
.buttonStyle(.plain)
}
}
private func loadDraftFromStore() {
let current = profileStore.ownProfile
isEnabled = current.isEnabled
displayName = current.displayName.trimmed.isEmpty ? defaultNickname : current.displayName
about = current.about
nip05 = current.nip05
}
private func publishProfile() {
let updated = NostrProfileStore.OwnPublicProfile(
isEnabled: isEnabled,
displayName: displayName.trimmed,
about: about.trimmed,
nip05: nip05.trimmed
)
if profileStore.saveAndPublishOwnProfile(updated) {
savedBanner = true
}
}
private func addFollow() {
let candidate = followInput.trimmed
guard let normalized = NostrProtocol.normalizePubkeyHex(candidate) else {
followError = String(localized: "public_profile.following.invalid_key", defaultValue: "Enter a valid npub1… or 64-character hex pubkey.", comment: "Validation error when adding an invalid Nostr pubkey")
return
}
followError = nil
if followsStore.follow(normalized) {
profileStore.ensureProfiles(for: [normalized])
followInput = ""
}
}
private func abbreviatedNpub(_ npub: String) -> String {
guard npub.count > 20 else { return npub }
return "\(npub.prefix(12))…\(npub.suffix(6))"
}
}
+1 -1
View File
@@ -89,7 +89,7 @@ struct LocationNotesManagerTests {
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { filter, id, relays, handler, eose in
#expect(filter.kinds == [1])
#expect(filter.kinds == [1, 7, 5])
#expect(!id.isEmpty)
relaysCaptured = relays
storedHandler = handler
+483
View File
@@ -0,0 +1,483 @@
//
// Phase2FeedTests.swift
// bitchatTests
//
// Coverage for Phase 2:
// - NIP-01 kind-0 profile metadata creation, sanitization, and size bounds
// - npub / hex pubkey normalization & global kind-1 mined notes
// - NostrFollowsStore private Keychain persistence, favorites merge, and panic wipe
// - NostrProfileStore opt-in handle, remote kind-0 batching/cooldown/EOSE, and panic wipe
// - LocationNotesManager dual-posture posting (.placePersona vs .publicHandle) & delete
// - HomeFeedManager Saved Places + Following merge, deduplication, scopes, global send, and panic wipe
// - SwiftUI smoke rendering for HomeFeedView and PublicProfileSheet
//
import Combine
import Foundation
import SwiftUI
import Testing
@testable import bitchat
struct Phase2ProtocolTests {
@Test
func kind0_metadataRoundTripsSanitizedFieldsAndRejectsOversizedPayload() throws {
let identity = try NostrIdentity.generate()
let raw = NostrProtocol.ProfileMetadata(
name: "alice\nignored",
displayName: " Alice Wonder ",
about: "line 1\nline 2",
nip05: "alice@example.com\r\n"
)
let event = try NostrProtocol.createMetadataEvent(profile: raw, senderIdentity: identity)
#expect(event.kind == NostrProtocol.EventKind.metadata.rawValue)
#expect(event.isValidSignature())
let parsed = try #require(NostrProtocol.parseMetadataEvent(event))
#expect(parsed.displayName == "Alice Wonder")
#expect(parsed.about == "line 1\nline 2")
#expect(parsed.nip05 == "alice@example.com")
#expect(parsed.preferredName == "Alice Wonder")
// Oversized untrusted kind-0 content is rejected before JSON parsing.
let huge = try NostrEvent(
pubkey: identity.publicKeyHex,
createdAt: Date(),
kind: .metadata,
tags: [],
content: "{\"about\":\"" + String(repeating: "x", count: NostrProtocol.maximumProfileMetadataBytes) + "\"}"
).sign(with: identity.schnorrSigningKey())
#expect(NostrProtocol.parseMetadataEvent(huge) == nil)
}
@Test
func normalizePubkeyHex_acceptsNpubAndHexAndRejectsGarbage() throws {
let identity = try NostrIdentity.generate()
#expect(NostrProtocol.normalizePubkeyHex(identity.npub) == identity.publicKeyHex.lowercased())
#expect(NostrProtocol.normalizePubkeyHex(identity.publicKeyHex.uppercased()) == identity.publicKeyHex.lowercased())
#expect(NostrProtocol.normalizePubkeyHex("not-a-key") == nil)
#expect(NostrProtocol.normalizePubkeyHex("deadbeef") == nil)
}
@Test
func createPublicTextNote_hasNoGeohashTagAndValidSignature() throws {
let identity = try NostrIdentity.generate()
let event = try NostrProtocol.createPublicTextNote(
content: "global update",
senderIdentity: identity,
nickname: "alice"
)
#expect(event.kind == NostrProtocol.EventKind.textNote.rawValue)
#expect(event.isValidSignature())
#expect(!event.tags.contains(where: { $0.first == "g" }))
}
}
@MainActor
struct Phase2StoresAndHomeFeedTests {
@Test
func followsStore_persistsPrivatelyMergesFavoritesAndWipesOnPanic() throws {
let keychain = PreviewKeychainManager()
let explicitPeer = try NostrIdentity.generate()
let favPeer = try NostrIdentity.generate()
let favRel = FavoritesPersistenceService.FavoriteRelationship(
peerNoisePublicKey: Data(repeating: 7, count: 32),
peerNostrPublicKey: favPeer.npub,
peerNickname: "mesh-friend",
isFavorite: true,
theyFavoritedUs: true,
favoritedAt: Date(),
lastUpdated: Date()
)
let store = NostrFollowsStore(keychain: keychain, favoritesProvider: { [favRel] })
#expect(store.isFollowing(favPeer.publicKeyHex))
#expect(!store.isFollowing(explicitPeer.publicKeyHex))
#expect(store.follow(explicitPeer.npub, alias: "alice"))
#expect(store.isFollowing(explicitPeer.publicKeyHex))
#expect(store.isExplicitlyFollowing(explicitPeer.publicKeyHex))
#expect(store.allFollowedPubkeys.count == 2)
// Reload from same Keychain verifies persistence
let reloaded = NostrFollowsStore(keychain: keychain, favoritesProvider: { [favRel] })
#expect(reloaded.isExplicitlyFollowing(explicitPeer.publicKeyHex))
#expect(reloaded.localAlias(for: explicitPeer.publicKeyHex) == "alice")
// Panic wipe removes both in-memory and Keychain state
reloaded.resetForPanic()
#expect(reloaded.explicitFollows.isEmpty)
#expect(reloaded.allFollowedPubkeys.isEmpty)
let afterWipe = NostrFollowsStore(keychain: keychain, favoritesProvider: { [] })
#expect(afterWipe.explicitFollows.isEmpty)
}
@Test
func followsStore_lockedBootDefersWritesAndReplaysOnUnlock() throws {
let keychain = MockKeychain()
let existingPeer = try NostrIdentity.generate()
let newPeer = try NostrIdentity.generate()
let initial = NostrFollowsStore(keychain: keychain, favoritesProvider: { [] })
#expect(initial.follow(existingPeer.publicKeyHex, alias: "existing"))
// Boot while device is locked: load fails with .deviceLocked.
keychain.simulatedGenericReadError = .deviceLocked
let lockedStore = NostrFollowsStore(keychain: keychain, favoritesProvider: { [] })
#expect(lockedStore.explicitFollows.isEmpty)
// Mutating while locked must NOT overwrite existing Keychain entry.
#expect(lockedStore.follow(newPeer.publicKeyHex, alias: "added-while-locked"))
keychain.simulatedGenericReadError = nil
let rawBeforeReplay = NostrFollowsStore(keychain: keychain, favoritesProvider: { [] })
#expect(rawBeforeReplay.explicitFollows.map(\.pubkeyHex) == [existingPeer.publicKeyHex])
// Unlocking and retrying loads existing follow, replays queued follow, and persists both.
lockedStore.retryDeferredLoad()
#expect(Set(lockedStore.explicitFollows.map(\.pubkeyHex)) == [existingPeer.publicKeyHex, newPeer.publicKeyHex])
let afterReplay = NostrFollowsStore(keychain: keychain, favoritesProvider: { [] })
#expect(Set(afterReplay.explicitFollows.map(\.pubkeyHex)) == [existingPeer.publicKeyHex, newPeer.publicKeyHex])
}
@Test
func profileStore_clearsCooldownWhenEOSEFiresBeforeTorConnects() throws {
let keychain = MockKeychain()
let remote = try NostrIdentity.generate()
var isConnected = false
var subscribeCount = 0
var lastEOSE: (() -> Void)?
let deps = NostrProfileStoreDependencies(
subscribe: { _, _, _, onEOSE in
subscribeCount += 1
lastEOSE = onEOSE
},
unsubscribe: { _ in },
sendEvent: { _ in },
currentIdentity: { nil },
now: { Date(timeIntervalSince1970: 1_700_000_000) },
isAnyDefaultRelayConnected: { isConnected }
)
let store = NostrProfileStore(keychain: keychain, dependencies: deps)
store.ensureProfiles(for: [remote.publicKeyHex])
#expect(subscribeCount == 1)
// 10s EOSE fallback fires while Tor/relays are still disconnected.
lastEOSE?()
// Once relays connect, cooldown must NOT block re-fetching the missing profile.
isConnected = true
store.ensureProfiles(for: [remote.publicKeyHex])
#expect(subscribeCount == 2)
store.resetForPanic()
}
@Test
func homeFeedManager_prunesExpiredFollowingPostsWithoutResurrectingPlacePosts() throws {
var currentNow = Date(timeIntervalSince1970: 1_700_000_000)
let author = try NostrIdentity.generate()
var placeHandler: ((NostrEvent) -> Void)?
var followingHandler: ((NostrEvent) -> Void)?
var placeManager: LocationNotesManager?
let homeDeps = HomeFeedDependencies(
acquirePlaceManager: { gh in
let mgr = LocationNotesManager(geohash: gh, dependencies: LocationNotesDependencies(
relayLookup: { _, _ in ["wss://geo.relay"] },
subscribe: { _, _, _, onEvent, onEOSE in
placeHandler = onEvent
onEOSE?()
},
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in try NostrIdentity.generate() },
now: { currentNow }
))
placeManager = mgr
return mgr
},
releasePlaceManager: { $0?.cancel() },
subscribeDefaultRelays: { _, _, onEvent, onEOSE in
followingHandler = onEvent
onEOSE?()
},
unsubscribe: { _ in },
sendDefaultRelays: { _ in },
publicIdentity: { nil },
ensureProfiles: { _ in },
now: { currentNow }
)
let feed = HomeFeedManager(dependencies: homeDeps)
feed.activate(bookmarks: ["9q8yy"], followedPubkeys: [author.publicKeyHex])
let expiring = try NostrProtocol.createGeohashTextNote(
content: "short-lived drop",
geohash: "9q8yy",
senderIdentity: author,
nickname: "alice",
expiresAt: currentNow.addingTimeInterval(60),
createdAt: currentNow
)
placeHandler?(expiring)
followingHandler?(expiring)
#expect(feed.items.count == 1)
// Advance past expiration: place manager prunes AND HomeFeedManager prunes Following cache.
currentNow = currentNow.addingTimeInterval(120)
placeManager?.pruneExpiredNotes()
feed.pruneExpiredFollowingNotes()
#expect(feed.items.isEmpty)
feed.resetForPanic()
}
@Test
func profileStore_defaultsOffPublishesKind0BatchesRemoteAndWipesOnPanic() throws {
let keychain = PreviewKeychainManager()
let me = try NostrIdentity.generate()
let remote = try NostrIdentity.generate()
var sentEvents: [NostrEvent] = []
var subscribedIDs: [String] = []
var unsubscribedIDs: [String] = []
var remoteHandler: ((NostrEvent) -> Void)?
var remoteEOSE: (() -> Void)?
let deps = NostrProfileStoreDependencies(
subscribe: { filter, id, onEvent, onEOSE in
#expect(filter.kinds == [0])
subscribedIDs.append(id)
remoteHandler = onEvent
remoteEOSE = onEOSE
},
unsubscribe: { unsubscribedIDs.append($0) },
sendEvent: { sentEvents.append($0) },
currentIdentity: { me },
now: { Date(timeIntervalSince1970: 1_700_000_000) }
)
let store = NostrProfileStore(keychain: keychain, dependencies: deps)
#expect(!store.isPublicHandleEnabled)
// Enable and publish kind 0
let saved = store.saveAndPublishOwnProfile(.init(
isEnabled: true,
displayName: "Jack",
about: "building bitchat",
nip05: "jack@bitchat.free"
))
#expect(saved)
#expect(sentEvents.count == 1)
#expect(sentEvents[0].kind == 0)
#expect(store.displayName(for: me.publicKeyHex, fallbackNickname: nil) == "Jack")
// Batch fetch remote profile, obey cooldown, auto-close on EOSE
store.ensureProfiles(for: [remote.publicKeyHex])
store.ensureProfiles(for: [remote.publicKeyHex]) // within cooldown -> skipped
#expect(subscribedIDs.count == 1)
let remoteMeta = try NostrProtocol.createMetadataEvent(
profile: .init(name: "bob", displayName: "Bob Builder", about: nil, nip05: "bob@example.com"),
senderIdentity: remote,
createdAt: Date(timeIntervalSince1970: 1_700_000_100)
)
remoteHandler?(remoteMeta)
remoteEOSE?()
#expect(unsubscribedIDs == subscribedIDs)
#expect(store.displayName(for: remote.publicKeyHex, fallbackNickname: "fallback") == "Bob Builder")
#expect(store.profile(for: remote.publicKeyHex)?.nip05 == "bob@example.com")
// Panic wipe clears cache and Keychain profile
store.resetForPanic()
#expect(!store.isPublicHandleEnabled)
#expect(store.profiles.isEmpty)
let afterWipe = NostrProfileStore(keychain: keychain, dependencies: deps)
#expect(!afterWipe.isPublicHandleEnabled)
}
@Test
func locationNotesManager_publicHandleMirrorsToDefaultRelaysAndSupportsDelete() async throws {
let placeID = try NostrIdentity.generate()
let globalID = try NostrIdentity.generate()
var geoSent: [NostrEvent] = []
var defaultSent: [NostrEvent] = []
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://geo.relay"] },
subscribe: { _, _, _, _, _ in },
unsubscribe: { _ in },
sendEvent: { event, _ in geoSent.append(event) },
deriveIdentity: { _ in placeID },
now: { Date(timeIntervalSince1970: 1_700_000_000) },
publicIdentity: { globalID },
sendToDefaultRelays: { defaultSent.append($0) }
)
let manager = LocationNotesManager(geohash: "9q8yy", dependencies: deps)
#expect(manager.sendFeedPost(
content: "hello from global handle",
nickname: "Jack",
identityMode: .publicHandle
))
#expect(geoSent.count == 1)
#expect(defaultSent.count == 1)
#expect(geoSent[0].pubkey == globalID.publicKeyHex)
let echoed = try #require(manager.notes.first)
#expect(manager.isOwnNote(echoed))
// Delete retracts on BOTH geo relays and default relays
#expect(manager.delete(note: echoed))
#expect(geoSent.count == 2)
#expect(defaultSent.count == 2)
#expect(geoSent[1].kind == NostrProtocol.EventKind.deletion.rawValue)
#expect(defaultSent[1].kind == NostrProtocol.EventKind.deletion.rawValue)
#expect(manager.notes.isEmpty)
}
@Test
func homeFeedManager_mergesDeduplicatesScopesAndResetsOnPanic() async throws {
let now = Date(timeIntervalSince1970: 1_700_000_000)
let me = try NostrIdentity.generate()
let followedAuthor = try NostrIdentity.generate()
let localStranger = try NostrIdentity.generate()
var placeHandlers: [String: (NostrEvent) -> Void] = [:]
var followingHandler: ((NostrEvent) -> Void)?
var sentGlobal: [NostrEvent] = []
var releasedCount = 0
var unsubscribedIDs: [String] = []
let homeDeps = HomeFeedDependencies(
acquirePlaceManager: { gh in
let placeDeps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://geo.relay"] },
subscribe: { _, _, _, onEvent, onEOSE in
placeHandlers[gh] = onEvent
onEOSE?()
},
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in try NostrIdentity.generate() },
now: { now }
)
return LocationNotesManager(geohash: gh, dependencies: placeDeps)
},
releasePlaceManager: { manager in
if manager != nil {
releasedCount += 1
manager?.cancel()
}
},
subscribeDefaultRelays: { _, _, onEvent, onEOSE in
followingHandler = onEvent
onEOSE?()
},
unsubscribe: { unsubscribedIDs.append($0) },
sendDefaultRelays: { sentGlobal.append($0) },
publicIdentity: { me },
ensureProfiles: { _ in },
now: { now }
)
let feed = HomeFeedManager(dependencies: homeDeps)
feed.activate(bookmarks: ["9q8yy"], followedPubkeys: [followedAuthor.publicKeyHex])
// 1. Local stranger posts in Saved Place #9q8yy
let localNote = try NostrProtocol.createGeohashTextNote(
content: "sf fog rolling in",
geohash: "9q8yy",
senderIdentity: localStranger,
nickname: "local",
createdAt: now.addingTimeInterval(-120)
)
// 2. Followed author posts in #9q8yy (arrives via BOTH place relay and following relay)
let crossPost = try NostrProtocol.createGeohashTextNote(
content: "coffee at mission",
geohash: "9q8yy",
senderIdentity: followedAuthor,
nickname: "friend",
createdAt: now.addingTimeInterval(-60)
)
// 3. Followed author posts globally (no geohash)
let globalPost = try NostrProtocol.createPublicTextNote(
content: "global thought",
senderIdentity: followedAuthor,
nickname: "friend",
createdAt: now
)
placeHandlers["9q8yy"]?(localNote)
placeHandlers["9q8yy"]?(crossPost)
followingHandler?(crossPost)
followingHandler?(globalPost)
// Deduplicated to 3 items total
#expect(feed.items.count == 3)
// Cross-post carries BOTH savedPlaceGeohash and isFromFollowedAuthor
let mergedCross = try #require(feed.items.first(where: { $0.id == crossPost.id }))
#expect(mergedCross.savedPlaceGeohash == "9q8yy")
#expect(mergedCross.isFromFollowedAuthor)
// Scope filters work accurately
#expect(feed.filteredItems(scope: .savedPlaces, sort: .latest, filter: .all).count == 2)
#expect(feed.filteredItems(scope: .following, sort: .latest, filter: .all).count == 2)
// Global post send works
#expect(feed.sendGlobalPost(content: "my global post", nickname: "me"))
#expect(sentGlobal.count == 1)
#expect(feed.items.contains(where: { $0.note.content == "my global post" }))
// Panic wipe tears down subscriptions, releases managers, and clears state
feed.resetForPanic()
#expect(feed.items.isEmpty)
#expect(releasedCount >= 1)
#expect(!unsubscribedIDs.isEmpty)
}
@Test
func homeFeedAndPublicProfileViewsRenderWithoutCrashing() {
let locationManager = LocationChannelManager(storage: UserDefaults(suiteName: "HomeFeedSmoke-\(UUID().uuidString)") ?? .standard)
let locationModel = LocationChannelsModel(manager: locationManager)
let homeDeps = HomeFeedDependencies(
acquirePlaceManager: { LocationNotesManager(geohash: $0, dependencies: LocationNotesDependencies(
relayLookup: { _, _ in [] },
subscribe: { _, _, _, _, _ in },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in try NostrIdentity.generate() },
now: Date.init
)) },
releasePlaceManager: { _ in },
subscribeDefaultRelays: { _, _, _, onEOSE in onEOSE?() },
unsubscribe: { _ in },
sendDefaultRelays: { _ in },
publicIdentity: { nil },
ensureProfiles: { _ in },
now: Date.init
)
let feedManager = HomeFeedManager(dependencies: homeDeps)
let homeView = HomeFeedView(
senderNickname: "tester",
onSelectPlace: { _, _ in },
onExplorePlaces: {},
onOpenProfileSheet: {},
feedManager: feedManager
)
.environmentObject(locationModel)
let profileSheet = PublicProfileSheet(defaultNickname: "tester")
#expect(String(describing: type(of: homeView)).contains("HomeFeedView"))
#expect(String(describing: type(of: profileSheet)).contains("PublicProfileSheet"))
}
}
+333
View File
@@ -0,0 +1,333 @@
//
// Phase3FeedTests.swift
// bitchatTests
//
// Coverage for Phase 3:
// - BLE Gateway uplink/downlink for kind-1 Place Feed posts & kind-7 reactions
// - LocalWebOfTrustService bridging verified + VouchAttestation -> .vouched filter
// - NIP-92 imeta tag encoding/parsing & BUD-02 Blossom upload auth + Tor fail-closed upload/download + SHA-256 verification
// - 3D Globe live spatial activity beacon builder
//
import BitFoundation
import CoreGraphics
import Foundation
import ImageIO
import Testing
import UniformTypeIdentifiers
@testable import bitchat
@MainActor
struct Phase3FeedTests {
@Test
func gatewayBridgesKind1PostAndKind7ReactionAndRejectsMetadata() throws {
let now = Date(timeIntervalSince1970: 1_700_000_000)
let suite = "Phase3Gateway-\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: suite)!
defaults.removePersistentDomain(forName: suite)
var published: [(NostrEvent, String)] = []
var injectedFeed: [(NostrEvent, String)] = []
var broadcasted: [Data] = []
let gateway = GatewayService(defaults: defaults, now: { now })
gateway.setEnabled(true)
gateway.relaysConnected = { true }
gateway.publishToRelays = { event, gh in published.append((event, gh)) }
gateway.injectFeedInbound = { event, gh in injectedFeed.append((event, gh)) }
gateway.broadcastToMesh = { broadcasted.append($0) }
let sender = try NostrIdentity.generate()
let depositor = PeerID(str: "0123456789abcdef")
// 1. Uplink deposit of kind-1 Place Feed note succeeds and injects into feed
let post = try NostrProtocol.createGeohashTextNote(
content: "offline mesh dispatch",
geohash: "9q8yy",
senderIdentity: sender,
nickname: "scout",
createdAt: now
)
let postCarrier = try #require(NostrCarrierPacket(direction: .toGateway, geohash: "9q8yy", event: post)?.encode())
gateway.handleMeshCarrier(postCarrier, from: depositor, directedToUs: true)
#expect(published.count == 1)
#expect(published[0].0.id == post.id)
#expect(injectedFeed.count == 1)
#expect(injectedFeed[0].0.id == post.id)
// 2. Uplink deposit of kind-7 NIP-25 reaction also bridges cleanly
let reaction = try NostrProtocol.createGeohashReactionEvent(
emoji: "🔥",
targetEventID: post.id,
targetAuthorPubkey: sender.publicKeyHex,
geohash: "9q8yy",
senderIdentity: sender,
createdAt: now
)
let reactCarrier = try #require(NostrCarrierPacket(direction: .toGateway, geohash: "9q8yy", event: reaction)?.encode())
gateway.handleMeshCarrier(reactCarrier, from: depositor, directedToUs: true)
#expect(published.count == 2)
#expect(injectedFeed.count == 2)
// 3. Downlink rebroadcast of a remote relay kind-1 post broadcasts on BLE
let remoteAuthor = try NostrIdentity.generate()
let remotePost = try NostrProtocol.createGeohashTextNote(
content: "from internet relay",
geohash: "9q8yy",
senderIdentity: remoteAuthor,
createdAt: now
)
gateway.rebroadcastRelayEvent(remotePost, geohash: "9q8yy")
#expect(broadcasted.count == 1)
// 4. Receiver injects downlinked kind-1 carrier into LocationNotesPool manager
let rxDeps = LocationNotesDependencies(
relayLookup: { _, _ in [] },
subscribe: { _, _, _, _, _ in },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in try NostrIdentity.generate() },
now: { now }
)
let manager = LocationNotesManager(geohash: "9q8yy", dependencies: rxDeps)
let rxGateway = GatewayService(defaults: defaults, now: { now })
rxGateway.injectFeedInbound = { event, _ in manager.ingestCarriedEvent(event) }
rxGateway.handleMeshCarrier(broadcasted[0], from: depositor, directedToUs: false)
#expect(manager.notes.map(\.id) == [remotePost.id])
}
@Test
func offlineLocationNotesManagerUplinksKind1ViaMeshGateway() async throws {
let now = Date(timeIntervalSince1970: 1_700_000_000)
var uplinked: [(NostrEvent, String)] = []
var deps = LocationNotesDependencies(
relayLookup: { _, _ in [] },
subscribe: { _, _, _, _, _ in },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in try NostrIdentity.generate() },
now: { now }
)
deps.anyRelayConnected = { _ in false }
deps.uplinkViaMesh = { event, gh in
uplinked.append((event, gh))
return true
}
let manager = LocationNotesManager(geohash: "9q8yy", dependencies: deps)
#expect(manager.sendFeedPost(content: "sent over BLE gateway", nickname: "meshuser"))
#expect(uplinked.count == 1)
#expect(uplinked[0].1 == "9q8yy")
#expect(manager.notes.first?.content == "sent over BLE gateway")
// Offline reaction also uplinks through the BLE gateway when relays are disconnected.
let note = try #require(manager.notes.first)
#expect(manager.toggleReaction(emoji: "🔥", on: note))
#expect(uplinked.count == 2)
#expect(uplinked[1].0.kind == NostrProtocol.EventKind.reaction.rawValue)
#expect(manager.reactions(forNoteID: note.id).first?.emoji == "🔥")
// When neither relays nor BLE gateway are available, reaction returns false with no optimistic echo.
deps.uplinkViaMesh = { _, _ in false }
let offlineNoGateway = LocationNotesManager(geohash: "9q8yy", dependencies: deps)
#expect(!offlineNoGateway.toggleReaction(emoji: "🔥", on: note))
#expect(offlineNoGateway.reactions(forNoteID: note.id).isEmpty)
}
@Test
func localWebOfTrustResolvesVerifiedVouchedAndFiltersFeed() {
let verifiedNoise = Data(repeating: 0xAA, count: 32)
let vouchedNoise = Data(repeating: 0xBB, count: 32)
let strangerPubkey = String(repeating: "3", count: 64)
let verifiedPubkey = String(repeating: "1", count: 64)
let vouchedPubkey = String(repeating: "2", count: 64)
let wot = LocalWebOfTrustService(
noiseKeyLookup: { pubkey in
if pubkey == verifiedPubkey { return verifiedNoise }
if pubkey == vouchedPubkey { return vouchedNoise }
return nil
},
isVerifiedFingerprint: { $0 == verifiedNoise.sha256Fingerprint() },
validVoucherCount: { $0 == vouchedNoise.sha256Fingerprint() ? 2 : 0 }
)
#expect(wot.trust(forNostrPubkey: verifiedPubkey) == .verified)
#expect(wot.trust(forNostrPubkey: vouchedPubkey) == .vouched(voucherCount: 2))
#expect(wot.trust(forNostrPubkey: strangerPubkey) == .none)
let now = Date(timeIntervalSince1970: 1_700_000_000)
let items = [
NoticeItem(note: .init(id: "1", pubkey: verifiedPubkey, content: "verified post", createdAt: now, nickname: "v", geohash: "9q8yy")),
NoticeItem(note: .init(id: "2", pubkey: vouchedPubkey, content: "vouched post", createdAt: now.addingTimeInterval(-10), nickname: "w", geohash: "9q8yy")),
NoticeItem(note: .init(id: "3", pubkey: strangerPubkey, content: "stranger post", createdAt: now.addingTimeInterval(-20), nickname: "s", geohash: "9q8yy"))
]
let vouchedOnly = PlaceFeedOrganizer.organize(
items: items,
sort: .latest,
filter: .vouched,
isVouched: { item in
guard let note = item.nostrNote else { return false }
return wot.isTrustedAuthor(note.pubkey)
}
)
#expect(vouchedOnly.map(\.id) == ["1", "2"])
}
@Test
func blossomImetaAuthUploadDownloadVerifiesSha256AndFailsClosedOnTor() async throws {
// Build a tiny valid 4x4 PNG in memory
let sampleImageData = try makeTinyPNGData()
let identity = try NostrIdentity.generate()
// 1. NIP-92 imeta tag round-trip & security rejections (http/localhost/missing hash)
let validHash = String(repeating: "a", count: 64)
let validURL = try #require(URL(string: "https://blossom.example.com/\(validHash).jpg"))
let attachment = NostrProtocol.MediaAttachment(
url: validURL,
mimeType: "image/jpeg",
sha256Hex: validHash,
sizeBytes: 1234,
dimensions: "4x4"
)
let parsed = NostrProtocol.parseMediaAttachments(from: [
NostrProtocol.imetaTag(for: attachment),
["imeta", "url http://insecure.example.com/x.jpg", "m image/jpeg", "x \(validHash)"],
["imeta", "url https://localhost/x.jpg", "m image/jpeg", "x \(String(repeating: "b", count: 64))"]
])
#expect(parsed == [attachment])
// 2. Fail-closed when Tor is not ready
let torBlockedService = BlossomMediaService(
defaults: UserDefaults(suiteName: "BlossomTor-\(UUID().uuidString)")!,
dependencies: .init(
awaitTorReady: { false },
isNetworkActivationAllowed: { true },
performRequest: { _, _ in (Data(), 200) },
now: Date.init
)
)
await #expect(throws: BlossomMediaError.torNotReady) {
_ = try await torBlockedService.uploadImage(rawData: sampleImageData, senderIdentity: identity)
}
// 3. Full upload -> download round-trip with BUD-02 auth header & SHA-256 verification
final class MockBlossomStore: @unchecked Sendable {
private let lock = NSLock()
private var blob = Data()
private var authHeader: String?
func store(blob: Data, authHeader: String?) -> String {
lock.lock()
defer { lock.unlock() }
self.blob = blob
self.authHeader = authHeader
return blob.sha256Fingerprint()
}
func loadBlob() -> Data {
lock.lock()
defer { lock.unlock() }
return blob
}
func loadAuthHeader() -> String? {
lock.lock()
defer { lock.unlock() }
return authHeader
}
}
let store = MockBlossomStore()
let service = BlossomMediaService(
defaults: UserDefaults(suiteName: "BlossomOK-\(UUID().uuidString)")!,
dependencies: .init(
awaitTorReady: { true },
isNetworkActivationAllowed: { true },
performRequest: { request, _ in
if request.httpMethod == "PUT" {
let hash = store.store(
blob: request.httpBody ?? Data(),
authHeader: request.value(forHTTPHeaderField: "Authorization")
)
let json = #"{"url":"https://blossom.example.com/\#(hash).jpg","sha256":"\#(hash)"}"#
return (Data(json.utf8), 200)
} else {
return (store.loadBlob(), 200)
}
},
now: Date.init
)
)
let uploaded = try await service.uploadImage(rawData: sampleImageData, senderIdentity: identity)
#expect(store.loadAuthHeader()?.hasPrefix("Nostr ") == true)
#expect(uploaded.sha256Hex == store.loadBlob().sha256Fingerprint())
let downloadedImage = try await service.fetchVerifiedImage(for: uploaded)
#expect(downloadedImage.size.width > 0)
#expect(service.cachedImage(for: uploaded.sha256Hex) != nil)
// Panic wipe evicts cached verified media
service.resetForPanic()
#expect(service.cachedImage(for: uploaded.sha256Hex) == nil)
// Tampered blob bytes fail SHA-256 verification
let tamperedService = BlossomMediaService(
defaults: UserDefaults(suiteName: "BlossomTamper-\(UUID().uuidString)")!,
dependencies: .init(
awaitTorReady: { true },
isNetworkActivationAllowed: { true },
performRequest: { _, _ in (Data("tampered".utf8), 200) },
now: Date.init
)
)
await #expect(throws: BlossomMediaError.hashMismatch) {
_ = try await tamperedService.fetchVerifiedImage(for: uploaded)
}
}
@Test
func globeActivityBeaconsCombineChatNotesAndBookmarks() {
let beacons = GlobeActivityBeacon.buildBeacons(
chatCounts: ["9q8yy": 5, "u4pru": 2],
noteCounts: ["9q8yy": 3],
bookmarks: ["9q8yy", "xn76u"]
)
#expect(beacons.count == 3)
#expect(beacons[0].geohash == "9q8yy")
#expect(beacons[0].activityCount == 8)
#expect(beacons[0].isBookmarked)
#expect(beacons.first(where: { $0.geohash == "xn76u" })?.isBookmarked == true)
#expect(beacons.first(where: { $0.geohash == "xn76u" })?.activityCount == 0)
}
private func makeTinyPNGData() throws -> Data {
let colorSpace = CGColorSpaceCreateDeviceRGB()
guard let ctx = CGContext(
data: nil,
width: 4,
height: 4,
bitsPerComponent: 8,
bytesPerRow: 16,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
), let cgImage = ctx.makeImage() else {
throw BlossomMediaError.invalidImage
}
let mutable = NSMutableData()
guard let dest = CGImageDestinationCreateWithData(mutable, UTType.png.identifier as CFString, 1, nil) else {
throw BlossomMediaError.invalidImage
}
CGImageDestinationAddImage(dest, cgImage, nil)
guard CGImageDestinationFinalize(dest) else {
throw BlossomMediaError.invalidImage
}
return mutable as Data
}
}
+493
View File
@@ -0,0 +1,493 @@
//
// PlaceFeedTests.swift
// bitchatTests
//
// Unit and smoke coverage for Phase 1 Place Feed:
// - NIP-10 thread tagging & parsing (marked root/reply, mention ignore, legacy positional)
// - NIP-25 kind-7 reactions (create, parse, normalize, toggle on/off + NIP-09 delete)
// - NIP-13 PoW mining & validatedDifficulty scoring on kind-1 notes
// - LocationNotesManager threading, out-of-order replies, pruning, and panic-wipe fencing
// - PlaceFeedOrganizer sorting (.latest / .top), filtering (.all / .localOnly / .verifiedPoW), and search
// - SwiftUI smoke rendering of PlaceFeedView and PlaceThreadSheet
//
import Combine
import Foundation
import SwiftUI
import Testing
@testable import bitchat
struct PlaceFeedProtocolTests {
@Test
func nip10_directReplyEmitsMarkedRootAndAuthorTags() throws {
let author = try NostrIdentity.generate()
let rootID = String(repeating: "a", count: 64)
let rootAuthor = String(repeating: "b", count: 64)
let event = try NostrProtocol.createGeohashTextNote(
content: "first reply",
geohash: "9q8yy",
senderIdentity: author,
nickname: "bob",
replyTo: .init(rootEventID: rootID, replyEventID: nil, replyAuthorPubkey: rootAuthor),
teleported: true
)
#expect(event.kind == NostrProtocol.EventKind.textNote.rawValue)
#expect(event.tags.contains(["g", "9q8yy"]))
#expect(event.tags.contains(["t", "teleport"]))
#expect(event.tags.contains(["e", rootID, "", "root"]))
#expect(event.tags.contains(["p", rootAuthor]))
let parsed = try #require(NostrProtocol.parseThreadReference(from: event.tags))
#expect(parsed.rootEventID == rootID)
#expect(parsed.replyEventID == nil)
#expect(parsed.replyAuthorPubkey == rootAuthor)
}
@Test
func nip10_nestedReplyEmitsBothRootAndReplyMarkers() throws {
let author = try NostrIdentity.generate()
let rootID = String(repeating: "1", count: 64)
let parentID = String(repeating: "2", count: 64)
let parentAuthor = String(repeating: "3", count: 64)
let event = try NostrProtocol.createGeohashTextNote(
content: "nested reply",
geohash: "9q8yy",
senderIdentity: author,
replyTo: .init(rootEventID: rootID, replyEventID: parentID, replyAuthorPubkey: parentAuthor)
)
#expect(event.tags.contains(["e", rootID, "", "root"]))
#expect(event.tags.contains(["e", parentID, "", "reply"]))
let parsed = try #require(NostrProtocol.parseThreadReference(from: event.tags))
#expect(parsed.rootEventID == rootID)
#expect(parsed.replyEventID == parentID)
#expect(parsed.replyAuthorPubkey == parentAuthor)
}
@Test
func nip10_parserIgnoresMentionsAndSupportsLegacyPositionalTags() throws {
let mentionOnly = [["e", String(repeating: "c", count: 64), "", "mention"]]
#expect(NostrProtocol.parseThreadReference(from: mentionOnly) == nil)
let rootID = String(repeating: "d", count: 64)
let midID = String(repeating: "e", count: 64)
let leafID = String(repeating: "f", count: 64)
let positional = [
["e", rootID],
["e", midID],
["e", leafID]
]
let parsed = try #require(NostrProtocol.parseThreadReference(from: positional))
#expect(parsed.rootEventID == rootID)
#expect(parsed.replyEventID == leafID)
}
@Test
func nip25_reactionCreateAndParseUsesFirstETagAndValidatesEmoji() throws {
let author = try NostrIdentity.generate()
let targetID = String(repeating: "a", count: 64)
let targetAuthor = String(repeating: "b", count: 64)
let reaction = try NostrProtocol.createGeohashReactionEvent(
emoji: "🔥",
targetEventID: targetID,
targetAuthorPubkey: targetAuthor,
geohash: "9q8yy",
senderIdentity: author
)
#expect(reaction.kind == NostrProtocol.EventKind.reaction.rawValue)
#expect(reaction.isValidSignature())
#expect(reaction.tags.contains(["g", "9q8yy"]))
#expect(reaction.tags.contains(["e", targetID]))
#expect(reaction.tags.contains(["p", targetAuthor]))
let parsed = try #require(NostrProtocol.parseReactionTarget(from: reaction))
#expect(parsed.targetEventID == targetID)
#expect(parsed.emoji == "🔥")
// First valid `e` tag wins so appended extra `e` tags cannot retarget a reaction.
let extraID = String(repeating: "9", count: 64)
let plusEvent = try NostrEvent(
pubkey: author.publicKeyHex,
createdAt: Date(),
kind: .reaction,
tags: [["g", "9q8yy"], ["e", targetID], ["e", extraID]],
content: "+"
).sign(with: author.schnorrSigningKey())
let parsedPlus = try #require(NostrProtocol.parseReactionTarget(from: plusEvent))
#expect(parsedPlus.targetEventID == targetID)
#expect(parsedPlus.emoji == "❤️")
let minusEvent = try NostrEvent(
pubkey: author.publicKeyHex,
createdAt: Date(),
kind: .reaction,
tags: [["g", "9q8yy"], ["e", targetID]],
content: "-"
).sign(with: author.schnorrSigningKey())
#expect(NostrProtocol.parseReactionTarget(from: minusEvent) == nil)
// Plain ASCII text and multi-grapheme strings are rejected as emoji chips.
#expect(NostrProtocol.normalizeReactionContent("ok") == nil)
#expect(NostrProtocol.normalizeReactionContent("ab") == nil)
#expect(NostrProtocol.normalizeReactionContent("1") == nil)
#expect(NostrProtocol.normalizeReactionContent("🔥🔥") == nil)
#expect(NostrProtocol.normalizeReactionContent("❤️") == "❤️")
}
@Test
func nip13_validatedPoWDifficultyChecksCommittedTargetAndLeadingZeros() {
let id16 = "0000" + String(repeating: "f", count: 60)
#expect(NostrProtocol.validatedPoWDifficulty(idHex: id16, tags: [["nonce", "1", "16"]]) == 16)
#expect(NostrProtocol.validatedPoWDifficulty(idHex: id16, tags: [["nonce", "1", "8"]]) == 8)
#expect(NostrProtocol.validatedPoWDifficulty(idHex: id16, tags: [["nonce", "1", "20"]]) == 0)
#expect(NostrProtocol.validatedPoWDifficulty(idHex: id16, tags: [["g", "9q8yy"]]) == 0)
}
}
@MainActor
struct PlaceFeedManagerTests {
@Test
func ingestSeparatesRepliesFromTopLevelAndOrdersRepliesChronologically() throws {
var handler: ((NostrEvent) -> Void)?
let now = Date(timeIntervalSince1970: 1_700_000_000)
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, onEvent, _ in handler = onEvent },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in try NostrIdentity.generate() },
now: { now }
)
let manager = LocationNotesManager(geohash: "9q8yy", dependencies: deps)
let alice = try NostrIdentity.generate()
let bob = try NostrIdentity.generate()
let rootEvent = try NostrProtocol.createGeohashTextNote(
content: "root post",
geohash: "9q8yy",
senderIdentity: alice,
nickname: "alice",
createdAt: now.addingTimeInterval(-300)
)
let laterReply = try NostrProtocol.createGeohashTextNote(
content: "second reply",
geohash: "9q8yy",
senderIdentity: alice,
nickname: "alice",
replyTo: .init(rootEventID: rootEvent.id, replyAuthorPubkey: bob.publicKeyHex),
createdAt: now.addingTimeInterval(-60)
)
let earlierReply = try NostrProtocol.createGeohashTextNote(
content: "first reply",
geohash: "9q8yy",
senderIdentity: bob,
nickname: "bob",
replyTo: .init(rootEventID: rootEvent.id, replyAuthorPubkey: alice.publicKeyHex),
createdAt: now.addingTimeInterval(-180)
)
// Deliver reply BEFORE root to verify out-of-order resilience.
handler?(laterReply)
handler?(rootEvent)
handler?(earlierReply)
#expect(manager.notes.count == 1)
#expect(manager.notes.first?.id == rootEvent.id)
#expect(manager.replyCount(forRootID: rootEvent.id) == 2)
#expect(manager.replies(forRootID: rootEvent.id).map(\.content) == ["first reply", "second reply"])
}
@Test
func toggleReactionPublishesKind7AndRetractsWithNip09Delete() throws {
var sentEvents: [NostrEvent] = []
var handler: ((NostrEvent) -> Void)?
let now = Date(timeIntervalSince1970: 1_700_000_000)
let me = try NostrIdentity.generate()
let peer = try NostrIdentity.generate()
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, onEvent, _ in handler = onEvent },
unsubscribe: { _ in },
sendEvent: { event, _ in sentEvents.append(event) },
deriveIdentity: { _ in me },
now: { now }
)
let manager = LocationNotesManager(geohash: "9q8yy", dependencies: deps)
let rootEvent = try NostrProtocol.createGeohashTextNote(
content: "coffee meetup",
geohash: "9q8yy",
senderIdentity: peer,
nickname: "peer",
createdAt: now
)
handler?(rootEvent)
let rootNote = try #require(manager.notes.first)
// Peer reacts with 🔥
let peerReaction = try NostrProtocol.createGeohashReactionEvent(
emoji: "🔥",
targetEventID: rootNote.id,
targetAuthorPubkey: peer.publicKeyHex,
geohash: "9q8yy",
senderIdentity: peer,
createdAt: now
)
handler?(peerReaction)
#expect(manager.reactions(forNoteID: rootNote.id) == [
AggregatedReaction(emoji: "🔥", count: 1, includesCurrentUser: false)
])
// We toggle 🔥 on -> publishes kind 7 and increments count to 2
#expect(manager.toggleReaction(emoji: "🔥", on: rootNote))
#expect(sentEvents.count == 1)
#expect(sentEvents[0].kind == NostrProtocol.EventKind.reaction.rawValue)
let ourReactionID = sentEvents[0].id
#expect(manager.reactions(forNoteID: rootNote.id) == [
AggregatedReaction(emoji: "🔥", count: 2, includesCurrentUser: true)
])
// We toggle 🔥 off -> publishes geohash-tagged NIP-09 kind 5 deletion and returns count to 1
#expect(manager.toggleReaction(emoji: "🔥", on: rootNote))
#expect(sentEvents.count == 2)
#expect(sentEvents[1].kind == NostrProtocol.EventKind.deletion.rawValue)
#expect(sentEvents[1].tags.contains(["e", ourReactionID]))
#expect(sentEvents[1].tags.contains(["g", "9q8yy"]))
#expect(manager.reactions(forNoteID: rootNote.id) == [
AggregatedReaction(emoji: "🔥", count: 1, includesCurrentUser: false)
])
// Forged NIP-09 deletion from another author is ignored.
let imposter = try NostrIdentity.generate()
let forgedDelete = try NostrProtocol.createDeleteEvent(
ofEventID: peerReaction.id,
senderIdentity: imposter,
geohash: "9q8yy"
)
handler?(forgedDelete)
#expect(manager.reactions(forNoteID: rootNote.id) == [
AggregatedReaction(emoji: "🔥", count: 1, includesCurrentUser: false)
])
// Legitimate NIP-09 deletion from the reaction author retracts the reaction live.
let peerDelete = try NostrProtocol.createDeleteEvent(
ofEventID: peerReaction.id,
senderIdentity: peer,
geohash: "9q8yy"
)
handler?(peerDelete)
#expect(manager.reactions(forNoteID: rootNote.id).isEmpty)
}
@Test
func resetForPanicClearsThreadsReactionsAndNotes() throws {
var sentEvents: [NostrEvent] = []
var handler: ((NostrEvent) -> Void)?
let now = Date(timeIntervalSince1970: 1_700_000_000)
let me = try NostrIdentity.generate()
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, onEvent, _ in handler = onEvent },
unsubscribe: { _ in },
sendEvent: { event, _ in sentEvents.append(event) },
deriveIdentity: { _ in me },
now: { now }
)
let manager = LocationNotesManager(geohash: "9q8yy", dependencies: deps)
let root = try NostrProtocol.createGeohashTextNote(
content: "pre-panic root",
geohash: "9q8yy",
senderIdentity: me,
createdAt: now
)
let reply = try NostrProtocol.createGeohashTextNote(
content: "pre-panic reply",
geohash: "9q8yy",
senderIdentity: me,
replyTo: .init(rootEventID: root.id),
createdAt: now
)
let reaction = try NostrProtocol.createGeohashReactionEvent(
emoji: "❤️",
targetEventID: root.id,
targetAuthorPubkey: me.publicKeyHex,
geohash: "9q8yy",
senderIdentity: me,
createdAt: now
)
handler?(root)
handler?(reply)
handler?(reaction)
#expect(manager.notes.count == 1)
#expect(manager.replyCount(forRootID: root.id) == 1)
#expect(manager.totalReactionCount(forNoteID: root.id) == 1)
manager.resetForPanic()
#expect(manager.notes.isEmpty)
#expect(manager.repliesByRootID.isEmpty)
#expect(manager.reactionsByNoteID.isEmpty)
#expect(sentEvents.isEmpty)
}
@Test
func deleteRemovesOwnReplyAndPruneDropsExpiredReplies() throws {
var sentEvents: [NostrEvent] = []
var handler: ((NostrEvent) -> Void)?
var currentNow = Date(timeIntervalSince1970: 1_700_000_000)
let me = try NostrIdentity.generate()
let other = try NostrIdentity.generate()
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, onEvent, _ in handler = onEvent },
unsubscribe: { _ in },
sendEvent: { event, _ in sentEvents.append(event) },
deriveIdentity: { _ in me },
now: { currentNow }
)
let manager = LocationNotesManager(geohash: "9q8yy", dependencies: deps)
let root = try NostrProtocol.createGeohashTextNote(
content: "root",
geohash: "9q8yy",
senderIdentity: other,
createdAt: currentNow
)
let ownReply = try NostrProtocol.createGeohashTextNote(
content: "mine",
geohash: "9q8yy",
senderIdentity: me,
replyTo: .init(rootEventID: root.id),
createdAt: currentNow
)
let expiringReply = try NostrProtocol.createGeohashTextNote(
content: "fades soon",
geohash: "9q8yy",
senderIdentity: other,
expiresAt: currentNow.addingTimeInterval(60),
replyTo: .init(rootEventID: root.id),
createdAt: currentNow
)
handler?(root)
handler?(ownReply)
handler?(expiringReply)
#expect(manager.replyCount(forRootID: root.id) == 2)
let mineNote = try #require(manager.replies(forRootID: root.id).first(where: { $0.content == "mine" }))
#expect(manager.delete(note: mineNote))
#expect(sentEvents.last?.kind == NostrProtocol.EventKind.deletion.rawValue)
#expect(manager.replyCount(forRootID: root.id) == 1)
currentNow = currentNow.addingTimeInterval(120)
manager.pruneExpiredNotes()
#expect(manager.replyCount(forRootID: root.id) == 0)
}
@Test
func organizerSortsTopFiltersLocalAndPoWAndSearches() {
let base = Date(timeIntervalSince1970: 1_700_000_000)
let localPlain = NoticeItem(note: .init(
id: "a1", pubkey: "1111", content: "rain starting downtown",
createdAt: base.addingTimeInterval(100), nickname: "alice", geohash: "9q8yy",
powDifficulty: 0, isTeleported: false
))
let teleportedPoW = NoticeItem(note: .init(
id: "b2", pubkey: "2222", content: "watching from afar",
createdAt: base.addingTimeInterval(50), nickname: "bob", geohash: "9q8yy",
powDifficulty: 10, isTeleported: true
))
let localPopular = NoticeItem(note: .init(
id: "c3", pubkey: "3333", content: "block party on 5th",
createdAt: base, nickname: "carol", geohash: "9q8yy",
powDifficulty: 8, isTeleported: false
))
let items = [localPlain, teleportedPoW, localPopular]
// Latest sort
let latest = PlaceFeedOrganizer.organize(items: items, sort: .latest, filter: .all)
#expect(latest.map(\.id) == ["a1", "b2", "c3"])
// Top sort ranks by replies * 3 + reactions * 2 + pow bonus
let top = PlaceFeedOrganizer.organize(
items: items,
sort: .top,
filter: .all,
replyCount: { $0 == "c3" ? 4 : 0 },
reactionCount: { $0 == "b2" ? 2 : 0 }
)
#expect(top.map(\.id) == ["c3", "b2", "a1"])
// On-site filter hides teleported posts
let localOnly = PlaceFeedOrganizer.organize(items: items, sort: .latest, filter: .localOnly)
#expect(localOnly.map(\.id) == ["a1", "c3"])
// PoW filter keeps only validated PoW (or board) posts
let powOnly = PlaceFeedOrganizer.organize(items: items, sort: .latest, filter: .verifiedPoW)
#expect(powOnly.map(\.id) == ["b2", "c3"])
// Search query matches content or author case-insensitively
let search = PlaceFeedOrganizer.organize(items: items, sort: .latest, filter: .all, query: "CAROL")
#expect(search.map(\.id) == ["c3"])
}
@Test
func placeFeedAndThreadViewsRenderWithoutCrashing() throws {
let now = Date(timeIntervalSince1970: 1_700_000_000)
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, _, onEOSE in onEOSE?() },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in try NostrIdentity.generate() },
now: { now }
)
let manager = LocationNotesManager(geohash: "9q8yy", dependencies: deps)
let transport = MockTransport()
let board = BoardManager(transport: transport, store: BoardStore(persistsToDisk: false))
let locationManager = LocationChannelManager(storage: UserDefaults(suiteName: "PlaceFeedSmoke-\(UUID().uuidString)") ?? .standard)
let locationModel = LocationChannelsModel(manager: locationManager)
let channel = GeohashChannel(level: .city, geohash: "9q8yy")
let feedView = PlaceFeedView(
channel: channel,
senderNickname: "tester",
board: board,
isTeleported: false,
notesManager: manager
)
.environmentObject(locationModel)
let rootNote = LocationNotesManager.Note(
id: String(repeating: "a", count: 64),
pubkey: String(repeating: "b", count: 64),
content: "smoke test root post",
createdAt: now,
nickname: "alice",
geohash: "9q8yy",
powDifficulty: 8
)
let threadSheet = PlaceThreadSheet(
rootNote: rootNote,
geohash: "9q8yy",
senderNickname: "tester",
isTeleported: false,
manager: manager
)
#expect(String(describing: type(of: feedView)).contains("PlaceFeedView"))
#expect(String(describing: type(of: threadSheet)).contains("PlaceThreadSheet"))
}
}
@@ -162,14 +162,13 @@ struct GatewayServiceTests {
func structuralGates() throws {
let fixture = Fixture()
// Wrong kind (kind-1 text note instead of kind-20000 ephemeral).
// Wrong kind (kind-0 profile metadata is not carried over the BLE gateway).
let identity = try NostrIdentity.generate()
let note = try NostrProtocol.createGeohashTextNote(
content: "note",
geohash: Self.geohash,
let metadata = try NostrProtocol.createMetadataEvent(
profile: .init(name: "alice", displayName: nil, about: nil, nip05: nil),
senderIdentity: identity
)
try deposit(note, into: fixture)
try deposit(metadata, into: fixture)
#expect(fixture.published.isEmpty)
// Carrier geohash disagreeing with the event's #g tag.