Files
bitchat/bitchatTests/Mocks/MockTransport.swift
T
dd6b624cae Quality pass on the 1.7.0 batch: fix confirmed bugs, bump to 1.7.1 (#1418)
* Quality pass on the 1.7.0 batch: fix confirmed bugs, bump to 1.7.1

Post-merge review of PRs #1400–#1417 (push-to-talk, mesh bridging, DM
store-and-forward, empty-mesh liveliness, geo-notes). Fixes the confirmed,
well-scoped findings; deeper architectural/security items are tracked
separately.

- PTT hot-mic leak: releasing the mic during VoiceCaptureSession.start()'s
  150ms retry pause left the mic live and streaming for up to 120s, because
  cancel() no-op'd once `completed` was set. Bail after the sleep if the hold
  was released, and make cancel() always tear down a late-started capture.
- Bridge courier depositDrop reported success and burned the dedup slot before
  the drop was actually published (evicted/compose-fail = lying 📦 "carried"
  with no retry). Only consume publishedDropKeys on durable accept; add
  BoundedIDSet.remove() to release evicted/failed slots (uses the dead dedupKey).
- Blocked senders resurfaced via archived "heard here earlier" echoes, the one
  path that bypassed the live block filter — filter at seed time.
- A late optimistic .sent clobbered the router's .carried state; extend
  ConversationStore.shouldSkipStatusUpdate to a full precedence guard
  (sending < sent < carried < delivered < read).
- Read receipts were permanently burned when the router dropped them (marked
  sent then dropped). sendReadReceipt/routeReadReceipt now return Bool; only
  record as sent on a successful route, else retry on the next read scan.
- MessageRouter.cleanupExpiredMessages() had no production caller, so DMs to a
  peer that never reconnects sat on .sending until relaunch — run it in the
  120s bridge sweep.
- Sightings tally now rolls over at midnight while idle; wave notification
  action localized across all 29 locales; bridged anon#tag uses suffix(4) like
  everything else; makeThrowawayIdentity delegates to NostrIdentity.generate();
  .swiftlint.yml excludes .claude worktrees.
- Add regression tests: carried→sent no-downgrade, carried→delivered upgrade,
  evicted pending drop stays retryable.
- Bump MARKETING_VERSION to 1.7.1.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Fix CI: adjust delivery-status benchmark and drop now-dead addSystemMessage

The stricter no-downgrade guard (delivered/carried never regress to sent) broke
two things the earlier commit didn't catch locally (perf tests are skipped in
the default run, and Periphery runs only in CI):

- PerformanceBaselineTests delivery benchmarks alternated sent <-> delivered
  assuming both directions apply; the delivered -> sent half is now correctly
  skipped, so the pass measured 0 updates. Alternate two delivered timestamps
  instead — every update is real, no downgrade.
- Routing the geoDM "not in a location channel" error into the thread removed
  the only caller of ChatPrivateConversationContext.addSystemMessage, leaving
  it (and its mock) dead per Periphery. Drop the protocol requirement, the mock
  impl, and the now-vacuous systemMessages.isEmpty assertions (the invariant is
  compile-time enforced: the context can no longer emit a public system line).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Address review findings: read-receipt dedup, carried-vs-sending, block-time echo purge

- Read receipts: claim the receipt in sentReadReceipts synchronously
  before spawning the routing task (chat open runs two read scans in one
  MainActor stretch, so the async insert let every unread message route
  twice), and release the claim when the route fails so the
  retry-on-failed-route behavior is preserved.

- Delivery status: extend the no-downgrade guard so the `.sending`
  stamp a pre-handshake resend emits can no longer clobber
  carried/delivered/read (the 📦 indicator survived `.sent` but not
  `.sending`).

- Archived echoes: blocking a peer now purges their carried public
  messages from the gossip archive at block time (UnifiedPeerService
  and /block), while the fingerprint-to-peerID mapping is still known —
  the seed-time filter can't resolve offline non-favorite strangers and
  stays only as defense-in-depth. New Transport hook (default no-op) +
  GossipSyncManager.removePublicMessages with immediate persist.

