From f544ac3a00e6b1fe4b12418d92bc630a1d9e18a5 Mon Sep 17 00:00:00 2001 From: Taksh Date: Mon, 12 Oct 2026 08:37:13 +0530 Subject: [PATCH 1/8] add a signed endorsement kind to the board wire format An endorsement is a third party's Ed25519 statement that it stands behind a board post. It binds the post ID and the post author's key so it cannot be re-pointed at another author's post. Clients that predate kind 0x03 fail the decode and drop it without relaying, same as any unknown kind. The store rejects endorsements for now; retention comes next. --- bitchat/Protocols/BoardPackets.swift | 82 ++++++++++++++++- bitchat/Services/Board/BoardStore.swift | 2 + .../Protocols/BoardPacketsTests.swift | 88 +++++++++++++++++++ 3 files changed, 168 insertions(+), 4 deletions(-) diff --git a/bitchat/Protocols/BoardPackets.swift b/bitchat/Protocols/BoardPackets.swift index d265a1c1..cfbea657 100644 --- a/bitchat/Protocols/BoardPackets.swift +++ b/bitchat/Protocols/BoardPackets.swift @@ -12,18 +12,22 @@ import Foundation // MARK: - Board wire format (MessageType.boardPost payloads) // // TLV layout (type u8, length u16 big-endian, value), matching REQUEST_SYNC: -// - 0x01: kind (u8) — 0x01 post, 0x02 tombstone +// - 0x01: kind (u8) — 0x01 post, 0x02 tombstone, 0x03 endorsement // - 0x02: postID (16B random) // - 0x03: geohash (UTF-8, empty = mesh-local board, max 12 chars) // - 0x04: content (UTF-8, 1...512 bytes) [post] -// - 0x05: authorSigningKey (32B Ed25519 public key) +// - 0x05: authorSigningKey (32B Ed25519 public key; for an endorsement, +// the endorsed post's author) // - 0x06: authorNickname (UTF-8, max 64 bytes) // - 0x07: createdAt (u64 big-endian, ms) [post] // - 0x08: expiresAt (u64 big-endian, ms, max 7 days after createdAt) [post] // - 0x09: flags (u8, bit0 = urgent) [post] // - 0x0A: signature (64B Ed25519) // - 0x0B: deletedAt (u64 big-endian, ms) [tombstone] -// Unknown TLVs are skipped for forward compatibility. +// - 0x0C: endorserSigningKey (32B Ed25519 public key) [endorsement] +// - 0x0D: endorsedAt (u64 big-endian, ms) [endorsement] +// Unknown TLVs are skipped for forward compatibility. Clients that predate a +// kind fail to decode it and drop it without relaying. enum BoardWireConstants { static let postIDLength = 16 @@ -36,6 +40,7 @@ enum BoardWireConstants { static let maxLifetimeMs: UInt64 = 7 * 24 * 60 * 60 * 1000 static let postSigningContext = "bitchat-board-v1" static let tombstoneSigningContext = "bitchat-board-del-v1" + static let endorsementSigningContext = "bitchat-board-endorse-v1" static let geohashAlphabet = Set("0123456789bcdefghjkmnpqrstuvwxyz") } @@ -51,11 +56,14 @@ private enum BoardTLVType: UInt8 { case flags = 0x09 case signature = 0x0A case deletedAt = 0x0B + case endorserSigningKey = 0x0C + case endorsedAt = 0x0D } private enum BoardWireKind: UInt8 { case post = 0x01 case tombstone = 0x02 + case endorsement = 0x03 } /// A signed, persistent bulletin-board notice. @@ -143,10 +151,52 @@ struct BoardTombstonePacket: Equatable { } } -/// Decoded board payload: either a live post or a tombstone. +/// A signed "I vouch for this post" from someone other than its author. +/// Receivers count only endorsements from keys they already trust, so a +/// stranger minting keys cannot manufacture confirmation. +struct BoardEndorsementPacket: Equatable { + let postID: Data + /// Bound into the signature so an endorsement cannot be re-pointed at a + /// different author's post that reuses the ID. + let postAuthorSigningKey: Data + let endorserSigningKey: Data + let endorsedAt: UInt64 + let signature: Data + + static func signingBytes( + postID: Data, + postAuthorSigningKey: Data, + endorserSigningKey: Data, + endorsedAt: UInt64 + ) -> Data { + var out = Data() + BoardWireEncoding.appendContext(BoardWireConstants.endorsementSigningContext, to: &out) + out.append(postID) + out.append(postAuthorSigningKey) + out.append(endorserSigningKey) + BoardWireEncoding.appendUInt64(endorsedAt, to: &out) + return out + } + + var signingBytes: Data { + Self.signingBytes( + postID: postID, + postAuthorSigningKey: postAuthorSigningKey, + endorserSigningKey: endorserSigningKey, + endorsedAt: endorsedAt + ) + } + + func verifySignature() -> Bool { + BoardWireEncoding.verify(signature: signature, over: signingBytes, publicKey: endorserSigningKey) + } +} + +/// Decoded board payload: a live post, a tombstone, or an endorsement. enum BoardWire: Equatable { case post(BoardPostPacket) case tombstone(BoardTombstonePacket) + case endorsement(BoardEndorsementPacket) func encode() -> Data { var out = Data() @@ -175,6 +225,13 @@ enum BoardWire: Equatable { putTLV(.authorSigningKey, tombstone.authorSigningKey) putTLV(.deletedAt, BoardWireEncoding.uint64Data(tombstone.deletedAt)) putTLV(.signature, tombstone.signature) + case .endorsement(let endorsement): + putTLV(.kind, Data([BoardWireKind.endorsement.rawValue])) + putTLV(.postID, endorsement.postID) + putTLV(.authorSigningKey, endorsement.postAuthorSigningKey) + putTLV(.endorserSigningKey, endorsement.endorserSigningKey) + putTLV(.endorsedAt, BoardWireEncoding.uint64Data(endorsement.endorsedAt)) + putTLV(.signature, endorsement.signature) } return out } @@ -196,6 +253,8 @@ enum BoardWire: Equatable { var flags: UInt8? var signature: Data? var deletedAt: UInt64? + var endorserSigningKey: Data? + var endorsedAt: UInt64? while off + 3 <= data.endIndex { let t = data[off]; off += 1 @@ -235,6 +294,11 @@ enum BoardWire: Equatable { signature = v case .deletedAt: deletedAt = BoardWireEncoding.uint64(from: v) + case .endorserSigningKey: + guard v.count == BoardWireConstants.signingKeyLength else { return nil } + endorserSigningKey = v + case .endorsedAt: + endorsedAt = BoardWireEncoding.uint64(from: v) case nil: continue // forward compatible; ignore unknown TLVs } @@ -272,6 +336,15 @@ enum BoardWire: Equatable { deletedAt: deletedAt, signature: signature )) + case .endorsement: + guard let endorserSigningKey, let endorsedAt else { return nil } + return .endorsement(BoardEndorsementPacket( + postID: postID, + postAuthorSigningKey: authorSigningKey, + endorserSigningKey: endorserSigningKey, + endorsedAt: endorsedAt, + signature: signature + )) case nil: return nil } @@ -281,6 +354,7 @@ enum BoardWire: Equatable { switch self { case .post(let post): return post.verifySignature() case .tombstone(let tombstone): return tombstone.verifySignature() + case .endorsement(let endorsement): return endorsement.verifySignature() } } diff --git a/bitchat/Services/Board/BoardStore.swift b/bitchat/Services/Board/BoardStore.swift index db6a9605..e70e22bc 100644 --- a/bitchat/Services/Board/BoardStore.swift +++ b/bitchat/Services/Board/BoardStore.swift @@ -176,6 +176,8 @@ final class BoardStore { return ingestPostLocked(post, packet: packet, rawPacket: rawPacket, nowMs: nowMs) case .tombstone(let tombstone): return ingestTombstoneLocked(tombstone, packet: packet, rawPacket: rawPacket, nowMs: nowMs, retainUntilOverride: retainUntilOverride) + case .endorsement: + return .rejected } } diff --git a/bitchatTests/Protocols/BoardPacketsTests.swift b/bitchatTests/Protocols/BoardPacketsTests.swift index 9e1ff450..2edca9d5 100644 --- a/bitchatTests/Protocols/BoardPacketsTests.swift +++ b/bitchatTests/Protocols/BoardPacketsTests.swift @@ -208,4 +208,92 @@ struct BoardPacketsTests { #expect(!BoardWire.urgentFlag(in: BoardWire.tombstone(tombstone).encode())) #expect(!BoardWire.urgentFlag(in: Data())) } + + @Test func endorsementIsNeverReadAsUrgent() throws { + let post = try makeSignedPost(flags: BoardPostPacket.urgentFlag) + let endorsement = try makeSignedEndorsement(of: post) + #expect(!BoardWire.urgentFlag(in: BoardWire.endorsement(endorsement).encode())) + } + + // MARK: - Endorsements + + private func makeSignedEndorsement( + of post: BoardPostPacket, + endorsedAt: UInt64 = 1_700_000_050_000, + signWith key: Curve25519.Signing.PrivateKey = Curve25519.Signing.PrivateKey(), + claimKey: Data? = nil + ) throws -> BoardEndorsementPacket { + let endorserKey = claimKey ?? key.publicKey.rawRepresentation + let signingBytes = BoardEndorsementPacket.signingBytes( + postID: post.postID, + postAuthorSigningKey: post.authorSigningKey, + endorserSigningKey: endorserKey, + endorsedAt: endorsedAt + ) + return BoardEndorsementPacket( + postID: post.postID, + postAuthorSigningKey: post.authorSigningKey, + endorserSigningKey: endorserKey, + endorsedAt: endorsedAt, + signature: try key.signature(for: signingBytes) + ) + } + + @Test func endorsementRoundTrip() throws { + let post = try makeSignedPost(flags: BoardPostPacket.urgentFlag) + let endorsement = try makeSignedEndorsement(of: post) + let decoded = try #require(BoardWire.decode(from: BoardWire.endorsement(endorsement).encode())) + #expect(decoded == .endorsement(endorsement)) + #expect(decoded.verifySignature()) + } + + @Test func forgedEndorsementSignatureFailsVerification() throws { + let post = try makeSignedPost() + let victim = Curve25519.Signing.PrivateKey() + let forged = try makeSignedEndorsement(of: post, claimKey: victim.publicKey.rawRepresentation) + let decoded = try #require(BoardWire.decode(from: BoardWire.endorsement(forged).encode())) + #expect(!decoded.verifySignature()) + } + + @Test func endorsementCannotBeRepointedAtAnotherAuthor() throws { + let post = try makeSignedPost() + let endorsement = try makeSignedEndorsement(of: post) + let repointed = BoardEndorsementPacket( + postID: endorsement.postID, + postAuthorSigningKey: Curve25519.Signing.PrivateKey().publicKey.rawRepresentation, + endorserSigningKey: endorsement.endorserSigningKey, + endorsedAt: endorsement.endorsedAt, + signature: endorsement.signature + ) + let decoded = try #require(BoardWire.decode(from: BoardWire.endorsement(repointed).encode())) + #expect(!decoded.verifySignature()) + } + + @Test func endorsementMissingEndorserKeyIsRejected() throws { + let post = try makeSignedPost() + let endorsement = try makeSignedEndorsement(of: post) + var encoded = Data() + func putTLV(_ type: UInt8, _ value: Data) { + encoded.append(type) + encoded.append(UInt8(value.count >> 8)) + encoded.append(UInt8(value.count & 0xFF)) + encoded.append(value) + } + putTLV(0x01, Data([0x03])) + putTLV(0x02, endorsement.postID) + putTLV(0x05, endorsement.postAuthorSigningKey) + putTLV(0x0D, BoardWireEncoding.uint64Data(endorsement.endorsedAt)) + putTLV(0x0A, endorsement.signature) + #expect(BoardWire.decode(from: encoded) == nil) + } + + @Test func endorsementSigningContextIsDistinctFromPostsAndTombstones() throws { + // A signature over one board kind must never verify as another. + let contexts = [ + BoardWireConstants.postSigningContext, + BoardWireConstants.tombstoneSigningContext, + BoardWireConstants.endorsementSigningContext + ] + #expect(Set(contexts).count == contexts.count) + } } From d3305b9c563854678e0bb2e6ac83fbe001258a30 Mon Sep 17 00:00:00 2001 From: Taksh Date: Mon, 12 Oct 2026 08:47:39 +0530 Subject: [PATCH 2/8] retain board endorsements alongside posts and tombstones Endorsements live as long as the post they name, sync in the same gossip round, and die with it on tombstone, eviction, or expiry. One that races ahead of its post is held as an orphan and counts once the post lands. Caps keep them inside the board's sync budget: 16 per post (first come keeps the slot, so a burst of fresh keys cannot push out endorsers that already count), 200 overall, and orphans bounded per endorser and in total like orphan tombstones. Self-endorsements and ones naming the wrong author are refused. --- bitchat/Services/Board/BoardStore.swift | 194 +++++++++++++++- bitchatTests/Services/BoardStoreTests.swift | 236 ++++++++++++++++++++ 2 files changed, 424 insertions(+), 6 deletions(-) diff --git a/bitchat/Services/Board/BoardStore.swift b/bitchat/Services/Board/BoardStore.swift index e70e22bc..37bbe5d7 100644 --- a/bitchat/Services/Board/BoardStore.swift +++ b/bitchat/Services/Board/BoardStore.swift @@ -44,6 +44,14 @@ final class BoardStore { /// is entirely sender-controlled; cap them like posts. static let maxOrphanTombstones = 100 static let maxOrphanTombstonesPerAuthor = 5 + /// Endorsements ride the same GCS sync filter as posts, so they are + /// bounded to roughly the post budget rather than posts × endorsers. + static let maxEndorsements = 200 + /// Confirmation only needs a handful of trusted voices; past this a + /// post has more endorsements than any receiver will count. + static let maxEndorsementsPerPost = 16 + static let maxOrphanEndorsements = 50 + static let maxOrphanEndorsementsPerEndorser = 5 /// Allowance for clock skew between peers when judging received /// timestamps against local time. static let clockSkewMs: UInt64 = 60 * 60 * 1000 @@ -65,6 +73,16 @@ final class BoardStore { let isOrphan: Bool } + private struct StoredEndorsement { + let endorsement: BoardEndorsementPacket + let packet: BitchatPacket + let rawPacket: Data + var retainUntil: UInt64 + /// True while the endorsed post is unknown here; only these count + /// against the orphan caps. + var isOrphan: Bool + } + /// On-disk entry: the raw signed packet, plus the retention deadline for /// tombstones (derived from the deleted post's original expiry, which is /// no longer recoverable once the post is gone). @@ -84,12 +102,21 @@ final class BoardStore { /// store rejects them. let postArrivals = PassthroughSubject() + /// Endorser signing keys per live postID, published on the main thread. + /// Raw keys only: whether an endorser counts is the reader's trust call. + @Published private(set) var endorsementsSnapshot: [Data: [Data]] = [:] + + /// Fires on the main thread for each endorsement newly accepted from the + /// wire whose post is known here — not for disk restores. + let endorsementArrivals = PassthroughSubject() + /// Fires on the main thread after a panic wipe so derived state (pending /// alerts, unseen badges) is dropped along with the posts themselves. let didWipe = PassthroughSubject() private var posts: [StoredPost] = [] private var tombstones: [StoredTombstone] = [] + private var endorsements: [StoredEndorsement] = [] private let queue = DispatchQueue(label: "chat.bitchat.board.store") private let fileURL: URL? private let now: () -> Date @@ -114,10 +141,20 @@ final class BoardStore { let result = ingestLocked(wire, packet: packet, rawPacket: rawPacket, nowMs: nowMs) if result == .accepted { persistLocked() - if case .post(let post) = wire { + switch wire { + case .post(let post): DispatchQueue.main.async { [weak self] in self?.postArrivals.send(post) } + case .endorsement(let endorsement): + let hasPost = posts.contains { $0.post.postID == endorsement.postID } + if hasPost { + DispatchQueue.main.async { [weak self] in + self?.endorsementArrivals.send(endorsement) + } + } + case .tombstone: + break } } return result @@ -135,12 +172,24 @@ final class BoardStore { } } - /// Raw signed packets (posts and live tombstones) for gossip sync rounds. + /// Endorser signing keys stored for one post, oldest endorsement first. + func endorserKeys(forPostID postID: Data) -> [Data] { + let nowMs = currentMs() + return queue.sync { + pruneExpiredLocked(nowMs: nowMs) + return endorsements + .filter { !$0.isOrphan && $0.endorsement.postID == postID } + .map(\.endorsement.endorserSigningKey) + } + } + + /// Raw signed packets (posts, live tombstones, endorsements) for gossip + /// sync rounds. func syncCandidates() -> [BitchatPacket] { let nowMs = currentMs() return queue.sync { pruneExpiredLocked(nowMs: nowMs) - return posts.map(\.packet) + tombstones.map(\.packet) + return posts.map(\.packet) + tombstones.map(\.packet) + endorsements.map(\.packet) } } @@ -151,6 +200,7 @@ final class BoardStore { queue.sync { posts.removeAll() tombstones.removeAll() + endorsements.removeAll() if let fileURL { try? FileManager.default.removeItem(at: fileURL) } @@ -176,8 +226,8 @@ final class BoardStore { return ingestPostLocked(post, packet: packet, rawPacket: rawPacket, nowMs: nowMs) case .tombstone(let tombstone): return ingestTombstoneLocked(tombstone, packet: packet, rawPacket: rawPacket, nowMs: nowMs, retainUntilOverride: retainUntilOverride) - case .endorsement: - return .rejected + case .endorsement(let endorsement): + return ingestEndorsementLocked(endorsement, packet: packet, rawPacket: rawPacket, nowMs: nowMs) } } @@ -197,6 +247,7 @@ final class BoardStore { guard !posts.contains(where: { $0.post.postID == post.postID }) else { return .duplicate } posts.append(StoredPost(post: post, packet: packet, rawPacket: rawPacket)) + adoptOrphanEndorsementsLocked(for: post) // Per-author cap, then global cap; oldest posts are evicted first. let authorPosts = posts.filter { $0.post.authorSigningKey == post.authorSigningKey } @@ -255,6 +306,16 @@ final class BoardStore { } guard retainUntil > nowMs else { return .rejected } tombstones.append(StoredTombstone(tombstone: tombstone, packet: packet, rawPacket: rawPacket, retainUntil: retainUntil, isOrphan: isOrphan)) + // A deleted post's endorsements stop meaning anything; drop them so + // they neither sync on nor count toward the endorsement caps. + let endorsementsBefore = endorsements.count + endorsements.removeAll { + $0.endorsement.postID == tombstone.postID + && $0.endorsement.postAuthorSigningKey == tombstone.authorSigningKey + } + if endorsements.count != endorsementsBefore { + publishSnapshotLocked() + } if isOrphan { enforceOrphanTombstoneCapsLocked(author: tombstone.authorSigningKey) } @@ -262,6 +323,118 @@ final class BoardStore { return .accepted } + private func ingestEndorsementLocked( + _ endorsement: BoardEndorsementPacket, + packet: BitchatPacket, + rawPacket: Data, + nowMs: UInt64 + ) -> BoardIngestResult { + // Self-endorsement adds no independent voice. + guard endorsement.endorserSigningKey != endorsement.postAuthorSigningKey, + endorsement.endorsedAt <= nowMs &+ Limits.clockSkewMs else { + return .rejected + } + if tombstones.contains(where: { + $0.tombstone.postID == endorsement.postID + && $0.tombstone.authorSigningKey == endorsement.postAuthorSigningKey + }) { + return .rejected + } + guard !endorsements.contains(where: { + $0.endorsement.postID == endorsement.postID + && $0.endorsement.endorserSigningKey == endorsement.endorserSigningKey + }) else { return .duplicate } + + if let target = posts.first(where: { $0.post.postID == endorsement.postID })?.post { + guard target.authorSigningKey == endorsement.postAuthorSigningKey else { return .rejected } + let stored = endorsements.filter { !$0.isOrphan && $0.endorsement.postID == endorsement.postID }.count + // First come keeps the slot: evicting by recency would let a burst + // of fresh keys push out endorsements that already counted. A + // full post still relays the endorsement for peers with room. + guard stored < Limits.maxEndorsementsPerPost else { return .accepted } + endorsements.append(StoredEndorsement( + endorsement: endorsement, + packet: packet, + rawPacket: rawPacket, + retainUntil: target.expiresAt, + isOrphan: false + )) + } else { + // Post not here yet (endorsement raced ahead); hold it, bounded + // like an orphan tombstone, so it counts once the post arrives. + let retainUntil = min( + endorsement.endorsedAt &+ Limits.orphanTombstoneLifetimeMs, + nowMs &+ Limits.orphanTombstoneLifetimeMs &+ Limits.clockSkewMs + ) + guard retainUntil > nowMs else { return .rejected } + endorsements.append(StoredEndorsement( + endorsement: endorsement, + packet: packet, + rawPacket: rawPacket, + retainUntil: retainUntil, + isOrphan: true + )) + enforceOrphanEndorsementCapsLocked(endorser: endorsement.endorserSigningKey) + } + enforceEndorsementCapLocked() + publishSnapshotLocked() + return .accepted + } + + /// A newly arrived post claims the endorsements that raced ahead of it. + /// Ones naming a different author key were never about this post. + private func adoptOrphanEndorsementsLocked(for post: BoardPostPacket) { + endorsements.removeAll { + $0.isOrphan + && $0.endorsement.postID == post.postID + && $0.endorsement.postAuthorSigningKey != post.authorSigningKey + } + var adopted = 0 + var overflow = Set() + for index in endorsements.indices + where endorsements[index].isOrphan && endorsements[index].endorsement.postID == post.postID { + guard adopted < Limits.maxEndorsementsPerPost else { + overflow.insert(endorsements[index].endorsement.endorserSigningKey) + continue + } + endorsements[index].isOrphan = false + endorsements[index].retainUntil = post.expiresAt + adopted += 1 + } + if !overflow.isEmpty { + endorsements.removeAll { + $0.isOrphan && $0.endorsement.postID == post.postID + && overflow.contains($0.endorsement.endorserSigningKey) + } + } + } + + private func enforceOrphanEndorsementCapsLocked(endorser: Data) { + let endorserOrphans = endorsements.enumerated().filter { + $0.element.isOrphan && $0.element.endorsement.endorserSigningKey == endorser + } + if endorserOrphans.count > Limits.maxOrphanEndorsementsPerEndorser { + let drop = Set(endorserOrphans.prefix(endorserOrphans.count - Limits.maxOrphanEndorsementsPerEndorser).map(\.offset)) + endorsements = endorsements.enumerated().filter { !drop.contains($0.offset) }.map(\.element) + } + let orphans = endorsements.enumerated().filter { $0.element.isOrphan } + if orphans.count > Limits.maxOrphanEndorsements { + let drop = Set(orphans.prefix(orphans.count - Limits.maxOrphanEndorsements).map(\.offset)) + endorsements = endorsements.enumerated().filter { !drop.contains($0.offset) }.map(\.element) + } + } + + /// Global cap, oldest received first, orphans before endorsements that + /// already count toward a live post. + private func enforceEndorsementCapLocked() { + let excess = endorsements.count - Limits.maxEndorsements + guard excess > 0 else { return } + let orphanOffsets = endorsements.enumerated().filter { $0.element.isOrphan }.map(\.offset) + let matchedOffsets = endorsements.enumerated().filter { !$0.element.isOrphan }.map(\.offset) + let drop = Set((orphanOffsets + matchedOffsets).prefix(excess)) + endorsements = endorsements.enumerated().filter { !drop.contains($0.offset) }.map(\.element) + } + /// Orphan tombstones reference posts we never saw, so a peer can mint /// unlimited valid ones for random IDs; bound them per author and /// globally, evicting the oldest received first (array order). @@ -289,21 +462,29 @@ final class BoardStore { guard !victims.isEmpty else { return } let victimIDs = Set(victims.map { $0.post.postID }) posts.removeAll { victimIDs.contains($0.post.postID) } + endorsements.removeAll { !$0.isOrphan && victimIDs.contains($0.endorsement.postID) } } private func pruneExpiredLocked(nowMs: UInt64) { let postsBefore = posts.count + let endorsementsBefore = endorsements.count posts.removeAll { $0.post.expiresAt <= nowMs } tombstones.removeAll { $0.retainUntil <= nowMs } - if posts.count != postsBefore { + endorsements.removeAll { $0.retainUntil <= nowMs } + if posts.count != postsBefore || endorsements.count != endorsementsBefore { publishSnapshotLocked() } } private func publishSnapshotLocked() { let snapshot = posts.map(\.post) + var endorsersByPost: [Data: [Data]] = [:] + for stored in endorsements where !stored.isOrphan { + endorsersByPost[stored.endorsement.postID, default: []].append(stored.endorsement.endorserSigningKey) + } DispatchQueue.main.async { [weak self] in self?.postsSnapshot = snapshot + self?.endorsementsSnapshot = endorsersByPost } } @@ -317,6 +498,7 @@ final class BoardStore { guard let fileURL else { return } let payloads = posts.map { PersistedEntry(packet: $0.rawPacket, retainUntil: nil) } + tombstones.map { PersistedEntry(packet: $0.rawPacket, retainUntil: $0.retainUntil) } + + endorsements.map { PersistedEntry(packet: $0.rawPacket, retainUntil: nil) } do { if payloads.isEmpty { try? FileManager.default.removeItem(at: fileURL) diff --git a/bitchatTests/Services/BoardStoreTests.swift b/bitchatTests/Services/BoardStoreTests.swift index d501de39..2bb00e2b 100644 --- a/bitchatTests/Services/BoardStoreTests.swift +++ b/bitchatTests/Services/BoardStoreTests.swift @@ -336,6 +336,242 @@ struct BoardStoreTests { #expect(store.syncCandidates().count == cycles) } + // MARK: - Endorsements + + private func makeEndorsement( + of post: BoardPostPacket, + endorser: Curve25519.Signing.PrivateKey, + endorsedAt: UInt64, + postAuthorKey: Data? = nil + ) throws -> (wire: BoardWire, packet: BitchatPacket) { + let authorKey = postAuthorKey ?? post.authorSigningKey + let endorserKey = endorser.publicKey.rawRepresentation + let endorsement = BoardEndorsementPacket( + postID: post.postID, + postAuthorSigningKey: authorKey, + endorserSigningKey: endorserKey, + endorsedAt: endorsedAt, + signature: try endorser.signature(for: BoardEndorsementPacket.signingBytes( + postID: post.postID, + postAuthorSigningKey: authorKey, + endorserSigningKey: endorserKey, + endorsedAt: endorsedAt + )) + ) + let wire = BoardWire.endorsement(endorsement) + return (wire, makePacket(payload: wire.encode(), timestamp: endorsedAt)) + } + + @Test func endorsementIsStoredAndDeduplicated() throws { + let clock = MutableClock(now: baseDate) + let store = makeStore(clock: clock) + let entry = try makePost(author: Curve25519.Signing.PrivateKey(), createdAt: baseMs) + store.ingest(entry.wire, packet: entry.packet) + let endorser = Curve25519.Signing.PrivateKey() + let endorsement = try makeEndorsement(of: entry.post, endorser: endorser, endorsedAt: baseMs + 1) + + #expect(store.ingest(endorsement.wire, packet: endorsement.packet) == .accepted) + #expect(store.ingest(endorsement.wire, packet: endorsement.packet) == .duplicate) + #expect(store.endorserKeys(forPostID: entry.post.postID) == [endorser.publicKey.rawRepresentation]) + #expect(store.syncCandidates().count == 2) + } + + @Test func selfEndorsementIsRejected() throws { + let clock = MutableClock(now: baseDate) + let store = makeStore(clock: clock) + let author = Curve25519.Signing.PrivateKey() + let entry = try makePost(author: author, createdAt: baseMs) + store.ingest(entry.wire, packet: entry.packet) + + let endorsement = try makeEndorsement(of: entry.post, endorser: author, endorsedAt: baseMs + 1) + #expect(store.ingest(endorsement.wire, packet: endorsement.packet) == .rejected) + #expect(store.endorserKeys(forPostID: entry.post.postID).isEmpty) + } + + @Test func endorsementNamingWrongAuthorIsRejected() throws { + let clock = MutableClock(now: baseDate) + let store = makeStore(clock: clock) + let entry = try makePost(author: Curve25519.Signing.PrivateKey(), createdAt: baseMs) + store.ingest(entry.wire, packet: entry.packet) + + let endorsement = try makeEndorsement( + of: entry.post, + endorser: Curve25519.Signing.PrivateKey(), + endorsedAt: baseMs + 1, + postAuthorKey: Curve25519.Signing.PrivateKey().publicKey.rawRepresentation + ) + #expect(store.ingest(endorsement.wire, packet: endorsement.packet) == .rejected) + } + + @Test func endorsementFromTheFutureIsRejected() throws { + let clock = MutableClock(now: baseDate) + let store = makeStore(clock: clock) + let entry = try makePost(author: Curve25519.Signing.PrivateKey(), createdAt: baseMs) + store.ingest(entry.wire, packet: entry.packet) + + let tooEarly = baseMs + BoardStore.Limits.clockSkewMs + 1 + let endorsement = try makeEndorsement(of: entry.post, endorser: Curve25519.Signing.PrivateKey(), endorsedAt: tooEarly) + #expect(store.ingest(endorsement.wire, packet: endorsement.packet) == .rejected) + } + + @Test func endorsementArrivingBeforePostCountsOnceThePostLands() throws { + let clock = MutableClock(now: baseDate) + let store = makeStore(clock: clock) + let entry = try makePost(author: Curve25519.Signing.PrivateKey(), createdAt: baseMs) + let endorser = Curve25519.Signing.PrivateKey() + let endorsement = try makeEndorsement(of: entry.post, endorser: endorser, endorsedAt: baseMs + 1) + + #expect(store.ingest(endorsement.wire, packet: endorsement.packet) == .accepted) + #expect(store.endorserKeys(forPostID: entry.post.postID).isEmpty) + + #expect(store.ingest(entry.wire, packet: entry.packet) == .accepted) + #expect(store.endorserKeys(forPostID: entry.post.postID) == [endorser.publicKey.rawRepresentation]) + } + + @Test func orphanEndorsementForADifferentAuthorIsDroppedWhenThePostLands() throws { + let clock = MutableClock(now: baseDate) + let store = makeStore(clock: clock) + let entry = try makePost(author: Curve25519.Signing.PrivateKey(), createdAt: baseMs) + let misattributed = try makeEndorsement( + of: entry.post, + endorser: Curve25519.Signing.PrivateKey(), + endorsedAt: baseMs + 1, + postAuthorKey: Curve25519.Signing.PrivateKey().publicKey.rawRepresentation + ) + #expect(store.ingest(misattributed.wire, packet: misattributed.packet) == .accepted) + + store.ingest(entry.wire, packet: entry.packet) + #expect(store.endorserKeys(forPostID: entry.post.postID).isEmpty) + #expect(store.syncCandidates().count == 1) + } + + @Test func tombstoneDropsThePostsEndorsements() throws { + let clock = MutableClock(now: baseDate) + let store = makeStore(clock: clock) + let author = Curve25519.Signing.PrivateKey() + let entry = try makePost(author: author, createdAt: baseMs) + store.ingest(entry.wire, packet: entry.packet) + let endorsement = try makeEndorsement(of: entry.post, endorser: Curve25519.Signing.PrivateKey(), endorsedAt: baseMs + 1) + store.ingest(endorsement.wire, packet: endorsement.packet) + + let tombstone = try makeTombstone(for: entry.post, author: author, deletedAt: baseMs + 2) + store.ingest(tombstone.wire, packet: tombstone.packet) + + #expect(store.endorserKeys(forPostID: entry.post.postID).isEmpty) + // Only the tombstone keeps syncing; a late copy of the endorsement is refused. + #expect(store.syncCandidates().count == 1) + #expect(store.ingest(endorsement.wire, packet: endorsement.packet) == .rejected) + } + + @Test func endorsementsExpireWithTheirPost() throws { + let clock = MutableClock(now: baseDate) + let store = makeStore(clock: clock) + let entry = try makePost(author: Curve25519.Signing.PrivateKey(), createdAt: baseMs, lifetimeMs: 60 * 60 * 1000) + store.ingest(entry.wire, packet: entry.packet) + let endorsement = try makeEndorsement(of: entry.post, endorser: Curve25519.Signing.PrivateKey(), endorsedAt: baseMs + 1) + store.ingest(endorsement.wire, packet: endorsement.packet) + + clock.now = baseDate.addingTimeInterval(2 * 60 * 60) + #expect(store.syncCandidates().isEmpty) + } + + @Test func perPostCapKeepsTheFirstEndorsers() throws { + let clock = MutableClock(now: baseDate) + let store = makeStore(clock: clock) + let entry = try makePost(author: Curve25519.Signing.PrivateKey(), createdAt: baseMs) + store.ingest(entry.wire, packet: entry.packet) + + var firstKeys: [Data] = [] + for index in 0.. Date: Mon, 12 Oct 2026 08:48:52 +0530 Subject: [PATCH 3/8] expose the signing keys a board confirmation can come from Verified peers, plus peers vouched for by someone we verified, mapped through the Noise-authenticated signing-key bindings only. An announce that merely claims a trusted peer's key does not qualify. Same validity rules as the vouch trust level: unverifying the voucher or letting the vouch expire removes the vouchee's key. --- .../Identity/SecureIdentityStateManager.swift | 22 ++++++++ bitchatTests/Mocks/MockIdentityManager.swift | 4 ++ ...SecureIdentityStateManagerVouchTests.swift | 53 +++++++++++++++++++ .../Services/UnifiedPeerServiceTests.swift | 4 ++ 4 files changed, 83 insertions(+) diff --git a/bitchat/Identity/SecureIdentityStateManager.swift b/bitchat/Identity/SecureIdentityStateManager.swift index 4204e940..cac81779 100644 --- a/bitchat/Identity/SecureIdentityStateManager.swift +++ b/bitchat/Identity/SecureIdentityStateManager.swift @@ -140,6 +140,7 @@ protocol SecureIdentityStateManagerProtocol { func markVouchBatchSent(to fingerprint: String, at date: Date) func signingPublicKey(forFingerprint fingerprint: String) -> Data? func mostRecentlyVerifiedFingerprints(limit: Int, excluding fingerprint: String) -> [String] + func trustedSigningKeys() -> Set // MARK: Noise-authenticated announcement identity func bindAuthenticatedSigningPublicKey(_ signingPublicKey: Data, fingerprint: String) @@ -843,6 +844,27 @@ final class SecureIdentityStateManager: SecureIdentityStateManagerProtocol { queue.sync { cache.cryptographicIdentities[fingerprint]?.signingPublicKey } } + /// Ed25519 keys of peers whose word counts for board confirmations: ones + /// I verified, plus ones vouched for by someone I verified. Only + /// Noise-authenticated bindings qualify, so an announce that merely + /// claims a trusted peer's key cannot borrow its standing. + func trustedSigningKeys() -> Set { + trustedSigningKeys(now: Date()) + } + + func trustedSigningKeys(now: Date) -> Set { + queue.sync { + let bindings = cache.authenticatedSigningKeysByFingerprint ?? [:] + var keys = Set() + for (fingerprint, key) in bindings + where cache.verifiedFingerprints.contains(fingerprint) + || !validVouchersLocked(for: fingerprint, now: now).isEmpty { + keys.insert(key) + } + return keys + } + } + /// Verified fingerprints ordered most recently verified first (entries /// without a recorded verification time sort last), excluding the given /// fingerprint. Feeds the outgoing vouch batch. diff --git a/bitchatTests/Mocks/MockIdentityManager.swift b/bitchatTests/Mocks/MockIdentityManager.swift index 930d57ff..7af47fcb 100644 --- a/bitchatTests/Mocks/MockIdentityManager.swift +++ b/bitchatTests/Mocks/MockIdentityManager.swift @@ -160,4 +160,8 @@ final class MockIdentityManager: SecureIdentityStateManagerProtocol { func mostRecentlyVerifiedFingerprints(limit: Int, excluding fingerprint: String) -> [String] { [] } + + func trustedSigningKeys() -> Set { + [] + } } diff --git a/bitchatTests/Services/SecureIdentityStateManagerVouchTests.swift b/bitchatTests/Services/SecureIdentityStateManagerVouchTests.swift index ae71c91a..cc624c3b 100644 --- a/bitchatTests/Services/SecureIdentityStateManagerVouchTests.swift +++ b/bitchatTests/Services/SecureIdentityStateManagerVouchTests.swift @@ -317,6 +317,59 @@ struct SecureIdentityStateManagerVouchTests { #expect(reloaded.validVouchers(for: vouchee).count == 1) } + // MARK: - Trusted signing keys (board confirmations) + + @Test + func trustedSigningKeys_includesVerifiedAndVouchedAuthenticatedKeys() { + let manager = makeManager() + let stranger = String(repeating: "0c", count: 32) + let voucherKey = Data(repeating: 0xA1, count: 32) + let voucheeKey = Data(repeating: 0xB1, count: 32) + let strangerKey = Data(repeating: 0xC1, count: 32) + manager.bindAuthenticatedSigningPublicKey(voucherKey, fingerprint: voucher) + manager.bindAuthenticatedSigningPublicKey(voucheeKey, fingerprint: vouchee) + manager.bindAuthenticatedSigningPublicKey(strangerKey, fingerprint: stranger) + #expect(manager.trustedSigningKeys().isEmpty) + + manager.setVerified(fingerprint: voucher, verified: true) + #expect(manager.trustedSigningKeys() == [voucherKey]) + + manager.recordVouch(voucheeFingerprint: vouchee, voucherFingerprint: voucher, timestamp: Date()) + #expect(manager.trustedSigningKeys() == [voucherKey, voucheeKey]) + } + + @Test + func trustedSigningKeys_ignoresVerifiedPeerWithoutAuthenticatedBinding() { + let manager = makeManager() + manager.setVerified(fingerprint: voucher, verified: true) + #expect(manager.trustedSigningKeys().isEmpty) + } + + @Test + func trustedSigningKeys_dropsVoucheeWhenVoucherIsUnverified() { + let manager = makeManager() + let voucheeKey = Data(repeating: 0xB2, count: 32) + manager.bindAuthenticatedSigningPublicKey(voucheeKey, fingerprint: vouchee) + manager.setVerified(fingerprint: voucher, verified: true) + manager.recordVouch(voucheeFingerprint: vouchee, voucherFingerprint: voucher, timestamp: Date()) + #expect(manager.trustedSigningKeys().contains(voucheeKey)) + + manager.setVerified(fingerprint: voucher, verified: false) + #expect(!manager.trustedSigningKeys().contains(voucheeKey)) + } + + @Test + func trustedSigningKeys_dropsExpiredVouch() { + let manager = makeManager() + let voucheeKey = Data(repeating: 0xB3, count: 32) + manager.bindAuthenticatedSigningPublicKey(voucheeKey, fingerprint: vouchee) + manager.setVerified(fingerprint: voucher, verified: true) + manager.recordVouch(voucheeFingerprint: vouchee, voucherFingerprint: voucher, timestamp: Date()) + + let later = Date().addingTimeInterval(VouchAttestation.maxAge + 60) + #expect(!manager.trustedSigningKeys(now: later).contains(voucheeKey)) + } + // MARK: - Helpers private func waitUntil( diff --git a/bitchatTests/Services/UnifiedPeerServiceTests.swift b/bitchatTests/Services/UnifiedPeerServiceTests.swift index 35194698..c17f554e 100644 --- a/bitchatTests/Services/UnifiedPeerServiceTests.swift +++ b/bitchatTests/Services/UnifiedPeerServiceTests.swift @@ -346,6 +346,10 @@ private final class TestIdentityManager: SecureIdentityStateManagerProtocol { nil } + func trustedSigningKeys() -> Set { + [] + } + func mostRecentlyVerifiedFingerprints(limit: Int, excluding fingerprint: String) -> [String] { [] } From cbddc6f3d66c81e3229cabffb42b8e0f7d230cab Mon Sep 17 00:00:00 2001 From: Taksh Date: Mon, 12 Oct 2026 08:51:14 +0530 Subject: [PATCH 4/8] let people endorse urgent board posts and count trusted confirmations BoardManager signs and broadcasts an endorsement for someone else's urgent post, and reports how many endorsers are keys we trust. Strangers' endorsements are still stored and relayed, they just never count here, and an author can't confirm their own post even when we trust them. Endorsing is offered on urgent posts only. A single unverified voice is the risk there, and calm notices need no quorum. --- bitchat/App/AppChromeModel.swift | 8 +- bitchat/Services/BLE/BLEService.swift | 4 +- bitchat/Services/Board/BoardManager.swift | 65 +++++- .../Services/MeshTransportCapabilities.swift | 4 +- bitchat/Sync/GossipSyncManager.swift | 2 +- bitchatTests/Services/BoardManagerTests.swift | 212 ++++++++++++++++++ 6 files changed, 287 insertions(+), 8 deletions(-) create mode 100644 bitchatTests/Services/BoardManagerTests.swift diff --git a/bitchat/App/AppChromeModel.swift b/bitchat/App/AppChromeModel.swift index 51cadfb0..8533965f 100644 --- a/bitchat/App/AppChromeModel.swift +++ b/bitchat/App/AppChromeModel.swift @@ -36,7 +36,13 @@ final class AppChromeModel: ObservableObject { private var prepareForPanic: (@MainActor () -> Void)? /// Bulletin-board coordinator, created on first use of the board sheet. - private(set) lazy var boardManager = BoardManager(transport: chatViewModel.meshService) + private(set) lazy var boardManager: BoardManager = { + let identityManager = chatViewModel.identityManager + return BoardManager( + transport: chatViewModel.meshService, + trustedSigningKeys: { identityManager.trustedSigningKeys() } + ) + }() init( chatViewModel: ChatViewModel, diff --git a/bitchat/Services/BLE/BLEService.swift b/bitchat/Services/BLE/BLEService.swift index edd630e9..fad8d93d 100644 --- a/bitchat/Services/BLE/BLEService.swift +++ b/bitchat/Services/BLE/BLEService.swift @@ -6564,7 +6564,7 @@ extension BLEService { // MARK: - Board (geohash bulletin board) - /// Validates and stores an incoming board post or tombstone. Returns + /// Validates and stores an incoming board post, tombstone, or endorsement. Returns /// whether the packet is worth relaying onward. private func handleBoardPost(_ packet: BitchatPacket, from peerID: PeerID) -> Bool { guard let wire = BoardWire.decode(from: packet.payload) else { @@ -6588,7 +6588,7 @@ extension BLEService { } } - /// Broadcasts a pre-signed board payload (post or tombstone) built by the + /// Broadcasts a pre-signed board payload (post, tombstone, or endorsement) built by the /// board manager, and ingests it locally so it shows up on our own board /// and joins gossip sync immediately. func sendBoardPayload(_ payload: Data) { diff --git a/bitchat/Services/Board/BoardManager.swift b/bitchat/Services/Board/BoardManager.swift index 82f78a8f..5874b31e 100644 --- a/bitchat/Services/Board/BoardManager.swift +++ b/bitchat/Services/Board/BoardManager.swift @@ -17,8 +17,13 @@ import Foundation final class BoardManager: ObservableObject { /// Live posts across all boards, newest state from the store. @Published private(set) var posts: [BoardPostPacket] = [] + /// Endorser signing keys per postID, newest state from the store. + @Published private(set) var endorsements: [Data: [Data]] = [:] private let transport: Transport + /// Keys whose endorsements count as confirmation (verified or vouched + /// peers). Read per call so a fresh verification shows up immediately. + private let trustedSigningKeys: () -> Set /// Board broadcast rides the mesh only; absent on other transports. private var boardTransport: MeshBoardBroadcasting? { transport as? MeshBoardBroadcasting } /// Publishes a bridged kind-1 note (expiring with the board post via @@ -31,22 +36,31 @@ final class BoardManager: ObservableObject { /// after a relaunch a delete still tombstones the board copy, but the /// Nostr copy is left to expire with relay retention. private var bridgedEventIDs: [Data: String] = [:] - private var cancellable: AnyCancellable? + private var cancellables = Set() init( transport: Transport, store: BoardStore = .shared, + trustedSigningKeys: (() -> Set)? = nil, publishToNostr: ((String, String, String, UInt64, Bool) -> String?)? = nil, deleteFromNostr: ((String, String) -> Void)? = nil ) { self.transport = transport + self.trustedSigningKeys = trustedSigningKeys ?? { [] } self.publishToNostr = publishToNostr ?? Self.livePublishToNostr self.deleteFromNostr = deleteFromNostr ?? Self.liveDeleteFromNostr - cancellable = store.$postsSnapshot + store.$postsSnapshot .receive(on: DispatchQueue.main) .sink { [weak self] snapshot in self?.posts = snapshot } + .store(in: &cancellables) + store.$endorsementsSnapshot + .receive(on: DispatchQueue.main) + .sink { [weak self] snapshot in + self?.endorsements = snapshot + } + .store(in: &cancellables) } /// Posts for one board context, urgent first, then newest first. @@ -64,6 +78,53 @@ final class BoardManager: ObservableObject { return !key.isEmpty && key == post.authorSigningKey } + /// How many people we trust have endorsed the post. Endorsements from + /// strangers are stored and relayed but never counted here. + func confirmationCount(for post: BoardPostPacket) -> Int { + guard let endorsers = endorsements[post.postID], !endorsers.isEmpty else { return 0 } + let trusted = trustedSigningKeys() + return Set(endorsers).filter { trusted.contains($0) && $0 != post.authorSigningKey }.count + } + + func hasEndorsed(_ post: BoardPostPacket) -> Bool { + let key = transport.noiseSigningPublicKeyData() + return !key.isEmpty && endorsements[post.postID]?.contains(key) == true + } + + /// Endorsing is offered on urgent posts only: that is where a single + /// unverified voice is the risk, and calm notices need no quorum. + func canEndorse(_ post: BoardPostPacket) -> Bool { + post.isUrgent && !isOwnPost(post) && !hasEndorsed(post) + } + + /// Signs and broadcasts our endorsement of someone else's post. + @discardableResult + func endorsePost(_ post: BoardPostPacket) -> Bool { + guard canEndorse(post) else { return false } + let signingKey = transport.noiseSigningPublicKeyData() + guard signingKey.count == BoardWireConstants.signingKeyLength else { return false } + let endorsedAt = UInt64(Date().timeIntervalSince1970 * 1000) + let signingBytes = BoardEndorsementPacket.signingBytes( + postID: post.postID, + postAuthorSigningKey: post.authorSigningKey, + endorserSigningKey: signingKey, + endorsedAt: endorsedAt + ) + guard let signature = transport.noiseSignData(signingBytes) else { + SecureLogger.error("Board: failed to sign endorsement", category: .session) + return false + } + let endorsement = BoardEndorsementPacket( + postID: post.postID, + postAuthorSigningKey: post.authorSigningKey, + endorserSigningKey: signingKey, + endorsedAt: endorsedAt, + signature: signature + ) + boardTransport?.sendBoardPayload(BoardWire.endorsement(endorsement).encode()) + return true + } + /// Creates, signs, and broadcasts a board post. Returns false when the /// content is empty/oversized or signing fails. @discardableResult diff --git a/bitchat/Services/MeshTransportCapabilities.swift b/bitchat/Services/MeshTransportCapabilities.swift index fd2203ea..c679053f 100644 --- a/bitchat/Services/MeshTransportCapabilities.swift +++ b/bitchat/Services/MeshTransportCapabilities.swift @@ -81,8 +81,8 @@ protocol MeshGroupMessaging: AnyObject { func broadcastGroupMessage(_ envelope: Data) } -/// Bulletin board: broadcast a pre-signed board payload (post or -/// tombstone) so it spreads over relay and gossip sync. +/// Bulletin board: broadcast a pre-signed board payload (post, tombstone, +/// or endorsement) so it spreads over relay and gossip sync. protocol MeshBoardBroadcasting: AnyObject { func sendBoardPayload(_ payload: Data) } diff --git a/bitchat/Sync/GossipSyncManager.swift b/bitchat/Sync/GossipSyncManager.swift index c54140f0..3d1e996e 100644 --- a/bitchat/Sync/GossipSyncManager.swift +++ b/bitchat/Sync/GossipSyncManager.swift @@ -533,7 +533,7 @@ final class GossipSyncManager { } } if requestedTypes.contains(.boardPost) { - // The board store already filters to live posts and tombstones; + // The board store already filters to live posts, tombstones, and endorsements; // no freshness window applies (posts sync until their own expiry). let boardPackets = boardPacketsProvider?() ?? [] for pkt in boardPackets { diff --git a/bitchatTests/Services/BoardManagerTests.swift b/bitchatTests/Services/BoardManagerTests.swift new file mode 100644 index 00000000..39363ea7 --- /dev/null +++ b/bitchatTests/Services/BoardManagerTests.swift @@ -0,0 +1,212 @@ +// +// BoardManagerTests.swift +// bitchatTests +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import BitFoundation +import CryptoKit +import Foundation +import Testing +@testable import bitchat + +@MainActor +struct BoardManagerTests { + + private func makeManager( + transport: MockTransport = MockTransport(), + store: BoardStore = BoardStore(persistsToDisk: false), + trusted: Set = [] + ) -> BoardManager { + BoardManager( + transport: transport, + store: store, + trustedSigningKeys: { trusted }, + publishToNostr: { _, _, _, _, _ in nil }, + deleteFromNostr: { _, _ in } + ) + } + + private func makePost( + author: Curve25519.Signing.PrivateKey = Curve25519.Signing.PrivateKey(), + urgent: Bool = true + ) throws -> BoardPostPacket { + let postID = Data((0..<16).map { _ in UInt8.random(in: 0...255) }) + let key = author.publicKey.rawRepresentation + let createdAt = UInt64(Date().timeIntervalSince1970 * 1000) + let expiresAt = createdAt + 60 * 60 * 1000 + let flags: UInt8 = urgent ? BoardPostPacket.urgentFlag : 0 + let signingBytes = BoardPostPacket.signingBytes( + postID: postID, + geohash: "", + content: "bridge is out on 5th", + authorSigningKey: key, + authorNickname: "scout", + createdAt: createdAt, + expiresAt: expiresAt, + flags: flags + ) + return BoardPostPacket( + postID: postID, + geohash: "", + content: "bridge is out on 5th", + authorSigningKey: key, + authorNickname: "scout", + createdAt: createdAt, + expiresAt: expiresAt, + flags: flags, + signature: try author.signature(for: signingBytes) + ) + } + + private func makeEndorsement(of post: BoardPostPacket, by endorser: Curve25519.Signing.PrivateKey) throws -> BoardWire { + let endorserKey = endorser.publicKey.rawRepresentation + let endorsedAt = UInt64(Date().timeIntervalSince1970 * 1000) + return .endorsement(BoardEndorsementPacket( + postID: post.postID, + postAuthorSigningKey: post.authorSigningKey, + endorserSigningKey: endorserKey, + endorsedAt: endorsedAt, + signature: try endorser.signature(for: BoardEndorsementPacket.signingBytes( + postID: post.postID, + postAuthorSigningKey: post.authorSigningKey, + endorserSigningKey: endorserKey, + endorsedAt: endorsedAt + )) + )) + } + + private func packet(for wire: BoardWire) -> BitchatPacket { + BitchatPacket( + type: MessageType.boardPost.rawValue, + senderID: Data((0..<8).map { _ in UInt8.random(in: 0...255) }), + recipientID: nil, + timestamp: UInt64(Date().timeIntervalSince1970 * 1000), + payload: wire.encode(), + signature: nil, + ttl: 7 + ) + } + + /// The store publishes snapshots on the main queue; let them land. + private func settle(_ condition: () -> Bool) async { + for _ in 0..<100 where !condition() { + try? await Task.sleep(nanoseconds: 5_000_000) + } + } + + // MARK: - Endorsing + + @Test func endorsingAnUrgentPostSendsAVerifiableEndorsement() throws { + let transport = MockTransport() + let manager = makeManager(transport: transport) + let post = try makePost() + + #expect(manager.endorsePost(post)) + let payload = try #require(transport.sentBoardPayloads.last) + let wire = try #require(BoardWire.decode(from: payload)) + guard case .endorsement(let endorsement) = wire else { + Issue.record("expected an endorsement payload") + return + } + #expect(wire.verifySignature()) + #expect(endorsement.postID == post.postID) + #expect(endorsement.postAuthorSigningKey == post.authorSigningKey) + #expect(endorsement.endorserSigningKey == transport.noiseSigningPublicKeyData()) + } + + @Test func calmPostsAreNotOfferedForEndorsement() throws { + let transport = MockTransport() + let manager = makeManager(transport: transport) + let post = try makePost(urgent: false) + + #expect(!manager.canEndorse(post)) + #expect(!manager.endorsePost(post)) + #expect(transport.sentBoardPayloads.isEmpty) + } + + @Test func ownPostCannotBeEndorsed() throws { + let transport = MockTransport() + let manager = makeManager(transport: transport) + let ownKey = transport.noiseSigningPublicKeyData() + let signingBytes = BoardPostPacket.signingBytes( + postID: Data(repeating: 0x01, count: 16), + geohash: "", + content: "mine", + authorSigningKey: ownKey, + authorNickname: "me", + createdAt: 1, + expiresAt: 2, + flags: BoardPostPacket.urgentFlag + ) + let own = BoardPostPacket( + postID: Data(repeating: 0x01, count: 16), + geohash: "", + content: "mine", + authorSigningKey: ownKey, + authorNickname: "me", + createdAt: 1, + expiresAt: 2, + flags: BoardPostPacket.urgentFlag, + signature: try #require(transport.noiseSignData(signingBytes)) + ) + + #expect(!manager.canEndorse(own)) + #expect(!manager.endorsePost(own)) + #expect(transport.sentBoardPayloads.isEmpty) + } + + @Test func alreadyEndorsedPostIsNotOfferedAgain() async throws { + let transport = MockTransport() + let store = BoardStore(persistsToDisk: false) + let manager = makeManager(transport: transport, store: store) + let post = try makePost() + store.ingest(.post(post), packet: packet(for: .post(post))) + + #expect(manager.endorsePost(post)) + let payload = try #require(transport.sentBoardPayloads.last) + let sent = try #require(BoardWire.decode(from: payload)) + store.ingest(sent, packet: packet(for: sent)) + await settle { manager.hasEndorsed(post) } + + #expect(manager.hasEndorsed(post)) + #expect(!manager.canEndorse(post)) + } + + // MARK: - Confirmation counting + + @Test func onlyTrustedEndorsersCountAsConfirmation() async throws { + let store = BoardStore(persistsToDisk: false) + let friend = Curve25519.Signing.PrivateKey() + let stranger = Curve25519.Signing.PrivateKey() + let manager = makeManager(store: store, trusted: [friend.publicKey.rawRepresentation]) + let post = try makePost() + store.ingest(.post(post), packet: packet(for: .post(post))) + + for endorser in [friend, stranger] { + let wire = try makeEndorsement(of: post, by: endorser) + store.ingest(wire, packet: packet(for: wire)) + } + await settle { manager.endorsements[post.postID]?.count == 2 } + + #expect(manager.endorsements[post.postID]?.count == 2) + #expect(manager.confirmationCount(for: post) == 1) + } + + @Test func trustingTheAuthorDoesNotLetThemConfirmThemselves() async throws { + let store = BoardStore(persistsToDisk: false) + let author = Curve25519.Signing.PrivateKey() + let manager = makeManager(store: store, trusted: [author.publicKey.rawRepresentation]) + let post = try makePost(author: author) + store.ingest(.post(post), packet: packet(for: .post(post))) + + #expect(manager.confirmationCount(for: post) == 0) + } + + @Test func postWithoutEndorsementsHasNoConfirmation() throws { + let manager = makeManager(trusted: [Curve25519.Signing.PrivateKey().publicKey.rawRepresentation]) + #expect(manager.confirmationCount(for: try makePost()) == 0) + } +} From 5eccfaba3ec3f0301805224d723436527a5523ff Mon Sep 17 00:00:00 2001 From: Taksh Date: Mon, 12 Oct 2026 08:54:06 +0530 Subject: [PATCH 5/8] tell the chat when someone you trust confirms an urgent notice The first trusted endorsement of a recent urgent pin adds one local line in the pin's scope, next to the existing urgent alert. Later endorsements only move the count in the notices sheet, and stale, calm, own, or unknown posts stay quiet. The count is phrased "(N)" to avoid plural forms across the catalog. Non-English strings are marked needs_review. --- bitchat/App/AppRuntime.swift | 11 ++ bitchat/Localizable.xcstrings | 186 ++++++++++++++++++ bitchat/Services/Board/BoardAlertsModel.swift | 45 +++++ bitchat/Services/Board/BoardManager.swift | 8 +- bitchat/Services/Board/BoardStore.swift | 9 + .../Services/BoardAlertsModelTests.swift | 99 +++++++++- 6 files changed, 355 insertions(+), 3 deletions(-) diff --git a/bitchat/App/AppRuntime.swift b/bitchat/App/AppRuntime.swift index 3d5bc5bc..95136fc8 100644 --- a/bitchat/App/AppRuntime.swift +++ b/bitchat/App/AppRuntime.swift @@ -102,8 +102,10 @@ final class AppRuntime: ObservableObject { onPanicWipe: { sharedContentImportModel.discardAll() } ) let chatViewModel = self.chatViewModel + let identityManager = chatViewModel.identityManager self.boardAlertsModel = BoardAlertsModel( arrivals: BoardStore.shared.postArrivals.eraseToAnyPublisher(), + endorsements: BoardStore.shared.endorsementArrivals.eraseToAnyPublisher(), wipes: BoardStore.shared.didWipe.eraseToAnyPublisher(), dependencies: BoardAlertsModel.Dependencies( isOwnPost: { post in @@ -116,6 +118,15 @@ final class AppRuntime: ObservableObject { } else { chatViewModel.addGeohashSystemMessage(content, geohash: geohash) } + }, + confirmation: { endorsement in + guard let post = BoardStore.shared.post(withID: endorsement.postID) else { return nil } + let count = BoardManager.trustedConfirmationCount( + endorsers: BoardStore.shared.endorserKeys(forPostID: endorsement.postID), + trusted: identityManager.trustedSigningKeys(), + author: post.authorSigningKey + ) + return (post, count) } ) ) diff --git a/bitchat/Localizable.xcstrings b/bitchat/Localizable.xcstrings index e498a20e..ebee7dc4 100644 --- a/bitchat/Localizable.xcstrings +++ b/bitchat/Localizable.xcstrings @@ -81307,6 +81307,192 @@ } } }, + "notices.alert.urgent_confirmed" : { + "comment" : "Local chat line when people the user verified or vouched for endorse an urgent notice. Placeholders: author, number of trusted confirmations, notice text", + "extractionState" : "manual", + "localizations" : { + "ar" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 إعلان عاجل من @%1$@ أكّده أشخاص تثق بهم (%2$lld): %3$@" + } + }, + "bn" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 @%1$@-এর জরুরি নোটিশ, আপনার বিশ্বস্ত লোকেরা নিশ্চিত করেছে (%2$lld): %3$@" + } + }, + "de" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 dringender hinweis von @%1$@, bestätigt von leuten, denen du vertraust (%2$lld): %3$@" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "📌 urgent notice from @%1$@ confirmed by people you trust (%2$lld): %3$@" + } + }, + "es" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 aviso urgente de @%1$@ confirmado por personas de confianza (%2$lld): %3$@" + } + }, + "fa" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 اعلان فوری از @%1$@ که افراد مورد اعتمادت تأیید کرده‌اند (%2$lld): %3$@" + } + }, + "fil" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 urgent na paunawa mula kay @%1$@, kinumpirma ng mga taong pinagkakatiwalaan mo (%2$lld): %3$@" + } + }, + "fr" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 avis urgent de @%1$@ confirmé par des personnes de confiance (%2$lld) : %3$@" + } + }, + "he" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 הודעה דחופה מ-@%1$@ אושרה על ידי אנשים שאתה סומך עליהם (%2$lld): %3$@" + } + }, + "hi" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 @%1$@ की तत्काल सूचना, आपके भरोसेमंद लोगों ने पुष्टि की (%2$lld): %3$@" + } + }, + "id" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 pemberitahuan mendesak dari @%1$@ dikonfirmasi oleh orang yang kamu percaya (%2$lld): %3$@" + } + }, + "it" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 avviso urgente da @%1$@ confermato da persone di cui ti fidi (%2$lld): %3$@" + } + }, + "ja" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 @%1$@ からの緊急のお知らせを信頼できる人が確認しました (%2$lld): %3$@" + } + }, + "ko" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 @%1$@ 님의 긴급 공지를 신뢰하는 사람들이 확인했습니다 (%2$lld): %3$@" + } + }, + "ms" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 notis segera daripada @%1$@ disahkan oleh orang yang anda percayai (%2$lld): %3$@" + } + }, + "ne" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 @%1$@ को जरुरी सूचना, तिमीले विश्वास गर्ने मानिसहरूले पुष्टि गरे (%2$lld): %3$@" + } + }, + "nl" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 dringende melding van @%1$@ bevestigd door mensen die je vertrouwt (%2$lld): %3$@" + } + }, + "pl" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 pilne ogłoszenie od @%1$@ potwierdzone przez zaufane osoby (%2$lld): %3$@" + } + }, + "pt" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 aviso urgente de @%1$@ confirmado por pessoas em quem confias (%2$lld): %3$@" + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 aviso urgente de @%1$@ confirmado por pessoas em quem você confia (%2$lld): %3$@" + } + }, + "ru" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 срочное объявление от @%1$@ подтвердили люди, которым ты доверяешь (%2$lld): %3$@" + } + }, + "sv" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 brådskande meddelande från @%1$@ bekräftat av personer du litar på (%2$lld): %3$@" + } + }, + "ta" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 @%1$@ இன் அவசர அறிவிப்பை நீங்கள் நம்பும் நபர்கள் உறுதிப்படுத்தினர் (%2$lld): %3$@" + } + }, + "th" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 ประกาศด่วนจาก @%1$@ ได้รับการยืนยันจากคนที่คุณไว้ใจ (%2$lld): %3$@" + } + }, + "tr" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 @%1$@ kişisinden acil duyuru, güvendiğin kişilerce doğrulandı (%2$lld): %3$@" + } + }, + "uk" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 термінове оголошення від @%1$@ підтвердили люди, яким ти довіряєш (%2$lld): %3$@" + } + }, + "ur" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 @%1$@ کا فوری نوٹس، جن لوگوں پر آپ بھروسہ کرتے ہیں انہوں نے تصدیق کی (%2$lld): %3$@" + } + }, + "vi" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 thông báo khẩn từ @%1$@ đã được những người bạn tin tưởng xác nhận (%2$lld): %3$@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 来自 @%1$@ 的紧急通知已获你信任的人确认 (%2$lld):%3$@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 來自 @%1$@ 的緊急通知已獲你信任的人確認 (%2$lld):%3$@" + } + } + } + }, "notices.alert.urgent_single" : { "comment" : "Local chat line when one urgent notice is pinned nearby", "extractionState" : "manual", diff --git a/bitchat/Services/Board/BoardAlertsModel.swift b/bitchat/Services/Board/BoardAlertsModel.swift index 35daedfe..7534988a 100644 --- a/bitchat/Services/Board/BoardAlertsModel.swift +++ b/bitchat/Services/Board/BoardAlertsModel.swift @@ -18,6 +18,8 @@ import Foundation /// arrive together. /// - Every other new pin just marks the header's pin icon until the notices /// sheet is opened. +/// - A recent urgent pin that someone we trust endorses gets one more line +/// saying so, the first time it happens. @MainActor final class BoardAlertsModel: ObservableObject { struct Dependencies { @@ -26,6 +28,9 @@ final class BoardAlertsModel: ObservableObject { /// Appends a local system line to a scope's chat timeline /// (geohash, or "" for mesh chat). var emitSystemLine: @MainActor (_ content: String, _ geohash: String) -> Void + /// The endorsed post and how many trusted people now confirm it, or + /// nil when the post is not known here. + var confirmation: @MainActor (BoardEndorsementPacket) -> (post: BoardPostPacket, trustedCount: Int)? = { _ in nil } var now: () -> Date = Date.init /// Schedules the collapsed flush of pending urgent alerts; tests /// inject a synchronous hook. @@ -51,10 +56,13 @@ final class BoardAlertsModel: ObservableObject { /// PostIDs already handled this session, so store eviction/re-sync churn /// can't re-alert. Bounded by session wire volume (32-byte strings). private var handledPostIDs = Set() + /// Urgent posts already announced as confirmed this session. + private var confirmedPostIDs = Set() private var pendingUrgent: [String: [BoardPostPacket]] = [:] private var flushScheduled = false private let dependencies: Dependencies private var cancellable: AnyCancellable? + private var endorsementCancellable: AnyCancellable? private var wipeCancellable: AnyCancellable? private enum Strings { @@ -73,10 +81,19 @@ final class BoardAlertsModel: ObservableObject { count ) } + + static func urgentConfirmed(author: String, count: Int, content: String) -> String { + String( + format: String(localized: "notices.alert.urgent_confirmed", defaultValue: "📌 urgent notice from @%1$@ confirmed by people you trust (%2$lld): %3$@", comment: "Local chat line when people the user verified or vouched for endorse an urgent notice. Placeholders: author, number of trusted confirmations, notice text"), + locale: .current, + author, count, content + ) + } } init( arrivals: AnyPublisher, + endorsements: AnyPublisher = Empty(completeImmediately: false).eraseToAnyPublisher(), wipes: AnyPublisher = Empty(completeImmediately: false).eraseToAnyPublisher(), dependencies: Dependencies ) { @@ -86,6 +103,11 @@ final class BoardAlertsModel: ObservableObject { .sink { [weak self] post in self?.handleArrival(post) } + endorsementCancellable = endorsements + .receive(on: DispatchQueue.main) + .sink { [weak self] endorsement in + self?.handleEndorsement(endorsement) + } wipeCancellable = wipes .receive(on: DispatchQueue.main) .sink { [weak self] in @@ -110,6 +132,7 @@ final class BoardAlertsModel: ObservableObject { func reset() { pendingUrgent.removeAll() handledPostIDs.removeAll() + confirmedPostIDs.removeAll() guard !unseenPostScopes.isEmpty else { return } unseenPostScopes.removeAll() } @@ -136,6 +159,28 @@ final class BoardAlertsModel: ObservableObject { } } + /// One line per urgent post, the first time a trusted endorsement lands + /// while the post is still recent. Later endorsements only move the + /// count shown in the notices sheet. + func handleEndorsement(_ endorsement: BoardEndorsementPacket) { + let postID = endorsement.postID.hexEncodedString() + guard !confirmedPostIDs.contains(postID), + let (post, trustedCount) = dependencies.confirmation(endorsement), + trustedCount > 0, + post.isUrgent, + !dependencies.isOwnPost(post) else { + return + } + let createdAt = Date(timeIntervalSince1970: TimeInterval(post.createdAt) / 1000) + guard dependencies.now().timeIntervalSince(createdAt) <= Self.inlineRecencyWindow else { return } + confirmedPostIDs.insert(postID) + let author = post.authorNickname.trimmedOrNilIfEmpty ?? "anon" + dependencies.emitSystemLine( + Strings.urgentConfirmed(author: author, count: trustedCount, content: Self.truncated(post.content)), + post.geohash + ) + } + private func flushPendingUrgent() { flushScheduled = false let pending = pendingUrgent diff --git a/bitchat/Services/Board/BoardManager.swift b/bitchat/Services/Board/BoardManager.swift index 5874b31e..f0e2efc9 100644 --- a/bitchat/Services/Board/BoardManager.swift +++ b/bitchat/Services/Board/BoardManager.swift @@ -82,8 +82,12 @@ final class BoardManager: ObservableObject { /// strangers are stored and relayed but never counted here. func confirmationCount(for post: BoardPostPacket) -> Int { guard let endorsers = endorsements[post.postID], !endorsers.isEmpty else { return 0 } - let trusted = trustedSigningKeys() - return Set(endorsers).filter { trusted.contains($0) && $0 != post.authorSigningKey }.count + return Self.trustedConfirmationCount(endorsers: endorsers, trusted: trustedSigningKeys(), author: post.authorSigningKey) + } + + /// Distinct trusted endorsers, never counting the author. + nonisolated static func trustedConfirmationCount(endorsers: [Data], trusted: Set, author: Data) -> Int { + Set(endorsers).filter { trusted.contains($0) && $0 != author }.count } func hasEndorsed(_ post: BoardPostPacket) -> Bool { diff --git a/bitchat/Services/Board/BoardStore.swift b/bitchat/Services/Board/BoardStore.swift index 37bbe5d7..7f03f27a 100644 --- a/bitchat/Services/Board/BoardStore.swift +++ b/bitchat/Services/Board/BoardStore.swift @@ -172,6 +172,15 @@ final class BoardStore { } } + /// The live post with this ID, if any. + func post(withID postID: Data) -> BoardPostPacket? { + let nowMs = currentMs() + return queue.sync { + pruneExpiredLocked(nowMs: nowMs) + return posts.first { $0.post.postID == postID }?.post + } + } + /// Endorser signing keys stored for one post, oldest endorsement first. func endorserKeys(forPostID postID: Data) -> [Data] { let nowMs = currentMs() diff --git a/bitchatTests/Services/BoardAlertsModelTests.swift b/bitchatTests/Services/BoardAlertsModelTests.swift index df891cea..865b02f6 100644 --- a/bitchatTests/Services/BoardAlertsModelTests.swift +++ b/bitchatTests/Services/BoardAlertsModelTests.swift @@ -30,7 +30,11 @@ struct BoardAlertsModelTests { } } - private func makeModel(harness: Harness, now: Date? = nil) -> BoardAlertsModel { + private func makeModel( + harness: Harness, + now: Date? = nil, + confirmation: @escaping @MainActor (BoardEndorsementPacket) -> (post: BoardPostPacket, trustedCount: Int)? = { _ in nil } + ) -> BoardAlertsModel { let fixedNow = now ?? baseDate return BoardAlertsModel( arrivals: Empty(completeImmediately: false).eraseToAnyPublisher(), @@ -39,6 +43,7 @@ struct BoardAlertsModelTests { emitSystemLine: { content, geohash in harness.lines.append((content, geohash)) }, + confirmation: confirmation, now: { fixedNow }, scheduleFlush: { flush in harness.pendingFlushes.append(flush) @@ -212,4 +217,96 @@ struct BoardAlertsModelTests { #expect(harness.lines[0].content.count < 200) #expect(harness.lines[0].content.contains("…")) } + + // MARK: - Trusted confirmations + + private func endorsement(of post: BoardPostPacket) -> BoardEndorsementPacket { + BoardEndorsementPacket( + postID: post.postID, + postAuthorSigningKey: post.authorSigningKey, + endorserSigningKey: Data(repeating: 9, count: 32), + endorsedAt: baseMs + 1, + signature: Data(repeating: 2, count: 64) + ) + } + + @Test + func trustedEndorsementOfRecentUrgentPost_emitsOneConfirmedLine() { + let harness = Harness() + let post = makePost(content: "road closed", geohash: "9q8yy", urgent: true) + var count = 1 + let model = makeModel(harness: harness) { _ in (post, count) } + + model.handleEndorsement(endorsement(of: post)) + count = 2 + model.handleEndorsement(endorsement(of: post)) + + #expect(harness.lines.count == 1) + #expect(harness.lines[0].geohash == "9q8yy") + #expect(harness.lines[0].content.contains("road closed")) + #expect(harness.lines[0].content.contains("@alice")) + #expect(harness.lines[0].content.contains("1")) + } + + @Test + func untrustedEndorsement_staysSilent() { + let harness = Harness() + let post = makePost(urgent: true) + let model = makeModel(harness: harness) { _ in (post, 0) } + + model.handleEndorsement(endorsement(of: post)) + #expect(harness.lines.isEmpty) + } + + @Test + func endorsementOfCalmPost_staysSilent() { + let harness = Harness() + let post = makePost(urgent: false) + let model = makeModel(harness: harness) { _ in (post, 3) } + + model.handleEndorsement(endorsement(of: post)) + #expect(harness.lines.isEmpty) + } + + @Test + func endorsementOfOwnPost_staysSilent() { + let harness = Harness() + let post = makePost(urgent: true, authorKey: ownKey) + let model = makeModel(harness: harness) { _ in (post, 2) } + + model.handleEndorsement(endorsement(of: post)) + #expect(harness.lines.isEmpty) + } + + @Test + func endorsementOfStaleUrgentPost_staysSilent() { + let harness = Harness() + let post = makePost(createdAt: baseMs, urgent: true) + let later = baseDate.addingTimeInterval(BoardAlertsModel.inlineRecencyWindow + 60) + let model = makeModel(harness: harness, now: later) { _ in (post, 2) } + + model.handleEndorsement(endorsement(of: post)) + #expect(harness.lines.isEmpty) + } + + @Test + func endorsementOfUnknownPost_staysSilent() { + let harness = Harness() + let model = makeModel(harness: harness) + + model.handleEndorsement(endorsement(of: makePost(urgent: true))) + #expect(harness.lines.isEmpty) + } + + @Test + func reset_allowsConfirmationAgainAfterWipe() { + let harness = Harness() + let post = makePost(urgent: true) + let model = makeModel(harness: harness) { _ in (post, 1) } + + model.handleEndorsement(endorsement(of: post)) + model.reset() + model.handleEndorsement(endorsement(of: post)) + #expect(harness.lines.count == 2) + } } From 14f5e5d732b31d4bda11bdd515162153ff69363a Mon Sep 17 00:00:00 2001 From: Taksh Date: Mon, 12 Oct 2026 08:56:01 +0530 Subject: [PATCH 6/8] add confirm and a trusted-confirmation badge to urgent notice rows Urgent board posts from someone else get a shield button, a leading swipe action, and an accessibility action to endorse them. Once people we trust have endorsed a post, the row shows "confirmed (N)" next to the urgent badge, and VoiceOver reads it too. NoticesList now observes the board so the badge updates as endorsements sync in. Non-English strings are marked needs_review. --- bitchat/Localizable.xcstrings | 372 ++++++++++++++++++ bitchat/Views/NoticesView.swift | 69 +++- bitchatTests/Services/BoardManagerTests.swift | 16 + 3 files changed, 453 insertions(+), 4 deletions(-) diff --git a/bitchat/Localizable.xcstrings b/bitchat/Localizable.xcstrings index ebee7dc4..8252b857 100644 --- a/bitchat/Localizable.xcstrings +++ b/bitchat/Localizable.xcstrings @@ -373,6 +373,192 @@ } } }, + "board.action.confirm" : { + "comment" : "Action to vouch for someone else's urgent board post; people who verified you see it as a confirmation", + "extractionState" : "manual", + "localizations" : { + "ar" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "تأكيد" + } + }, + "bn" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "নিশ্চিত করো" + } + }, + "de" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "bestätigen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "confirm" + } + }, + "es" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "confirmar" + } + }, + "fa" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "تأیید" + } + }, + "fil" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "kumpirmahin" + } + }, + "fr" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "confirmer" + } + }, + "he" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "אישור" + } + }, + "hi" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "पुष्टि करो" + } + }, + "id" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "konfirmasi" + } + }, + "it" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "conferma" + } + }, + "ja" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "確認する" + } + }, + "ko" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "확인" + } + }, + "ms" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "sahkan" + } + }, + "ne" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "पुष्टि गर्नुहोस्" + } + }, + "nl" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "bevestigen" + } + }, + "pl" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "potwierdź" + } + }, + "pt" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "confirmar" + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "confirmar" + } + }, + "ru" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "подтвердить" + } + }, + "sv" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "bekräfta" + } + }, + "ta" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "உறுதிப்படுத்து" + } + }, + "th" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "ยืนยัน" + } + }, + "tr" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "onayla" + } + }, + "uk" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "підтвердити" + } + }, + "ur" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "تصدیق کریں" + } + }, + "vi" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "xác nhận" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "确认" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "確認" + } + } + } + }, "board.action.delete" : { "comment" : "Delete action for own board posts", "extractionState" : "manual", @@ -1303,6 +1489,192 @@ } } }, + "board.confirmed_badge" : { + "comment" : "Badge on an urgent board post endorsed by people the user verified or vouched for; placeholder is how many", + "extractionState" : "manual", + "localizations" : { + "ar" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "مؤكَّد (%lld)" + } + }, + "bn" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "নিশ্চিত (%lld)" + } + }, + "de" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "bestätigt (%lld)" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "confirmed (%lld)" + } + }, + "es" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "confirmado (%lld)" + } + }, + "fa" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "تأییدشده (%lld)" + } + }, + "fil" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "kumpirmado (%lld)" + } + }, + "fr" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "confirmé (%lld)" + } + }, + "he" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "מאושר (%lld)" + } + }, + "hi" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "पुष्टि (%lld)" + } + }, + "id" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "terkonfirmasi (%lld)" + } + }, + "it" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "confermato (%lld)" + } + }, + "ja" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "確認済み (%lld)" + } + }, + "ko" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "확인됨 (%lld)" + } + }, + "ms" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "disahkan (%lld)" + } + }, + "ne" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "पुष्टि भयो (%lld)" + } + }, + "nl" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "bevestigd (%lld)" + } + }, + "pl" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "potwierdzone (%lld)" + } + }, + "pt" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "confirmado (%lld)" + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "confirmado (%lld)" + } + }, + "ru" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "подтверждено (%lld)" + } + }, + "sv" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "bekräftad (%lld)" + } + }, + "ta" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "உறுதிசெய்யப்பட்டது (%lld)" + } + }, + "th" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "ยืนยันแล้ว (%lld)" + } + }, + "tr" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "onaylandı (%lld)" + } + }, + "uk" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "підтверджено (%lld)" + } + }, + "ur" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "تصدیق شدہ (%lld)" + } + }, + "vi" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "đã xác nhận (%lld)" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "已确认 (%lld)" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "已確認 (%lld)" + } + } + } + }, "board.empty_subtitle" : { "comment" : "Subtitle shown when the board has no posts", "extractionState" : "manual", diff --git a/bitchat/Views/NoticesView.swift b/bitchat/Views/NoticesView.swift index 51edd184..fc47c7b6 100644 --- a/bitchat/Views/NoticesView.swift +++ b/bitchat/Views/NoticesView.swift @@ -248,6 +248,7 @@ struct NoticesView: View { static let placeholder = String(localized: "board.compose.placeholder", defaultValue: "post a notice…", comment: "Placeholder for the board composer text field") static let send = String(localized: "board.accessibility.post", defaultValue: "Post notice", comment: "Accessibility label for the board post button") static let deleteAction = String(localized: "board.action.delete", defaultValue: "delete", comment: "Delete action for own board posts") + static let confirmAction = String(localized: "board.action.confirm", defaultValue: "confirm", comment: "Action to vouch for someone else's urgent board post; people who verified you see it as a confirmation") static let expiryLabel = String(localized: "board.compose.expiry", defaultValue: "expires in", comment: "Label for the board post expiry picker") static let permanentOption = String(localized: "notices.expiry.permanent", defaultValue: "permanent", comment: "Accessibility label for the ∞ (never expires) option in the geo notes expiry picker") static let closeHint = String(localized: "notices.accessibility.close", defaultValue: "Close notices", comment: "Accessibility label for the notices close button") @@ -282,13 +283,24 @@ struct NoticesView: View { ) } - static func rowAccessibilityLabel(author: String, content: String, urgent: Bool) -> String { + static func confirmedBadge(_ count: Int) -> String { + String( + format: String(localized: "board.confirmed_badge", defaultValue: "confirmed (%lld)", comment: "Badge on an urgent board post endorsed by people the user verified or vouched for; placeholder is how many"), + locale: .current, + count + ) + } + + static func rowAccessibilityLabel(author: String, content: String, urgent: Bool, confirmations: Int = 0) -> String { let base = String( format: String(localized: "board.accessibility.post_row", defaultValue: "Notice from %@: %@", comment: "Accessibility label for a board post row"), locale: .current, author, content ) - return urgent ? "\(urgentBadge), \(base)" : base + var prefix: [String] = [] + if urgent { prefix.append(urgentBadge) } + if confirmations > 0 { prefix.append(confirmedBadge(confirmations)) } + return prefix.isEmpty ? base : (prefix + [base]).joined(separator: ", ") } } @@ -599,7 +611,7 @@ private struct GeoNoticesList: View { private struct NoticesList: View { let items: [NoticeItem] let showsSource: Bool - let board: BoardManager + @ObservedObject var board: BoardManager let notesManager: LocationNotesManager? @ThemedPalette private var palette @@ -722,8 +734,25 @@ private struct NoticesList: View { } } + private func confirmations(_ item: NoticeItem) -> Int { + guard case .board(let post) = item.source else { return 0 } + return board.confirmationCount(for: post) + } + + private func canEndorse(_ item: NoticeItem) -> Bool { + guard case .board(let post) = item.source else { return false } + return board.canEndorse(post) + } + + private func endorse(_ item: NoticeItem) { + guard case .board(let post) = item.source else { return } + board.endorsePost(post) + } + private func row(_ item: NoticeItem) -> some View { let isOwn = canDelete(item) + let confirmed = confirmations(item) + let endorsable = canEndorse(item) return VStack(alignment: .leading, spacing: 2) { HStack(spacing: 6) { if item.isUrgent { @@ -734,6 +763,14 @@ private struct NoticesList: View { .bitchatFont(size: 11, weight: .semibold) .foregroundColor(palette.alertRed) } + if confirmed > 0 { + Image(systemName: "checkmark.shield.fill") + .font(.bitchatSystem(size: 11)) + .foregroundColor(palette.accent) + Text(Strings.confirmedBadge(confirmed)) + .bitchatFont(size: 11, weight: .semibold) + .foregroundColor(palette.accent) + } Text(verbatim: "@\(item.author)") .bitchatFont(size: 12, weight: .semibold) Text(Self.timestampText(for: item.createdAt)) @@ -748,6 +785,17 @@ private struct NoticesList: View { if showsSource { sourceBadge(item) } + if endorsable { + Button { + endorse(item) + } label: { + Image(systemName: "checkmark.shield") + .font(.bitchatSystem(size: 12)) + .foregroundColor(palette.secondary) + } + .buttonStyle(.plain) + .accessibilityLabel(Strings.confirmAction) + } if isOwn { Button { delete(item) @@ -766,12 +814,25 @@ private struct NoticesList: View { } .padding(.vertical, 4) .accessibilityElement(children: .ignore) - .accessibilityLabel(Strings.rowAccessibilityLabel(author: item.author, content: item.content, urgent: item.isUrgent)) + .accessibilityLabel(Strings.rowAccessibilityLabel(author: item.author, content: item.content, urgent: item.isUrgent, confirmations: confirmed)) .accessibilityActions { + if endorsable { + Button(Strings.confirmAction) { endorse(item) } + } if isOwn { Button(Strings.deleteAction) { delete(item) } } } + .swipeActions(edge: .leading, allowsFullSwipe: true) { + if endorsable { + Button { + endorse(item) + } label: { + Label(Strings.confirmAction, systemImage: "checkmark.shield") + } + .tint(palette.accent) + } + } .swipeActions(edge: .trailing, allowsFullSwipe: false) { if isOwn { Button(role: .destructive) { diff --git a/bitchatTests/Services/BoardManagerTests.swift b/bitchatTests/Services/BoardManagerTests.swift index 39363ea7..2715eab3 100644 --- a/bitchatTests/Services/BoardManagerTests.swift +++ b/bitchatTests/Services/BoardManagerTests.swift @@ -209,4 +209,20 @@ struct BoardManagerTests { let manager = makeManager(trusted: [Curve25519.Signing.PrivateKey().publicKey.rawRepresentation]) #expect(manager.confirmationCount(for: try makePost()) == 0) } + + // MARK: - Notices row label + + @Test func rowLabelAnnouncesConfirmationAfterUrgency() { + let label = NoticesView.Strings.rowAccessibilityLabel(author: "scout", content: "bridge out", urgent: true, confirmations: 2) + let urgent = NoticesView.Strings.urgentBadge + let confirmed = NoticesView.Strings.confirmedBadge(2) + #expect(label.hasPrefix("\(urgent), \(confirmed), ")) + #expect(label.contains("bridge out")) + } + + @Test func rowLabelOmitsConfirmationWhenNobodyTrustedConfirmed() { + let label = NoticesView.Strings.rowAccessibilityLabel(author: "scout", content: "bridge out", urgent: true) + #expect(!label.contains(NoticesView.Strings.confirmedBadge(0))) + #expect(label.hasPrefix("\(NoticesView.Strings.urgentBadge), ")) + } } From 8877feb0835e327260aaa67101bd3084012f7041 Mon Sep 17 00:00:00 2001 From: Taksh Date: Mon, 12 Oct 2026 08:57:08 +0530 Subject: [PATCH 7/8] test board endorsements end to end on the simulated mesh Three real engines in a line: alice pins an urgent notice, carol endorses it two hops away, and the endorsement relays back through bob into all three stores. A self-endorsement is refused at every node. --- .../BoardEndorsementMeshTests.swift | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 bitchatTests/Simulation/BoardEndorsementMeshTests.swift diff --git a/bitchatTests/Simulation/BoardEndorsementMeshTests.swift b/bitchatTests/Simulation/BoardEndorsementMeshTests.swift new file mode 100644 index 00000000..4e96cbe0 --- /dev/null +++ b/bitchatTests/Simulation/BoardEndorsementMeshTests.swift @@ -0,0 +1,118 @@ +// +// BoardEndorsementMeshTests.swift +// bitchatTests +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import BitFoundation +import Foundation +import Testing +@testable import bitchat + +/// Board endorsements over real engines: a post and its endorsement relay +/// across a line topology and land in every node's own store. +@Suite(.serialized) +struct BoardEndorsementMeshTests { + + private func signedUrgentPost(by service: BLEService) throws -> BoardPostPacket { + let postID = Data((0..<16).map { _ in UInt8.random(in: 0...255) }) + let key = service.noiseSigningPublicKeyData() + let createdAt = UInt64(Date().timeIntervalSince1970 * 1000) + let expiresAt = createdAt + 60 * 60 * 1000 + let signingBytes = BoardPostPacket.signingBytes( + postID: postID, + geohash: "", + content: "flooding at the underpass", + authorSigningKey: key, + authorNickname: "alice", + createdAt: createdAt, + expiresAt: expiresAt, + flags: BoardPostPacket.urgentFlag + ) + return BoardPostPacket( + postID: postID, + geohash: "", + content: "flooding at the underpass", + authorSigningKey: key, + authorNickname: "alice", + createdAt: createdAt, + expiresAt: expiresAt, + flags: BoardPostPacket.urgentFlag, + signature: try #require(service.noiseSignData(signingBytes)) + ) + } + + private func signedEndorsement(of post: BoardPostPacket, by service: BLEService) throws -> BoardEndorsementPacket { + let key = service.noiseSigningPublicKeyData() + let endorsedAt = UInt64(Date().timeIntervalSince1970 * 1000) + let signingBytes = BoardEndorsementPacket.signingBytes( + postID: post.postID, + postAuthorSigningKey: post.authorSigningKey, + endorserSigningKey: key, + endorsedAt: endorsedAt + ) + return BoardEndorsementPacket( + postID: post.postID, + postAuthorSigningKey: post.authorSigningKey, + endorserSigningKey: key, + endorsedAt: endorsedAt, + signature: try #require(service.noiseSignData(signingBytes)) + ) + } + + @Test + func endorsementRelaysBackToTheAuthorAcrossALine() throws { + let mesh = SimulatedMesh() + let a = mesh.addNode(nickname: "alice") + let b = mesh.addNode(nickname: "bob") + let c = mesh.addNode(nickname: "carol") + let stores = (0..<3).map { _ in BoardStore(persistsToDisk: false) } + for (node, store) in zip([a, b, c], stores) { + node.service.boardStore = store + } + mesh.connect(0, 1) + mesh.connect(1, 2) + mesh.announceAll() + + let post = try signedUrgentPost(by: a.service) + a.service.sendBoardPayload(BoardWire.post(post).encode()) + mesh.settleUntil { stores[2].post(withID: post.postID) != nil } + #expect(stores[2].post(withID: post.postID) != nil) + + let endorsement = try signedEndorsement(of: post, by: c.service) + c.service.sendBoardPayload(BoardWire.endorsement(endorsement).encode()) + mesh.settleUntil { !stores[0].endorserKeys(forPostID: post.postID).isEmpty } + + let carolKey = c.service.noiseSigningPublicKeyData() + #expect(stores[0].endorserKeys(forPostID: post.postID) == [carolKey]) + #expect(stores[1].endorserKeys(forPostID: post.postID) == [carolKey]) + #expect(stores[2].endorserKeys(forPostID: post.postID) == [carolKey]) + } + + @Test + func selfEndorsementIsStoredNowhere() throws { + let mesh = SimulatedMesh() + let a = mesh.addNode(nickname: "alice") + _ = mesh.addNode(nickname: "bob") + let stores = (0..<2).map { _ in BoardStore(persistsToDisk: false) } + for (node, store) in zip(mesh.nodes, stores) { + node.service.boardStore = store + } + mesh.connect(0, 1) + mesh.announceAll() + + let post = try signedUrgentPost(by: a.service) + a.service.sendBoardPayload(BoardWire.post(post).encode()) + mesh.settleUntil { stores[1].post(withID: post.postID) != nil } + + let selfEndorsement = try signedEndorsement(of: post, by: a.service) + a.service.sendBoardPayload(BoardWire.endorsement(selfEndorsement).encode()) + mesh.advanceTime(by: 2) + mesh.advanceTime(by: 2) + + #expect(stores[0].endorserKeys(forPostID: post.postID).isEmpty) + #expect(stores[1].endorserKeys(forPostID: post.postID).isEmpty) + } +} From 211964c998305239a606e275cac33fe5d523c652 Mon Sep 17 00:00:00 2001 From: Taksh Date: Mon, 12 Oct 2026 09:21:56 +0530 Subject: [PATCH 8/8] bind endorsements to the exact post, ignore flags on non-posts, keep trusted endorser slots --- bitchat/Protocols/BoardPackets.swift | 42 +++++++-- bitchat/Services/Board/BoardManager.swift | 9 +- bitchat/Services/Board/BoardStore.swift | 72 +++++++++++---- .../Protocols/BoardPacketsTests.swift | 38 ++++++++ .../Services/BoardAlertsModelTests.swift | 1 + bitchatTests/Services/BoardManagerTests.swift | 2 + bitchatTests/Services/BoardStoreTests.swift | 87 ++++++++++++++++++- .../BoardEndorsementMeshTests.swift | 2 + 8 files changed, 227 insertions(+), 26 deletions(-) diff --git a/bitchat/Protocols/BoardPackets.swift b/bitchat/Protocols/BoardPackets.swift index cfbea657..c91056c2 100644 --- a/bitchat/Protocols/BoardPackets.swift +++ b/bitchat/Protocols/BoardPackets.swift @@ -26,6 +26,8 @@ import Foundation // - 0x0B: deletedAt (u64 big-endian, ms) [tombstone] // - 0x0C: endorserSigningKey (32B Ed25519 public key) [endorsement] // - 0x0D: endorsedAt (u64 big-endian, ms) [endorsement] +// - 0x0E: postDigest (32B SHA-256 of the endorsed post's signing bytes) +// [endorsement] // Unknown TLVs are skipped for forward compatibility. Clients that predate a // kind fail to decode it and drop it without relaying. @@ -33,6 +35,7 @@ enum BoardWireConstants { static let postIDLength = 16 static let signingKeyLength = 32 static let signatureLength = 64 + static let postDigestLength = 32 static let contentMaxBytes = 512 static let nicknameMaxBytes = 64 static let geohashMaxLength = 12 @@ -58,6 +61,7 @@ private enum BoardTLVType: UInt8 { case deletedAt = 0x0B case endorserSigningKey = 0x0C case endorsedAt = 0x0D + case postDigest = 0x0E } private enum BoardWireKind: UInt8 { @@ -124,6 +128,12 @@ struct BoardPostPacket: Equatable { func verifySignature() -> Bool { BoardWireEncoding.verify(signature: signature, over: signingBytes, publicKey: authorSigningKey) } + + /// Names this exact post (content, scope, flags, and timestamps), so an + /// endorsement can't carry over to another post reusing the ID. + var digest: Data { + Data(SHA256.hash(data: signingBytes)) + } } /// A signed deletion marker. Only the author's key can produce one; receivers @@ -159,6 +169,9 @@ struct BoardEndorsementPacket: Equatable { /// Bound into the signature so an endorsement cannot be re-pointed at a /// different author's post that reuses the ID. let postAuthorSigningKey: Data + /// The endorsed post's `digest`. The author could otherwise collect an + /// endorsement and re-sign different content under the same ID. + let postDigest: Data let endorserSigningKey: Data let endorsedAt: UInt64 let signature: Data @@ -166,6 +179,7 @@ struct BoardEndorsementPacket: Equatable { static func signingBytes( postID: Data, postAuthorSigningKey: Data, + postDigest: Data, endorserSigningKey: Data, endorsedAt: UInt64 ) -> Data { @@ -173,6 +187,7 @@ struct BoardEndorsementPacket: Equatable { BoardWireEncoding.appendContext(BoardWireConstants.endorsementSigningContext, to: &out) out.append(postID) out.append(postAuthorSigningKey) + out.append(postDigest) out.append(endorserSigningKey) BoardWireEncoding.appendUInt64(endorsedAt, to: &out) return out @@ -182,6 +197,7 @@ struct BoardEndorsementPacket: Equatable { Self.signingBytes( postID: postID, postAuthorSigningKey: postAuthorSigningKey, + postDigest: postDigest, endorserSigningKey: endorserSigningKey, endorsedAt: endorsedAt ) @@ -229,6 +245,7 @@ enum BoardWire: Equatable { putTLV(.kind, Data([BoardWireKind.endorsement.rawValue])) putTLV(.postID, endorsement.postID) putTLV(.authorSigningKey, endorsement.postAuthorSigningKey) + putTLV(.postDigest, endorsement.postDigest) putTLV(.endorserSigningKey, endorsement.endorserSigningKey) putTLV(.endorsedAt, BoardWireEncoding.uint64Data(endorsement.endorsedAt)) putTLV(.signature, endorsement.signature) @@ -255,6 +272,7 @@ enum BoardWire: Equatable { var deletedAt: UInt64? var endorserSigningKey: Data? var endorsedAt: UInt64? + var postDigest: Data? while off + 3 <= data.endIndex { let t = data[off]; off += 1 @@ -299,6 +317,9 @@ enum BoardWire: Equatable { endorserSigningKey = v case .endorsedAt: endorsedAt = BoardWireEncoding.uint64(from: v) + case .postDigest: + guard v.count == BoardWireConstants.postDigestLength else { return nil } + postDigest = v case nil: continue // forward compatible; ignore unknown TLVs } @@ -337,10 +358,15 @@ enum BoardWire: Equatable { signature: signature )) case .endorsement: - guard let endorserSigningKey, let endorsedAt else { return nil } + // Post-only fields have no place here; a flags TLV in particular + // would read as urgent to the relay peek. + guard let endorserSigningKey, let endorsedAt, let postDigest, + flags == nil, content == nil, geohash == nil, authorNickname == nil, + createdAt == nil, expiresAt == nil, deletedAt == nil else { return nil } return .endorsement(BoardEndorsementPacket( postID: postID, postAuthorSigningKey: authorSigningKey, + postDigest: postDigest, endorserSigningKey: endorserSigningKey, endorsedAt: endorsedAt, signature: signature @@ -359,19 +385,25 @@ enum BoardWire: Equatable { } /// Cheap TLV peek for relay policy: is this payload an urgent post? - /// Avoids a full decode on the hot relay path. + /// Avoids a full decode on the hot relay path. Only the post kind can be + /// urgent, so a flags TLV slipped onto a tombstone or endorsement never + /// earns the longer relay reach. static func urgentFlag(in data: Data) -> Bool { var off = data.startIndex + var isPost = false + var isUrgent = false while off + 3 <= data.endIndex { let t = data[off]; off += 1 let len = (Int(data[off]) << 8) | Int(data[off + 1]); off += 2 guard off + len <= data.endIndex else { return false } - if t == BoardTLVType.flags.rawValue, len == 1 { - return data[off] & BoardPostPacket.urgentFlag != 0 + if t == BoardTLVType.kind.rawValue, len == 1 { + isPost = data[off] == BoardWireKind.post.rawValue + } else if t == BoardTLVType.flags.rawValue, len == 1 { + isUrgent = data[off] & BoardPostPacket.urgentFlag != 0 } off += len } - return false + return isPost && isUrgent } /// Empty geohash = mesh-local board; otherwise 1-12 chars of the geohash diff --git a/bitchat/Services/Board/BoardManager.swift b/bitchat/Services/Board/BoardManager.swift index f0e2efc9..6452005a 100644 --- a/bitchat/Services/Board/BoardManager.swift +++ b/bitchat/Services/Board/BoardManager.swift @@ -23,7 +23,7 @@ final class BoardManager: ObservableObject { private let transport: Transport /// Keys whose endorsements count as confirmation (verified or vouched /// peers). Read per call so a fresh verification shows up immediately. - private let trustedSigningKeys: () -> Set + private let trustedSigningKeys: @Sendable () -> Set /// Board broadcast rides the mesh only; absent on other transports. private var boardTransport: MeshBoardBroadcasting? { transport as? MeshBoardBroadcasting } /// Publishes a bridged kind-1 note (expiring with the board post via @@ -41,12 +41,15 @@ final class BoardManager: ObservableObject { init( transport: Transport, store: BoardStore = .shared, - trustedSigningKeys: (() -> Set)? = nil, + trustedSigningKeys: (@Sendable () -> Set)? = nil, publishToNostr: ((String, String, String, UInt64, Bool) -> String?)? = nil, deleteFromNostr: ((String, String) -> Void)? = nil ) { self.transport = transport self.trustedSigningKeys = trustedSigningKeys ?? { [] } + if let trustedSigningKeys { + store.setTrustedEndorsers(trustedSigningKeys) + } self.publishToNostr = publishToNostr ?? Self.livePublishToNostr self.deleteFromNostr = deleteFromNostr ?? Self.liveDeleteFromNostr store.$postsSnapshot @@ -111,6 +114,7 @@ final class BoardManager: ObservableObject { let signingBytes = BoardEndorsementPacket.signingBytes( postID: post.postID, postAuthorSigningKey: post.authorSigningKey, + postDigest: post.digest, endorserSigningKey: signingKey, endorsedAt: endorsedAt ) @@ -121,6 +125,7 @@ final class BoardManager: ObservableObject { let endorsement = BoardEndorsementPacket( postID: post.postID, postAuthorSigningKey: post.authorSigningKey, + postDigest: post.digest, endorserSigningKey: signingKey, endorsedAt: endorsedAt, signature: signature diff --git a/bitchat/Services/Board/BoardStore.swift b/bitchat/Services/Board/BoardStore.swift index 7f03f27a..c8a8744a 100644 --- a/bitchat/Services/Board/BoardStore.swift +++ b/bitchat/Services/Board/BoardStore.swift @@ -120,6 +120,9 @@ final class BoardStore { private let queue = DispatchQueue(label: "chat.bitchat.board.store") private let fileURL: URL? private let now: () -> Date + /// Signing keys this device trusts, read on `queue` when endorsement + /// slots run out (see `setTrustedEndorsers`). + private var trustedEndorsers: @Sendable () -> Set = { [] } /// - Parameter fileURL: Overrides the on-disk location (tests). Ignored /// when `persistsToDisk` is false. @@ -129,6 +132,13 @@ final class BoardStore { loadFromDisk() } + /// Lets endorsements from people this device trusts keep a slot when a + /// post's (or the store's) endorsement budget is full, so a burst of + /// freshly minted keys can't crowd out the confirmations that count. + func setTrustedEndorsers(_ provider: @escaping @Sendable () -> Set) { + queue.sync { trustedEndorsers = provider } + } + // MARK: - Ingest /// Ingest a board packet whose payload decodes to `wire`. The caller must @@ -355,12 +365,23 @@ final class BoardStore { }) else { return .duplicate } if let target = posts.first(where: { $0.post.postID == endorsement.postID })?.post { - guard target.authorSigningKey == endorsement.postAuthorSigningKey else { return .rejected } - let stored = endorsements.filter { !$0.isOrphan && $0.endorsement.postID == endorsement.postID }.count - // First come keeps the slot: evicting by recency would let a burst - // of fresh keys push out endorsements that already counted. A - // full post still relays the endorsement for peers with room. - guard stored < Limits.maxEndorsementsPerPost else { return .accepted } + guard target.authorSigningKey == endorsement.postAuthorSigningKey, + target.digest == endorsement.postDigest else { return .rejected } + let stored = endorsements.filter { !$0.isOrphan && $0.endorsement.postID == endorsement.postID } + if stored.count >= Limits.maxEndorsementsPerPost { + // First come keeps the slot: evicting by recency would let a + // burst of fresh keys push out endorsements that already + // counted. The one exception is a trusted endorser, who takes + // the newest untrusted slot. A full post still relays the + // endorsement for peers with room. + let trusted = trustedEndorsers() + guard trusted.contains(endorsement.endorserSigningKey), + let displaced = endorsements.lastIndex(where: { + !$0.isOrphan && $0.endorsement.postID == endorsement.postID + && !trusted.contains($0.endorsement.endorserSigningKey) + }) else { return .accepted } + endorsements.remove(at: displaced) + } endorsements.append(StoredEndorsement( endorsement: endorsement, packet: packet, @@ -391,24 +412,31 @@ final class BoardStore { } /// A newly arrived post claims the endorsements that raced ahead of it. - /// Ones naming a different author key were never about this post. + /// Ones naming a different author key or post digest were never about + /// this post. Trusted endorsers are adopted first when there are more + /// candidates than slots. private func adoptOrphanEndorsementsLocked(for post: BoardPostPacket) { + let digest = post.digest endorsements.removeAll { $0.isOrphan && $0.endorsement.postID == post.postID - && $0.endorsement.postAuthorSigningKey != post.authorSigningKey + && ($0.endorsement.postAuthorSigningKey != post.authorSigningKey || $0.endorsement.postDigest != digest) } - var adopted = 0 + let candidates = endorsements.indices.filter { + endorsements[$0].isOrphan && endorsements[$0].endorsement.postID == post.postID + } + guard !candidates.isEmpty else { return } + let trusted = trustedEndorsers() + let ordered = candidates.filter { trusted.contains(endorsements[$0].endorsement.endorserSigningKey) } + + candidates.filter { !trusted.contains(endorsements[$0].endorsement.endorserSigningKey) } var overflow = Set() - for index in endorsements.indices - where endorsements[index].isOrphan && endorsements[index].endorsement.postID == post.postID { - guard adopted < Limits.maxEndorsementsPerPost else { + for (rank, index) in ordered.enumerated() { + guard rank < Limits.maxEndorsementsPerPost else { overflow.insert(endorsements[index].endorsement.endorserSigningKey) continue } endorsements[index].isOrphan = false endorsements[index].retainUntil = post.expiresAt - adopted += 1 } if !overflow.isEmpty { endorsements.removeAll { @@ -433,14 +461,22 @@ final class BoardStore { } } - /// Global cap, oldest received first, orphans before endorsements that - /// already count toward a live post. + /// Global cap, oldest received first: orphans before endorsements that + /// already count toward a live post, and within each, untrusted + /// endorsers before trusted ones. private func enforceEndorsementCapLocked() { let excess = endorsements.count - Limits.maxEndorsements guard excess > 0 else { return } - let orphanOffsets = endorsements.enumerated().filter { $0.element.isOrphan }.map(\.offset) - let matchedOffsets = endorsements.enumerated().filter { !$0.element.isOrphan }.map(\.offset) - let drop = Set((orphanOffsets + matchedOffsets).prefix(excess)) + let trusted = trustedEndorsers() + func offsets(orphan: Bool, trusted isTrusted: Bool) -> [Int] { + endorsements.enumerated().filter { + $0.element.isOrphan == orphan + && trusted.contains($0.element.endorsement.endorserSigningKey) == isTrusted + }.map(\.offset) + } + let evictionOrder = offsets(orphan: true, trusted: false) + offsets(orphan: true, trusted: true) + + offsets(orphan: false, trusted: false) + offsets(orphan: false, trusted: true) + let drop = Set(evictionOrder.prefix(excess)) endorsements = endorsements.enumerated().filter { !drop.contains($0.offset) }.map(\.element) } diff --git a/bitchatTests/Protocols/BoardPacketsTests.swift b/bitchatTests/Protocols/BoardPacketsTests.swift index 2edca9d5..59b2dc22 100644 --- a/bitchatTests/Protocols/BoardPacketsTests.swift +++ b/bitchatTests/Protocols/BoardPacketsTests.swift @@ -227,12 +227,14 @@ struct BoardPacketsTests { let signingBytes = BoardEndorsementPacket.signingBytes( postID: post.postID, postAuthorSigningKey: post.authorSigningKey, + postDigest: post.digest, endorserSigningKey: endorserKey, endorsedAt: endorsedAt ) return BoardEndorsementPacket( postID: post.postID, postAuthorSigningKey: post.authorSigningKey, + postDigest: post.digest, endorserSigningKey: endorserKey, endorsedAt: endorsedAt, signature: try key.signature(for: signingBytes) @@ -261,6 +263,7 @@ struct BoardPacketsTests { let repointed = BoardEndorsementPacket( postID: endorsement.postID, postAuthorSigningKey: Curve25519.Signing.PrivateKey().publicKey.rawRepresentation, + postDigest: endorsement.postDigest, endorserSigningKey: endorsement.endorserSigningKey, endorsedAt: endorsement.endorsedAt, signature: endorsement.signature @@ -269,6 +272,41 @@ struct BoardPacketsTests { #expect(!decoded.verifySignature()) } + @Test func endorsementCannotBeRepointedAtAnotherVersionOfThePost() throws { + let post = try makeSignedPost() + let endorsement = try makeSignedEndorsement(of: post) + let repointed = BoardEndorsementPacket( + postID: endorsement.postID, + postAuthorSigningKey: endorsement.postAuthorSigningKey, + postDigest: Data(repeating: 0xAB, count: BoardWireConstants.postDigestLength), + endorserSigningKey: endorsement.endorserSigningKey, + endorsedAt: endorsement.endorsedAt, + signature: endorsement.signature + ) + let decoded = try #require(BoardWire.decode(from: BoardWire.endorsement(repointed).encode())) + #expect(!decoded.verifySignature()) + } + + @Test func endorsementCarryingPostOnlyFieldsIsRejected() throws { + let post = try makeSignedPost() + let encoded = BoardWire.endorsement(try makeSignedEndorsement(of: post)).encode() + let urgentFlags = Data([0x09, 0x00, 0x01, BoardPostPacket.urgentFlag]) + #expect(BoardWire.decode(from: encoded + urgentFlags) == nil) + let content = Data([0x04, 0x00, 0x01, 0x41]) + #expect(BoardWire.decode(from: encoded + content) == nil) + } + + @Test func onlyUrgentPostsPeekAsUrgent() throws { + let urgentPost = try makeSignedPost(flags: BoardPostPacket.urgentFlag) + #expect(BoardWire.urgentFlag(in: BoardWire.post(urgentPost).encode())) + + // A flags TLV appended to a non-post never earns the urgent relay reach. + let urgentFlags = Data([0x09, 0x00, 0x01, BoardPostPacket.urgentFlag]) + let endorsement = BoardWire.endorsement(try makeSignedEndorsement(of: urgentPost)).encode() + #expect(!BoardWire.urgentFlag(in: endorsement + urgentFlags)) + #expect(!BoardWire.urgentFlag(in: urgentFlags)) + } + @Test func endorsementMissingEndorserKeyIsRejected() throws { let post = try makeSignedPost() let endorsement = try makeSignedEndorsement(of: post) diff --git a/bitchatTests/Services/BoardAlertsModelTests.swift b/bitchatTests/Services/BoardAlertsModelTests.swift index 865b02f6..f7d21314 100644 --- a/bitchatTests/Services/BoardAlertsModelTests.swift +++ b/bitchatTests/Services/BoardAlertsModelTests.swift @@ -224,6 +224,7 @@ struct BoardAlertsModelTests { BoardEndorsementPacket( postID: post.postID, postAuthorSigningKey: post.authorSigningKey, + postDigest: post.digest, endorserSigningKey: Data(repeating: 9, count: 32), endorsedAt: baseMs + 1, signature: Data(repeating: 2, count: 64) diff --git a/bitchatTests/Services/BoardManagerTests.swift b/bitchatTests/Services/BoardManagerTests.swift index 2715eab3..dc56f4ed 100644 --- a/bitchatTests/Services/BoardManagerTests.swift +++ b/bitchatTests/Services/BoardManagerTests.swift @@ -67,11 +67,13 @@ struct BoardManagerTests { return .endorsement(BoardEndorsementPacket( postID: post.postID, postAuthorSigningKey: post.authorSigningKey, + postDigest: post.digest, endorserSigningKey: endorserKey, endorsedAt: endorsedAt, signature: try endorser.signature(for: BoardEndorsementPacket.signingBytes( postID: post.postID, postAuthorSigningKey: post.authorSigningKey, + postDigest: post.digest, endorserSigningKey: endorserKey, endorsedAt: endorsedAt )) diff --git a/bitchatTests/Services/BoardStoreTests.swift b/bitchatTests/Services/BoardStoreTests.swift index 2bb00e2b..30ed938a 100644 --- a/bitchatTests/Services/BoardStoreTests.swift +++ b/bitchatTests/Services/BoardStoreTests.swift @@ -342,18 +342,22 @@ struct BoardStoreTests { of post: BoardPostPacket, endorser: Curve25519.Signing.PrivateKey, endorsedAt: UInt64, - postAuthorKey: Data? = nil + postAuthorKey: Data? = nil, + postDigest: Data? = nil ) throws -> (wire: BoardWire, packet: BitchatPacket) { let authorKey = postAuthorKey ?? post.authorSigningKey + let digest = postDigest ?? post.digest let endorserKey = endorser.publicKey.rawRepresentation let endorsement = BoardEndorsementPacket( postID: post.postID, postAuthorSigningKey: authorKey, + postDigest: digest, endorserSigningKey: endorserKey, endorsedAt: endorsedAt, signature: try endorser.signature(for: BoardEndorsementPacket.signingBytes( postID: post.postID, postAuthorSigningKey: authorKey, + postDigest: digest, endorserSigningKey: endorserKey, endorsedAt: endorsedAt )) @@ -495,6 +499,87 @@ struct BoardStoreTests { #expect(store.endorserKeys(forPostID: entry.post.postID) == firstKeys) } + @Test func trustedEndorserTakesTheNewestUntrustedSlotOnAFullPost() throws { + let clock = MutableClock(now: baseDate) + let store = makeStore(clock: clock) + let trustedEndorser = Curve25519.Signing.PrivateKey() + let trustedKey = trustedEndorser.publicKey.rawRepresentation + store.setTrustedEndorsers { [trustedKey] } + let entry = try makePost(author: Curve25519.Signing.PrivateKey(), createdAt: baseMs) + store.ingest(entry.wire, packet: entry.packet) + + var flood: [Data] = [] + for index in 0..