mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-25 01:05:19 +00:00
* Friend-courier store-and-forward: mutual favorites carry sealed messages to offline peers When a private message has no reachable transport, the router now seals it to the recipient's Noise static key (new one-way Noise X pattern) and hands the envelope to up to three connected mutual favorites. Couriers store the opaque ciphertext under strict quotas (20 total, 5 per depositor, 16 KiB, 24 h) and hand it over when the recipient's announce matches a rotating HMAC recipient tag; the recipient opens it and the message flows through the normal private-message pipeline, so dedup and delivery acks just work. - CourierEnvelope TLV + courierEnvelope (0x04) message type in BitFoundation - Noise X one-way pattern reusing the existing handshake machinery, domain-separated by a courier prologue; sender identity authenticated via the ss DH (no forward secrecy - documented tradeoff) - CourierStore with eviction, file persistence, and panic-wipe integration - Rotating recipient tags (HMAC over epoch day) so carried envelopes don't correlate for observers who don't already know the recipient's key - New "carried" delivery status with figure.walk glyph; header indicator while carrying mail for others - Three-node end-to-end test ferrying packets through real BLEService instances, plus codec/crypto/store/router suites (986 tests green) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix courier handoff verification and directed sends * Authenticate courier deposits by ingress peer * Gate courier handover on direct announces and isolate store test Envelopes are removed from the courier store optimistically, so releasing them on a relayed (multi-hop) announce risks losing carried mail to a speculative flood that never reaches the recipient. Handover now also requires the announce to have arrived directly (full TTL), i.e. an actual encounter with a live link; regression test builds a relayed copy of a genuinely signed announce (TTL is excluded from announce signatures). Also make CourierStore's on-disk location injectable so the persistence test round-trips through a temp directory instead of wiping the real Application Support store, and reattach BLEAnnounceHandler's doc comment to the class it describes. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Use Xcode-bundled Swift in CI instead of a standalone toolchain The unpinned setup-swift action installs Swift 6.1, which refuses the SDK on runner images that have rolled to Xcode 26.5 ("this SDK is not supported by the compiler"). Jobs passed or failed depending on which image they landed on. The Xcode-bundled toolchain always matches the image's SDK, and matches local development. Cache keys now include the toolchain version so artifacts from one compiler are never restored into builds with another. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Drop couriered mail from blocked senders at envelope open The UI-layer block check (isPeerBlocked in the transport event coordinator) resolves a fingerprint from the live session or peer list, but a couriered message arrives precisely when its sender is absent — no session, no registry entry — so the check failed open and a blocked identity's mail was delivered anyway. Gate in openCourierEnvelope, where the sealed sender's full static key is in hand. End-to-end test ferries a full deposit→carry→handover round and verifies the envelope from a blocked sender never reaches the delegate (confirmed failing without the gate). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix favorites end-to-end: peer-list dedup, Nostr sync, /fav key corruption - UnifiedPeerService: dedup offline favorites against mesh peers by noise key. Phase 2 compared a 64-hex noise-key PeerID against 16-hex mesh IDs (never equal), leaving only a nickname+isConnected heuristic — a mutual favorite that was reachable-but-not-connected or renamed rendered twice, and a same-nick stranger could suppress a favorite entirely. - Nostr inbound: intercept [FAVORITED]/[UNFAVORITED] markers in the live PM handler so they update theyFavoritedUs instead of rendering as chat text; mutual favorites can now form over Nostr. Delete the dead favorite-aware PM variant and ChatNostrCoordinator.handleFavoriteNotification (unwired, parsed a stale FAVORITE:TRUE|… format no sender emits). - NostrTransport.isPeerReachable: match short form regardless of incoming ID width — toggling an offline favorite (addressed by 64-hex noise key) was silently dropped with no reachable transport. - BLEService.sendPrivateMessage: normalize recipient to the short ID like sendFilePrivate, so a 64-hex target hits the existing Noise session instead of initiating a handshake with a 32-byte wire recipient ID. - /fav, /unfav: stop writing Data(hexString: peerID.id) — the 8-byte routing ID for mesh peers — into the favorites store as a "noise key", and stop double-sending the favorite notification; delegate to toggleFavorite with a proper state check. - FavoritesPersistenceService.updatePeerFavoritedUs: keep the stored nickname when the caller passes the "Unknown" placeholder. - Bump marketing version to 1.5.4. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Route DMs to mutual favorites via Nostr when a mesh-keyed peer goes offline Field-tested on device: with a DM window opened while the peer was on mesh (conversation keyed by the short 16-hex ID), walking out of range and sending failed instantly with "peer not reachable" even though the header showed the peer as Nostr-reachable (mutual favorite, npub known). sendPrivateMessage derived the favorites key as Data(hexString: peerID.id) — for a short mesh ID that is the 8-byte routing ID, never the noise key — so the mutual-favorite/Nostr-key checks always came up empty and the send failed before reaching MessageRouter. Conversations keyed by the full 64-hex noise-key ID (opened from the offline favorite row) were unaffected, which is why later tests appeared to work. Resolve the noise key properly (peerID.noiseKey, then the unified peer row, then the favorites store by derived short ID) and add a regression test for the mesh-keyed-peer-goes-offline case. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Label Nostr DMs from favorites with their stored nickname Field-tested: a DM delivered over the Nostr fallback rendered as "anon#678e" instead of the sender's name. The inbound handler named the sender via displayNameForNostrPubkey, which only knows geohash-scoped names — even though the pipeline had already resolved the sender's noise key (the conversation is keyed by it). When the conversation key carries a noise key, prefer the favorite's stored nickname; geohash DMs (nostr_ keys) keep the anon geo name. This also stops an inbound Nostr [FAVORITED] from overwriting the stored nickname with the anon fallback, since the same name feeds updatePeerFavoritedUs. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix courier path for offline favorites addressed by noise-key IDs Two Codex review findings, both the same ID-width confusion this PR targets, in the courier flow: - CourierDirectory.favoritesBacked resolved recipients only via getFavoriteStatus(forPeerID:), which requires a short 16-hex ID — offline favorites are addressed by the full 64-hex noise-key ID, so attemptCourierDeposit silently bailed for exactly the peers couriers exist to serve. The 64-hex ID now yields its own key directly. - openCourierEnvelope emitted the derived short mesh ID even when the sender has no live mesh identity, landing couriered mail in an unresolvable short-ID thread labeled "Unknown". Absent senders now emit the full noise-key ID so the message joins the stable favorite conversation; present senders keep the live short-ID thread. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
509 lines
21 KiB
Swift
509 lines
21 KiB
Swift
//
|
|
// NostrTransportTests.swift
|
|
// bitchat
|
|
//
|
|
// This is free and unencumbered software released into the public domain.
|
|
// For more information, see <https://unlicense.org>
|
|
//
|
|
|
|
import Foundation
|
|
import Testing
|
|
import BitFoundation
|
|
@testable import bitchat
|
|
|
|
@Suite("NostrTransport Tests")
|
|
struct NostrTransportTests {
|
|
typealias FavoriteRelationship = FavoritesPersistenceService.FavoriteRelationship
|
|
|
|
@Test("Warm cache marks full and short IDs reachable")
|
|
@MainActor
|
|
func reachabilityCacheWarmsFromFavorites() async throws {
|
|
let keychain = MockKeychain()
|
|
let idBridge = NostrIdentityBridge(keychain: keychain)
|
|
let recipient = try NostrIdentity.generate()
|
|
let noiseKey = Data((0..<32).map(UInt8.init))
|
|
let fullPeerID = PeerID(hexData: noiseKey)
|
|
let shortPeerID = fullPeerID.toShort()
|
|
let relationship = makeRelationship(
|
|
peerNoisePublicKey: noiseKey,
|
|
peerNostrPublicKey: recipient.npub,
|
|
peerNickname: "Alice"
|
|
)
|
|
let favorites = [noiseKey: relationship]
|
|
|
|
let transport = NostrTransport(
|
|
keychain: keychain,
|
|
idBridge: idBridge,
|
|
dependencies: makeDependencies(
|
|
loadFavorites: { favorites },
|
|
favoriteStatusForNoiseKey: { favorites[$0] },
|
|
favoriteStatusForPeerID: { $0 == shortPeerID ? relationship : nil },
|
|
currentIdentity: { nil }
|
|
)
|
|
)
|
|
|
|
// Offline favorites are addressed by the full 64-hex noise key, so
|
|
// both forms must resolve to the same reachability answer.
|
|
#expect(transport.isPeerReachable(fullPeerID))
|
|
#expect(transport.isPeerReachable(shortPeerID))
|
|
#expect(!transport.isPeerReachable(PeerID(str: "feedfeedfeedfeed")))
|
|
}
|
|
|
|
@Test("Favorite status notification refreshes reachability cache")
|
|
@MainActor
|
|
func favoriteStatusNotificationRefreshesReachability() async throws {
|
|
let keychain = MockKeychain()
|
|
let idBridge = NostrIdentityBridge(keychain: keychain)
|
|
let recipient = try NostrIdentity.generate()
|
|
let noiseKey = Data((32..<64).map(UInt8.init))
|
|
let peerID = PeerID(hexData: noiseKey).toShort()
|
|
let notificationCenter = NotificationCenter()
|
|
var favorites: [Data: FavoriteRelationship] = [:]
|
|
|
|
let transport = NostrTransport(
|
|
keychain: keychain,
|
|
idBridge: idBridge,
|
|
dependencies: makeDependencies(
|
|
notificationCenter: notificationCenter,
|
|
loadFavorites: { favorites },
|
|
favoriteStatusForNoiseKey: { favorites[$0] },
|
|
favoriteStatusForPeerID: { _ in favorites.values.first },
|
|
currentIdentity: { nil }
|
|
)
|
|
)
|
|
|
|
#expect(!transport.isPeerReachable(peerID))
|
|
|
|
favorites[noiseKey] = makeRelationship(
|
|
peerNoisePublicKey: noiseKey,
|
|
peerNostrPublicKey: recipient.npub,
|
|
peerNickname: "Bob"
|
|
)
|
|
notificationCenter.post(name: .favoriteStatusChanged, object: nil)
|
|
|
|
let didRefresh = await TestHelpers.waitUntil({ transport.isPeerReachable(peerID) }, timeout: 5.0)
|
|
#expect(didRefresh)
|
|
}
|
|
|
|
@Test("Private message resolves short peer ID and emits decryptable packet")
|
|
@MainActor
|
|
func sendPrivateMessageResolvesShortPeerID() async throws {
|
|
let keychain = MockKeychain()
|
|
let idBridge = NostrIdentityBridge(keychain: keychain)
|
|
let sender = try NostrIdentity.generate()
|
|
let recipient = try NostrIdentity.generate()
|
|
let noiseKey = Data((64..<96).map(UInt8.init))
|
|
let shortPeerID = PeerID(hexData: noiseKey).toShort()
|
|
let relationship = makeRelationship(
|
|
peerNoisePublicKey: noiseKey,
|
|
peerNostrPublicKey: recipient.npub,
|
|
peerNickname: "Carol"
|
|
)
|
|
let probe = NostrTransportProbe()
|
|
let transport = NostrTransport(
|
|
keychain: keychain,
|
|
idBridge: idBridge,
|
|
dependencies: makeDependencies(
|
|
favoriteStatusForNoiseKey: { _ in nil },
|
|
favoriteStatusForPeerID: { $0 == shortPeerID ? relationship : nil },
|
|
currentIdentity: { sender },
|
|
registerPendingGiftWrap: probe.recordPendingGiftWrap(id:),
|
|
sendEvent: probe.record(event:),
|
|
scheduleAfter: { delay, action in
|
|
probe.enqueueScheduledAction(delay: delay, action: action)
|
|
}
|
|
)
|
|
)
|
|
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
|
|
|
transport.sendPrivateMessage("hello over nostr", to: shortPeerID, recipientNickname: "Carol", messageID: "pm-1")
|
|
|
|
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: 5.0)
|
|
#expect(didSend)
|
|
let result = try decodeEmbeddedPayload(from: probe.sentEvents[0], recipient: recipient)
|
|
let privateMessage = try decodePrivateMessage(from: result.payload)
|
|
|
|
#expect(result.senderPubkey == sender.publicKeyHex)
|
|
#expect(privateMessage.messageID == "pm-1")
|
|
#expect(privateMessage.content == "hello over nostr")
|
|
#expect(result.packet.recipientID == shortPeerID.routingData)
|
|
#expect(probe.pendingGiftWrapIDs.isEmpty)
|
|
}
|
|
|
|
@Test("Favorite notification embeds current npub")
|
|
@MainActor
|
|
func sendFavoriteNotificationEmbedsCurrentIdentity() async throws {
|
|
let keychain = MockKeychain()
|
|
let idBridge = NostrIdentityBridge(keychain: keychain)
|
|
let sender = try NostrIdentity.generate()
|
|
let recipient = try NostrIdentity.generate()
|
|
let noiseKey = Data((96..<128).map(UInt8.init))
|
|
let fullPeerID = PeerID(hexData: noiseKey)
|
|
let relationship = makeRelationship(
|
|
peerNoisePublicKey: noiseKey,
|
|
peerNostrPublicKey: recipient.npub,
|
|
peerNickname: "Dan"
|
|
)
|
|
let probe = NostrTransportProbe()
|
|
let transport = NostrTransport(
|
|
keychain: keychain,
|
|
idBridge: idBridge,
|
|
dependencies: makeDependencies(
|
|
favoriteStatusForNoiseKey: { $0 == noiseKey ? relationship : nil },
|
|
favoriteStatusForPeerID: { _ in nil },
|
|
currentIdentity: { sender },
|
|
registerPendingGiftWrap: probe.recordPendingGiftWrap(id:),
|
|
sendEvent: probe.record(event:),
|
|
scheduleAfter: { delay, action in
|
|
probe.enqueueScheduledAction(delay: delay, action: action)
|
|
}
|
|
)
|
|
)
|
|
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
|
|
|
transport.sendFavoriteNotification(to: fullPeerID, isFavorite: true)
|
|
|
|
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: 5.0)
|
|
#expect(didSend)
|
|
let result = try decodeEmbeddedPayload(from: probe.sentEvents[0], recipient: recipient)
|
|
let privateMessage = try decodePrivateMessage(from: result.payload)
|
|
|
|
#expect(privateMessage.content == "[FAVORITED]:\(sender.npub)")
|
|
}
|
|
|
|
@Test("Delivery ACK encodes delivered payload type")
|
|
@MainActor
|
|
func sendDeliveryAckEmitsDeliveredAck() async throws {
|
|
let keychain = MockKeychain()
|
|
let idBridge = NostrIdentityBridge(keychain: keychain)
|
|
let sender = try NostrIdentity.generate()
|
|
let recipient = try NostrIdentity.generate()
|
|
let noiseKey = Data((128..<160).map(UInt8.init))
|
|
let fullPeerID = PeerID(hexData: noiseKey)
|
|
let relationship = makeRelationship(
|
|
peerNoisePublicKey: noiseKey,
|
|
peerNostrPublicKey: recipient.npub,
|
|
peerNickname: "Eve"
|
|
)
|
|
let probe = NostrTransportProbe()
|
|
let transport = NostrTransport(
|
|
keychain: keychain,
|
|
idBridge: idBridge,
|
|
dependencies: makeDependencies(
|
|
favoriteStatusForNoiseKey: { $0 == noiseKey ? relationship : nil },
|
|
favoriteStatusForPeerID: { _ in nil },
|
|
currentIdentity: { sender },
|
|
registerPendingGiftWrap: probe.recordPendingGiftWrap(id:),
|
|
sendEvent: probe.record(event:),
|
|
scheduleAfter: { delay, action in
|
|
probe.enqueueScheduledAction(delay: delay, action: action)
|
|
}
|
|
)
|
|
)
|
|
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
|
|
|
transport.sendDeliveryAck(for: "ack-1", to: fullPeerID)
|
|
|
|
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: 5.0)
|
|
#expect(didSend)
|
|
let result = try decodeEmbeddedPayload(from: probe.sentEvents[0], recipient: recipient)
|
|
|
|
#expect(result.payload.type == .delivered)
|
|
#expect(String(data: result.payload.data, encoding: .utf8) == "ack-1")
|
|
#expect(result.packet.recipientID == fullPeerID.toShort().routingData)
|
|
}
|
|
|
|
@Test("Geohash private message registers pending gift wrap")
|
|
@MainActor
|
|
func sendPrivateMessageGeohashRegistersPendingGiftWrap() async throws {
|
|
let keychain = MockKeychain()
|
|
let idBridge = NostrIdentityBridge(keychain: keychain)
|
|
let sender = try NostrIdentity.generate()
|
|
let recipient = try NostrIdentity.generate()
|
|
let probe = NostrTransportProbe()
|
|
let transport = NostrTransport(
|
|
keychain: keychain,
|
|
idBridge: idBridge,
|
|
dependencies: makeDependencies(
|
|
currentIdentity: { sender },
|
|
registerPendingGiftWrap: probe.recordPendingGiftWrap(id:),
|
|
sendEvent: probe.record(event:),
|
|
scheduleAfter: { delay, action in
|
|
probe.enqueueScheduledAction(delay: delay, action: action)
|
|
}
|
|
)
|
|
)
|
|
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
|
|
|
transport.sendPrivateMessageGeohash(
|
|
content: "geo hello",
|
|
toRecipientHex: recipient.publicKeyHex,
|
|
from: sender,
|
|
messageID: "geo-1"
|
|
)
|
|
|
|
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: 5.0)
|
|
#expect(didSend)
|
|
let event = probe.sentEvents[0]
|
|
let result = try decodeEmbeddedPayload(from: event, recipient: recipient)
|
|
let privateMessage = try decodePrivateMessage(from: result.payload)
|
|
|
|
#expect(privateMessage.messageID == "geo-1")
|
|
#expect(privateMessage.content == "geo hello")
|
|
#expect(result.packet.recipientID == nil)
|
|
#expect(probe.pendingGiftWrapIDs == [event.id])
|
|
}
|
|
|
|
@Test("Read receipt queue sends in order and waits for scheduler")
|
|
@MainActor
|
|
func readReceiptQueueThrottlesSequentially() async throws {
|
|
let keychain = MockKeychain()
|
|
let idBridge = NostrIdentityBridge(keychain: keychain)
|
|
let sender = try NostrIdentity.generate()
|
|
let recipient = try NostrIdentity.generate()
|
|
let noiseKey = Data((160..<192).map(UInt8.init))
|
|
let fullPeerID = PeerID(hexData: noiseKey)
|
|
let relationship = makeRelationship(
|
|
peerNoisePublicKey: noiseKey,
|
|
peerNostrPublicKey: recipient.npub,
|
|
peerNickname: "Frank"
|
|
)
|
|
let probe = NostrTransportProbe()
|
|
let transport = NostrTransport(
|
|
keychain: keychain,
|
|
idBridge: idBridge,
|
|
dependencies: makeDependencies(
|
|
favoriteStatusForNoiseKey: { $0 == noiseKey ? relationship : nil },
|
|
favoriteStatusForPeerID: { _ in nil },
|
|
currentIdentity: { sender },
|
|
registerPendingGiftWrap: probe.recordPendingGiftWrap(id:),
|
|
sendEvent: probe.record(event:),
|
|
scheduleAfter: { delay, action in
|
|
probe.enqueueScheduledAction(delay: delay, action: action)
|
|
}
|
|
)
|
|
)
|
|
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
|
|
|
let first = ReadReceipt(originalMessageID: "read-1", readerID: transport.myPeerID, readerNickname: "Me")
|
|
let second = ReadReceipt(originalMessageID: "read-2", readerID: transport.myPeerID, readerNickname: "Me")
|
|
|
|
transport.sendReadReceipt(first, to: fullPeerID)
|
|
transport.sendReadReceipt(second, to: fullPeerID)
|
|
|
|
let readReceiptTimeout: TimeInterval = 5.0
|
|
let sentFirst = await TestHelpers.waitUntil({ probe.sentEvents.count >= 1 }, timeout: readReceiptTimeout)
|
|
try #require(sentFirst, "Expected first queued read receipt event")
|
|
let scheduledThrottle = await TestHelpers.waitUntil({ probe.scheduledActionCount == 1 }, timeout: readReceiptTimeout)
|
|
try #require(scheduledThrottle, "Expected queued throttle action after first read receipt")
|
|
let firstEvent = try #require(probe.sentEvents.first, "Expected first queued read receipt event")
|
|
let firstPayload = try decodeEmbeddedPayload(from: firstEvent, recipient: recipient).payload
|
|
#expect(firstPayload.type == .readReceipt)
|
|
#expect(String(data: firstPayload.data, encoding: .utf8) == "read-1")
|
|
|
|
try #require(probe.runNextScheduledAction(), "Expected queued throttle action after first read receipt")
|
|
|
|
let sentSecond = await TestHelpers.waitUntil({ probe.sentEvents.count >= 2 }, timeout: readReceiptTimeout)
|
|
try #require(sentSecond, "Expected second read receipt after running throttle action")
|
|
let secondEvent = try #require(probe.sentEvents.last, "Expected second queued read receipt event")
|
|
let secondPayload = try decodeEmbeddedPayload(from: secondEvent, recipient: recipient).payload
|
|
#expect(secondPayload.type == .readReceipt)
|
|
#expect(String(data: secondPayload.data, encoding: .utf8) == "read-2")
|
|
withExtendedLifetime(transport) {}
|
|
}
|
|
|
|
// These thread-safety tests must hammer from the dispatch pool
|
|
// (concurrentPerform), NOT a task group: transport calls block in
|
|
// queue.sync, and a 100-task group runs them on the Swift Concurrency
|
|
// cooperative pool — one thread per core, just 3 on CI runners. Parking
|
|
// every cooperative thread in a blocking sync violates the forward
|
|
// progress contract and wedged dispatch on the CI runners' macOS,
|
|
// deadlocking the whole app suite into the 15-minute job timeout
|
|
// (watchdog stacks: NostrTransport.isPeerReachable syncs holding all
|
|
// pool threads). Blocking is legal on dispatch worker threads.
|
|
@Test("Concurrent read receipt enqueue does not crash")
|
|
@MainActor
|
|
func concurrentReadReceiptEnqueue() async throws {
|
|
let keychain = MockKeychain()
|
|
let idBridge = NostrIdentityBridge(keychain: keychain)
|
|
let transport = NostrTransport(keychain: keychain, idBridge: idBridge)
|
|
let iterations = 100
|
|
|
|
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
|
|
DispatchQueue.global().async {
|
|
DispatchQueue.concurrentPerform(iterations: iterations) { i in
|
|
let receipt = ReadReceipt(
|
|
originalMessageID: UUID().uuidString,
|
|
readerID: PeerID(str: String(format: "%016x", i)),
|
|
readerNickname: "Reader\(i)"
|
|
)
|
|
let peerID = PeerID(str: String(format: "%016x", i))
|
|
transport.sendReadReceipt(receipt, to: peerID)
|
|
}
|
|
continuation.resume()
|
|
}
|
|
}
|
|
withExtendedLifetime(transport) {}
|
|
}
|
|
|
|
@Test("isPeerReachable is thread safe")
|
|
@MainActor
|
|
func isPeerReachableThreadSafety() async throws {
|
|
let keychain = MockKeychain()
|
|
let idBridge = NostrIdentityBridge(keychain: keychain)
|
|
let transport = NostrTransport(keychain: keychain, idBridge: idBridge)
|
|
let iterations = 100
|
|
|
|
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
|
|
DispatchQueue.global().async {
|
|
DispatchQueue.concurrentPerform(iterations: iterations) { i in
|
|
let peerID = PeerID(str: String(format: "%016x", i))
|
|
#expect(transport.isPeerReachable(peerID) == false)
|
|
}
|
|
continuation.resume()
|
|
}
|
|
}
|
|
withExtendedLifetime(transport) {}
|
|
}
|
|
|
|
@MainActor
|
|
private func makeDependencies(
|
|
notificationCenter: NotificationCenter = NotificationCenter(),
|
|
loadFavorites: @escaping @MainActor () -> [Data: FavoriteRelationship] = { [:] },
|
|
favoriteStatusForNoiseKey: @escaping @MainActor (Data) -> FavoriteRelationship? = { _ in nil },
|
|
favoriteStatusForPeerID: @escaping @MainActor (PeerID) -> FavoriteRelationship? = { _ in nil },
|
|
currentIdentity: @escaping @MainActor () throws -> NostrIdentity? = { nil },
|
|
registerPendingGiftWrap: @escaping @MainActor (String) -> Void = { _ in },
|
|
sendEvent: @escaping @MainActor (NostrEvent) -> Void = { _ in },
|
|
scheduleAfter: @escaping @Sendable (TimeInterval, @escaping @Sendable () -> Void) -> Void = { _, _ in }
|
|
) -> NostrTransport.Dependencies {
|
|
NostrTransport.Dependencies(
|
|
notificationCenter: notificationCenter,
|
|
loadFavorites: loadFavorites,
|
|
favoriteStatusForNoiseKey: favoriteStatusForNoiseKey,
|
|
favoriteStatusForPeerID: favoriteStatusForPeerID,
|
|
currentIdentity: currentIdentity,
|
|
registerPendingGiftWrap: registerPendingGiftWrap,
|
|
sendEvent: sendEvent,
|
|
scheduleAfter: scheduleAfter
|
|
)
|
|
}
|
|
|
|
private func makeRelationship(
|
|
peerNoisePublicKey: Data,
|
|
peerNostrPublicKey: String?,
|
|
peerNickname: String
|
|
) -> FavoriteRelationship {
|
|
FavoriteRelationship(
|
|
peerNoisePublicKey: peerNoisePublicKey,
|
|
peerNostrPublicKey: peerNostrPublicKey,
|
|
peerNickname: peerNickname,
|
|
isFavorite: true,
|
|
theyFavoritedUs: true,
|
|
favoritedAt: Date(timeIntervalSince1970: 1),
|
|
lastUpdated: Date(timeIntervalSince1970: 2)
|
|
)
|
|
}
|
|
|
|
private func decodeEmbeddedPayload(
|
|
from event: NostrEvent,
|
|
recipient: NostrIdentity
|
|
) throws -> (packet: BitchatPacket, payload: NoisePayload, senderPubkey: String) {
|
|
let (content, senderPubkey, _) = try NostrProtocol.decryptPrivateMessage(
|
|
giftWrap: event,
|
|
recipientIdentity: recipient
|
|
)
|
|
guard content.hasPrefix("bitchat1:") else {
|
|
throw NostrTransportTestError.invalidEmbeddedContent
|
|
}
|
|
let encoded = String(content.dropFirst("bitchat1:".count))
|
|
guard let packetData = base64URLDecode(encoded),
|
|
let packet = BitchatPacket.from(packetData),
|
|
let payload = NoisePayload.decode(packet.payload) else {
|
|
throw NostrTransportTestError.invalidPacket
|
|
}
|
|
return (packet, payload, senderPubkey)
|
|
}
|
|
|
|
private func decodePrivateMessage(from payload: NoisePayload) throws -> PrivateMessagePacket {
|
|
guard payload.type == .privateMessage,
|
|
let message = PrivateMessagePacket.decode(from: payload.data) else {
|
|
throw NostrTransportTestError.invalidPrivateMessage
|
|
}
|
|
return message
|
|
}
|
|
}
|
|
|
|
private enum NostrTransportTestError: Error {
|
|
case invalidEmbeddedContent
|
|
case invalidPacket
|
|
case invalidPrivateMessage
|
|
}
|
|
|
|
private func base64URLDecode(_ string: String) -> Data? {
|
|
var candidate = string
|
|
let padding = (4 - (candidate.count % 4)) % 4
|
|
if padding > 0 {
|
|
candidate += String(repeating: "=", count: padding)
|
|
}
|
|
candidate = candidate
|
|
.replacingOccurrences(of: "-", with: "+")
|
|
.replacingOccurrences(of: "_", with: "/")
|
|
return Data(base64Encoded: candidate)
|
|
}
|
|
|
|
private final class NostrTransportProbe: @unchecked Sendable {
|
|
private let lock = NSLock()
|
|
private var sentEventsStorage: [NostrEvent] = []
|
|
private var pendingGiftWrapIDsStorage: [String] = []
|
|
private var scheduledActionsStorage: [(@Sendable () -> Void)] = []
|
|
|
|
var sentEvents: [NostrEvent] {
|
|
lock.lock()
|
|
defer { lock.unlock() }
|
|
return sentEventsStorage
|
|
}
|
|
|
|
var pendingGiftWrapIDs: [String] {
|
|
lock.lock()
|
|
defer { lock.unlock() }
|
|
return pendingGiftWrapIDsStorage
|
|
}
|
|
|
|
var scheduledActionCount: Int {
|
|
lock.lock()
|
|
defer { lock.unlock() }
|
|
return scheduledActionsStorage.count
|
|
}
|
|
|
|
func record(event: NostrEvent) {
|
|
lock.lock()
|
|
sentEventsStorage.append(event)
|
|
lock.unlock()
|
|
}
|
|
|
|
func recordPendingGiftWrap(id: String) {
|
|
lock.lock()
|
|
pendingGiftWrapIDsStorage.append(id)
|
|
lock.unlock()
|
|
}
|
|
|
|
func enqueueScheduledAction(delay: TimeInterval, action: @escaping @Sendable () -> Void) {
|
|
_ = delay
|
|
lock.lock()
|
|
scheduledActionsStorage.append(action)
|
|
lock.unlock()
|
|
}
|
|
|
|
@discardableResult
|
|
func runNextScheduledAction() -> Bool {
|
|
let action: (@Sendable () -> Void)?
|
|
lock.lock()
|
|
action = scheduledActionsStorage.isEmpty ? nil : scheduledActionsStorage.removeFirst()
|
|
lock.unlock()
|
|
guard let action else { return false }
|
|
action()
|
|
return true
|
|
}
|
|
}
|