- Bridge courier: an envelope that can't encode within the drop size
  caps fails identically on every attempt; consume the dedup slot so
  the 120s retry sweep stops re-running Noise sealing on it.

- MeshSightingsTracker: cache the day-key DateFormatter instead of
  building one per call.

Tests: double-markAsRead dedup + failed-route retry, carried→sending
no-downgrade matrix, block-time purge (manager + service wiring),
oversize-drop slot consumption.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Also skip the sent→sending downgrade in the delivery-status guard

Codex review follow-up: sendPrivateMessage without an established Noise
session emits `.sending` asynchronously, so it can land after the
message already reached `.sent` and visibly walk "Sent" back to
"Sending...". Treat `.sending` as weaker than `.sent` too — the status
was already truthful. `.failed` → `.sending` stays allowed so a retry
after a real failure remains visible.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Retain Codable properties in Periphery scan (same fix as #1421)

The noiseKey assign-only false positive fired persistently on this branch
(twice, including a rerun) despite the baselined USR. Byte-identical to the
fix on fix/announce-replay-link-steal so the branches merge cleanly in
either order.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 16:44:02 +02:00

312 lines
10 KiB
Swift

//
// MockTransport.swift
// bitchatTests
//
// Mock Transport implementation for unit testing ChatViewModel.
// This is free and unencumbered software released into the public domain.
//
import Foundation
import Combine
import CoreBluetooth
import BitFoundation
@testable import bitchat
/// Mock Transport implementation for testing ChatViewModel in isolation.
/// Records all method calls and allows test code to verify interactions.
final class MockTransport: Transport {
// MARK: - Protocol Properties
weak var delegate: BitchatDelegate?
weak var eventDelegate: TransportEventDelegate?
weak var peerEventsDelegate: TransportPeerEventsDelegate?
var myPeerID: PeerID = PeerID(str: "TESTPEER")
var myNickname: String = "TestUser"
private let peerSnapshotSubject = CurrentValueSubject<[TransportPeerSnapshot], Never>([])
// MARK: - Recording Properties (for test assertions)
private(set) var sentMessages: [(content: String, mentions: [String], messageID: String?, timestamp: Date?)] = []
private(set) var sentPrivateMessages: [(content: String, peerID: PeerID, recipientNickname: String, messageID: String)] = []
private(set) var sentReadReceipts: [(receipt: ReadReceipt, peerID: PeerID)] = []
private(set) var sentDeliveryAcks: [(messageID: String, peerID: PeerID)] = []
private(set) var sentFavoriteNotifications: [(peerID: PeerID, isFavorite: Bool)] = []
private(set) var sentBroadcastFiles: [(packet: BitchatFilePacket, transferID: String)] = []
private(set) var sentPrivateFiles: [(packet: BitchatFilePacket, peerID: PeerID, transferID: String)] = []
private(set) var cancelledTransfers: [String] = []
private(set) var sentVerifyChallenges: [(peerID: PeerID, noiseKeyHex: String, nonceA: Data)] = []
private(set) var sentVerifyResponses: [(peerID: PeerID, noiseKeyHex: String, nonceA: Data)] = []
private(set) var sentCourierMessages: [(content: String, messageID: String, recipientNoiseKey: Data, couriers: [PeerID])] = []
private(set) var startServicesCallCount = 0
private(set) var stopServicesCallCount = 0
private(set) var emergencyDisconnectCallCount = 0
private(set) var broadcastAnnounceCallCount = 0
private(set) var triggeredHandshakes: [PeerID] = []
private(set) var purgedArchivePeers: [PeerID] = []
// MARK: - Configurable Mock State
var connectedPeers: Set<PeerID> = []
var reachablePeers: Set<PeerID> = []
var peerNicknames: [PeerID: String] = [:]
var peerFingerprints: [PeerID: String] = [:]
var peerNoiseStates: [PeerID: LazyHandshakeState] = [:]
private let mockKeychain = MockKeychain()
// MARK: - Transport Protocol Implementation
func currentPeerSnapshots() -> [TransportPeerSnapshot] {
peerSnapshotSubject.value
}
func setNickname(_ nickname: String) {
myNickname = nickname
}
func startServices() {
startServicesCallCount += 1
}
func stopServices() {
stopServicesCallCount += 1
}
func emergencyDisconnectAll() {
emergencyDisconnectCallCount += 1
connectedPeers.removeAll()
reachablePeers.removeAll()
}
func isPeerConnected(_ peerID: PeerID) -> Bool {
connectedPeers.contains(peerID)
}
func isPeerReachable(_ peerID: PeerID) -> Bool {
reachablePeers.contains(peerID) || connectedPeers.contains(peerID)
}
func peerNickname(peerID: PeerID) -> String? {
peerNicknames[peerID]
}
func getPeerNicknames() -> [PeerID: String] {
peerNicknames
}
func getFingerprint(for peerID: PeerID) -> String? {
peerFingerprints[peerID]
}
func getNoiseSessionState(for peerID: PeerID) -> LazyHandshakeState {
peerNoiseStates[peerID] ?? .none
}
func triggerHandshake(with peerID: PeerID) {
triggeredHandshakes.append(peerID)
}
func purgeArchivedPublicMessages(from peerID: PeerID) {
purgedArchivePeers.append(peerID)
}
// Noise identity wrappers backed by a mock-keychain encryption service
// (mirrors the previous `getNoiseService()` placeholder behavior: a real
// identity, but no peer sessions). Exposed so tests can assert against
// the same identity the wrappers use.
private(set) lazy var mockNoiseService = NoiseEncryptionService(keychain: mockKeychain)
func noiseSessionPublicKeyData(for peerID: PeerID) -> Data? {
mockNoiseService.getPeerPublicKeyData(peerID)
}
func noiseIdentityFingerprint() -> String {
mockNoiseService.getIdentityFingerprint()
}
func noiseStaticPublicKeyData() -> Data {
mockNoiseService.getStaticPublicKeyData()
}
func noiseSigningPublicKeyData() -> Data {
mockNoiseService.getSigningPublicKeyData()
}
func noiseSignData(_ data: Data) -> Data? {
mockNoiseService.signData(data)
}
func noiseVerifySignature(_ signature: Data, for data: Data, publicKey: Data) -> Bool {
mockNoiseService.verifySignature(signature, for: data, publicKey: publicKey)
}
// MARK: - Messaging
func sendMessage(_ content: String, mentions: [String]) {
sentMessages.append((content, mentions, nil, nil))
}
func sendMessage(_ content: String, mentions: [String], messageID: String, timestamp: Date) {
sentMessages.append((content, mentions, messageID, timestamp))
}
func sendPrivateMessage(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String) {
sentPrivateMessages.append((content, peerID, recipientNickname, messageID))
}
func sendReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) {
sentReadReceipts.append((receipt, peerID))
}
func sendFavoriteNotification(to peerID: PeerID, isFavorite: Bool) {
sentFavoriteNotifications.append((peerID, isFavorite))
}
func sendBroadcastAnnounce() {
broadcastAnnounceCallCount += 1
}
func sendDeliveryAck(for messageID: String, to peerID: PeerID) {
sentDeliveryAcks.append((messageID, peerID))
}
func sendFileBroadcast(_ packet: BitchatFilePacket, transferId: String) {
sentBroadcastFiles.append((packet, transferId))
}
func sendFilePrivate(_ packet: BitchatFilePacket, to peerID: PeerID, transferId: String) {
sentPrivateFiles.append((packet, peerID, transferId))
}
func cancelTransfer(_ transferId: String) {
cancelledTransfers.append(transferId)
}
func sendVerifyChallenge(to peerID: PeerID, noiseKeyHex: String, nonceA: Data) {
sentVerifyChallenges.append((peerID, noiseKeyHex, nonceA))
}
func sendVerifyResponse(to peerID: PeerID, noiseKeyHex: String, nonceA: Data) {
sentVerifyResponses.append((peerID, noiseKeyHex, nonceA))
}
var courierSendResult = true
func sendCourierMessage(_ content: String, messageID: String, recipientNoiseKey: Data, via couriers: [PeerID]) -> Bool {
sentCourierMessages.append((content, messageID, recipientNoiseKey, couriers))
return courierSendResult
}
// MARK: - Mesh Diagnostics
private(set) var sentMeshPings: [PeerID] = []
var meshPingResult: MeshPingResult?
var meshPaths: [PeerID: [PeerID]] = [:]
var meshTopologySnapshot: MeshTopologySnapshot?
func sendMeshPing(to peerID: PeerID, completion: @escaping @MainActor (MeshPingResult?) -> Void) {
sentMeshPings.append(peerID)
let result = meshPingResult
Task { @MainActor in completion(result) }
}
func computeMeshPath(to peerID: PeerID) -> [PeerID]? {
meshPaths[peerID]
}
func currentMeshTopology() -> MeshTopologySnapshot? {
meshTopologySnapshot
}
// MARK: - Test Helpers
/// Clears all recorded method calls for fresh assertions
func resetRecordings() {
sentMessages.removeAll()
sentPrivateMessages.removeAll()
sentReadReceipts.removeAll()
sentDeliveryAcks.removeAll()
sentFavoriteNotifications.removeAll()
sentBroadcastFiles.removeAll()
sentPrivateFiles.removeAll()
cancelledTransfers.removeAll()
sentVerifyChallenges.removeAll()
sentVerifyResponses.removeAll()
startServicesCallCount = 0
stopServicesCallCount = 0
emergencyDisconnectCallCount = 0
broadcastAnnounceCallCount = 0
triggeredHandshakes.removeAll()
}
/// Simulates a peer connecting
func simulateConnect(_ peerID: PeerID, nickname: String? = nil) {
connectedPeers.insert(peerID)
if let nickname = nickname {
peerNicknames[peerID] = nickname
}
delegate?.didConnectToPeer(peerID)
delegate?.didUpdatePeerList(Array(connectedPeers))
publishPeerSnapshots()
}
/// Simulates a peer disconnecting
func simulateDisconnect(_ peerID: PeerID) {
connectedPeers.remove(peerID)
peerNicknames.removeValue(forKey: peerID)
delegate?.didDisconnectFromPeer(peerID)
delegate?.didUpdatePeerList(Array(connectedPeers))
publishPeerSnapshots()
}
/// Simulates receiving a message
func simulateIncomingMessage(_ message: BitchatMessage) {
delegate?.didReceiveMessage(message)
}
/// Simulates receiving a public message
func simulateIncomingPublicMessage(
from peerID: PeerID,
nickname: String,
content: String,
timestamp: Date = Date(),
messageID: String? = nil
) {
delegate?.didReceivePublicMessage(
from: peerID,
nickname: nickname,
content: content,
timestamp: timestamp,
messageID: messageID
)
}
/// Simulates Bluetooth state change
func simulateBluetoothStateChange(_ state: CBManagerState) {
delegate?.didUpdateBluetoothState(state)
}
/// Updates the peer snapshot publisher
func updatePeerSnapshots(_ snapshots: [TransportPeerSnapshot]) {
peerSnapshotSubject.send(snapshots)
Task { @MainActor [weak self] in
self?.peerEventsDelegate?.didUpdatePeerSnapshots(snapshots)
}
}
private func publishPeerSnapshots() {
let now = Date()
let snapshots = connectedPeers.map { peerID in
TransportPeerSnapshot(
peerID: peerID,
nickname: peerNicknames[peerID] ?? "",
isConnected: true,
noisePublicKey: Data(hexString: peerID.bare),
lastSeen: now
)
}
updatePeerSnapshots(snapshots)
}
}