mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-25 10:45:20 +00:00
* Mesh bridging: stitch nearby mesh islands over Nostr, courier drops, settings surface Three features plus a UI consolidation, all opt-in behind a new Bridge toggle: Channel bridge: while bridging, outgoing public mesh messages are also signed (with a derived, unlinkable per-cell Nostr identity) as kind-20000 events tagged #r with the local geohash-6 cell and published to the cell's deterministic geo relays; mesh-only peers deposit via new toBridge/fromBridge carrier directions through a bridge gateway (bridge + gateway toggles). Remote islands' events render into the mesh timeline marked with a network glyph. Events carry the original mesh message ID so the store's insert-by-ID absorbs radio/bridge duplicates in either order. Loop prevention mirrors GatewayService (three BoundedIDSet caches + skip-if-seen-locally + budgets). Nothing crosses a bridge unless its author signed it for the bridge; a per-message "nearby only" composer toggle keeps a message radio-only. Courier over the bridge: sealed courier envelopes park on default relays as kind-1401 drops tagged #x with their day-rotating recipient tag (NIP-40 expiry), signed by per-drop throwaway keys. Recipients subscribe for their own candidate tags; bridge gateways watch verified local peers' tags and hand matching drops over as directed courier packets. DM delivery to known peers stops requiring a physical courier encounter; the Noise-X seal never opens in transit. Presence: kind-20001 heartbeats on the rendezvous feed a "people across the bridge" count in the header (approximate: local participants subtracted by radio-copy attribution). Settings/Info: AppInfoView is now a segmented Settings/Info sheet. Settings hosts appearance, voice (fixes the duplicated Voice section), a Connectivity section (bridge + gateway + Tor toggles, the latter two moved out of the location sheet), and a confirmed panic-wipe button. New announce TLV 0x06 advertises the gateway's rendezvous cell; PeerCapabilities gains .bridge. i18n: 23 new keys across all 29 locales; coverage tests green. Tests: 50 new app tests + 3 BitFoundation tests; full suite 1445 green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Settings polish: one toggle style, sticky Info-first tab, location access in Settings - The live-voice toggle now uses the same settings card + IRC pill as the connectivity toggles (settingToggle, renamed from connectivityToggle). - Segmented control orders Info first; the selected pane persists across opens (AppStorage), so first-ever open lands on Info and afterwards the sheet reopens where it was left. - "remove location access" moved from the channels sheet into the Settings Connectivity section (same key, still deep-links to system settings). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Location UX + copy: state-aware access control, honest empty state, clearer bridge/gateway text - Settings' location control now covers all three permission states: grant (real prompt, only possible while never-asked), open-system-settings when denied, remove-access when granted. The channels sheet keeps its own grant path for people who start there. - The channels list no longer spins forever without permission; it shows "grant location access to find nearby channels" instead (new key, 29 locales). - Bridge and gateway subtitles rewritten for clarity; the gateway subtitle moved to a new key since it now carries bridge traffic, and the old geohash-only key is deleted. The word "user" is banned from copy in every locale ("this person is blocked"). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Field-test fixes: dedupe relay-connectivity triggers, throttle presence, log bridge decisions First on-device run confirmed publishes accepted and the subscription delivering, but exposed trigger spam: NostrRelayManager's isConnected re-emits per relay recompute, so presence published 5x/second and the courier-drop subscription rebuilt 6x in 300ms. removeDuplicates() on the sinks + a 30s presence throttle (same-second heartbeats are byte-identical events anyway). Also: injection/skip/downlink now log under 🌉 so field verification is observable — the first test looked silent precisely because dedup correctly suppressed same-island bridged copies. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix restart self-echo: recognize own rendezvous events by derived pubkey Second field run proved bidirectional bridging live (~1-2s Mac<->iPhone via Tor) but caught a bug: relay backfill after an app relaunch re-delivered the device's own pre-restart events, and with the in-memory published-ID cache wiped they rendered as bridged copies of your own messages. The rendezvous identity is deterministically derived per cell, so self-recognition by pubkey needs no cache and survives restarts; own events are also marked never-downlink. Regression test simulates the fresh-launch state. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * People sheet: mesh, bridge, and groups in one list The header's bridged count had no matching faces anywhere — the people sheet only knew mesh peers. BridgeService now publishes named participants (nickname from message tags, geohash-style #last4 disambiguation, presence keeps a known name alive) and the mesh people sheet gains an "across the bridge" section between mesh peers and groups. Display-only rows in v1 (bridged identities have no DM route yet). Two new catalog keys x29 locales; also normalizes one out-of-sort-order entry inherited from a hand-edited key on main. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Header: one people icon, one count, one sheet Fold the bridged-people count into the main person.2.fill count instead of a second network-glyph counter; the merged people sheet (mesh / across the bridge / groups) is the breakdown. VoiceOver still announces how many of the total are across the bridge. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * People sheet symmetry: #mesh section header, no active count Every section now gets the same glyph+label header shape (shared PeopleSectionHeader): #mesh over the peer list, across-the-bridge over bridged people. The "N active" line is gone (mesh); location channels keep their geohash subtitle. Dead subtitle/count helpers removed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * One switch: the bridge toggle drives all internet sharing Field feedback: two toggles (bridge + gateway) with an invisible dependency was a trap — bridged messages silently never reached mesh-only neighbors unless a second lever was found and flipped. Collapsed to a single switch that does the right thing for your situation: - Bridge ON + internet: your messages cross, you see the bridge, AND your device serves its island — accepts toBridge deposits, carries remote messages onto the radio, watches courier drops for verified local peers, advertises the cell, and runs the geohash-channel gateway. - Bridge ON, no internet: you ride whoever nearby is serving. - Bridge OFF: nothing of yours crosses; radio reception of bridged traffic stays passive and free. With every online bridger serving, downlink gets a 0.2-1.5s jittered holdoff + send-time suppression recheck so co-located gateways don't burn duplicate airtime (two-gateway test included). The internet-gateway card is gone from Settings (GatewayService now follows the bridge switch, with launch-time migration); its orphaned catalog keys deleted and the bridge subtitle broadened across all 29 locales. Also: MeshPeerList's empty state ("nobody around...") aligned to the section row rhythm. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Bridge pumps its own location; fix centered people sheet; stop drop-subscription churn Field session 3 found the bridge silently cell-less: it read availableChannels passively, which only flow while some other feature (channels sheet, location notes, geo sampling) happens to pump location — turn those off and the bridge never gets a rendezvous. BridgeService now requests a one-shot fix whenever it's enabled without a cell (and piggybacks one on the presence timer so moving devices migrate cells). Also from the session: the people sheet's scroll content hugged its widest child and got centered on iPhone when the list was empty — pinned to full width, leading. And the courier-drop subscription rebuilt every ~60s on verified announces despite an unchanged tag set — now resubscribes only when the tags actually change. (Also merges origin/main: keychain test isolation #1413.) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix launch race: bridge reacts to the permission callback, retries cell-less Field session 4: the launch-time location request ran before the CoreLocation authorization callback delivered, so refreshChannels() silently no-opped (it requires .authorized) and nothing ever retried — the bridge stayed cell-less all session. Three layers now close it: - a $permissionState sink re-enters refreshRendezvous the moment authorization resolves (the fast path), - the maintenance timer arms even without a cell and retries the full rendezvous refresh (the backstop; it previously required a cell, which made it useless for exactly this failure), - flipping the bridge switch while never-asked triggers the location prompt — that's the user-initiated moment for it. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * People sheet: one header style for every section; bridged people visible while own bridge is off GroupChatList's header now uses the shared PeopleSectionHeader (glyph + label, same size/padding as #mesh and across-the-bridge; keeps its key and header trait). Bridge section and the header count are no longer gated on this device's own toggle: bridged people arrive over passive radio from a serving neighbor, and whoever is visible in the timeline belongs in the sheet and the count. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * People sheet: equalize the first section's gap MeshPeerList's first row kept a legacy 10pt top bump from when nothing sat above it, and the outer VStack's 6pt inter-child spacing applied between the #mesh header and the list but not inside the other sections. Both gone: sections own their rhythm (header 12/4, rows 4), spacing 0 outside. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * People sheet: rows drop their leading glyphs — the section header carries the type Mesh rows lose the per-state transport icon (connected/relayed/nostr/ offline), bridge rows the network glyph, group rows the person.3 icon. Trailing state badges (star, lock, verified, unread, blocked, crown) stay, and the row accessibility description still announces connection state, so VoiceOver loses nothing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Remove dead code left behind by the Settings|Info consolidation Periphery (--strict) flagged five leftovers on this branch: - LocationChannelsModel.setGatewayEnabled: the standalone internet-gateway toggle is gone (the bridge switch drives internet sharing), so nothing calls it; the gatewayEnabled published property stays for the header dot. - AppInfoView Strings.Location title/enable/openSettings: the old Location section's header and permission buttons no longer exist. Their orphaned Localizable.xcstrings entries go with them (the gateway-toggle keys were already pruned). - BridgePeopleList's appTheme environment value was never read. The sixth CI finding (PrekeyBundleStore.StoredBundle.noiseKey assign-only) is a Periphery flake: the property is read in loadFromDisk, the finding didn't reproduce locally or on the next CI run of unchanged code. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * People sheet: mesh rows get their transport glyph back The mesh section is the one heterogeneous list — the leading icon encodes HOW a peer is reachable (radio / relayed / nostr-only / offline), which the header can't say. Bridge and group rows stay glyph-free. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix courier drop skipped by stale BLE reachability; periodic deposit sweep Field test: a DM sent seconds after the recipient's radio vanished still saw them as "reachable" (60s verified retention), so canDeliverPromptly held, every deposit was skipped, and the message sat spooled with no retry path. MessageRouter now sweeps its outbox every 2 minutes and publishes bridge drops for messages whose recipient no transport can promptly reach; the drop layer's message-ID dedup makes the sweep idempotent. Regression test reproduces the exact field sequence. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Show "carried" when a message ships as a bridge drop Field feedback: dropped DMs delivered but the sender saw nothing — the drop path never fired onMessageCarried, and the recipient's delivery ack has no radio route back until the peers next share a transport. depositDrop now reports whether a fresh drop was sealed and the router marks the message carried (📦) on both the send path and the sweep; the ack still upgrades it to delivered whenever a route exists. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix locale word order: offline tag after name in DM header; localized "ago" The private-chat header rendered the localized offline word in the availability-glyph slot, before the name — "sin conexión bob". Offline now shows the same dimmed person glyph the mesh list uses, with the word as a small trailing tag after the name and lock, so it reads correctly in every locale. Full sweep of views found one more composition bug: notice timestamps glued English "ago" onto a localized duration; now the whole phrase comes from RelativeDateTimeFormatter (same as the "fades" label). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * DM header offline state: icon only The availability slot now reads uniformly as a glyph (radio / relayed / globe / dimmed person), matching the mesh list; the text tag is gone. VoiceOver still announces "offline" via the glyph's accessibility label. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Offline glyph: slashed antenna instead of dimmed person Offline is now the visual negation of connected (same antenna glyph, slashed) in both the DM header and mesh list rows; a generic person icon didn't say "unreachable". 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>
595 lines
22 KiB
Swift
595 lines
22 KiB
Swift
//
|
|
// BridgeServiceTests.swift
|
|
// bitchat
|
|
//
|
|
// This is free and unencumbered software released into the public domain.
|
|
// For more information, see <https://unlicense.org>
|
|
//
|
|
|
|
import BitFoundation
|
|
import Foundation
|
|
import Testing
|
|
@testable import bitchat
|
|
|
|
@Suite("Mesh bridge policy")
|
|
@MainActor
|
|
struct BridgeServiceTests {
|
|
private static let cell = "u4pruy"
|
|
|
|
/// Closure-injected harness around `BridgeService` recording every side
|
|
/// effect, with a controllable clock, location, and connectivity.
|
|
@MainActor
|
|
private final class Fixture {
|
|
private final class ClockBox {
|
|
var now = Date()
|
|
}
|
|
|
|
var relaysConnected = true
|
|
var locationCell: String? = BridgeServiceTests.cell
|
|
var meshAdvertisedCell: String?
|
|
var bridgePeers: [PeerID] = []
|
|
var sendSucceeds = true
|
|
var locallySeenMessageIDs: Set<String> = []
|
|
var nickname = "tester"
|
|
|
|
private(set) var published: [(event: NostrEvent, cell: String)] = []
|
|
|
|
/// Published chat messages only — the fixture's own presence
|
|
/// heartbeats (kind 20001, sent on enable) are filtered out.
|
|
var publishedMessages: [(event: NostrEvent, cell: String)] {
|
|
published.filter { $0.event.kind == NostrProtocol.EventKind.ephemeralEvent.rawValue }
|
|
}
|
|
private(set) var broadcasts: [Data] = []
|
|
private(set) var injected: [BridgeService.InboundBridgeMessage] = []
|
|
private(set) var uplinkSends: [(payload: Data, peer: PeerID)] = []
|
|
private(set) var openedSubscriptions: [[String]] = []
|
|
private(set) var closedSubscriptions = 0
|
|
private(set) var enabledChanges: [Bool] = []
|
|
private(set) var locationFixRequests = 0
|
|
private(set) var cellChanges: [String?] = []
|
|
private(set) var scheduledTimers: [(delay: TimeInterval, work: @MainActor () -> Void)] = []
|
|
|
|
private let clock = ClockBox()
|
|
let identity: NostrIdentity
|
|
let defaults: UserDefaults
|
|
let service: BridgeService
|
|
|
|
init(enabled: Bool = true) {
|
|
let suite = "BridgeServiceTests-\(UUID().uuidString)"
|
|
defaults = UserDefaults(suiteName: suite)!
|
|
defaults.removePersistentDomain(forName: suite)
|
|
identity = try! NostrIdentity.generate()
|
|
let clock = clock
|
|
service = BridgeService(defaults: defaults) { clock.now }
|
|
service.publishToRelays = { [weak self] event, cell in
|
|
self?.published.append((event, cell))
|
|
}
|
|
service.openSubscription = { [weak self] cells in
|
|
self?.openedSubscriptions.append(cells)
|
|
}
|
|
service.closeSubscription = { [weak self] in
|
|
self?.closedSubscriptions += 1
|
|
}
|
|
service.relaysConnected = { [weak self] in self?.relaysConnected ?? false }
|
|
service.locationCell = { [weak self] in self?.locationCell }
|
|
service.requestLocationFix = { [weak self] in self?.locationFixRequests += 1 }
|
|
service.meshAdvertisedCell = { [weak self] in self?.meshAdvertisedCell }
|
|
service.sendToBridgePeer = { [weak self] payload, peer in
|
|
guard let self, self.sendSucceeds else { return false }
|
|
self.uplinkSends.append((payload, peer))
|
|
return true
|
|
}
|
|
service.availableBridgePeers = { [weak self] in self?.bridgePeers ?? [] }
|
|
service.broadcastToMesh = { [weak self] payload in
|
|
self?.broadcasts.append(payload)
|
|
}
|
|
service.injectInbound = { [weak self] message in
|
|
self?.injected.append(message)
|
|
}
|
|
service.isMessageSeenLocally = { [weak self] id in
|
|
self?.locallySeenMessageIDs.contains(id) ?? false
|
|
}
|
|
service.deriveIdentity = { [weak self] _ in
|
|
guard let self else { throw NostrError.invalidEvent }
|
|
return self.identity
|
|
}
|
|
service.myNickname = { [weak self] in self?.nickname ?? "" }
|
|
service.onEnabledChanged = { [weak self] enabled in self?.enabledChanges.append(enabled) }
|
|
service.onActiveCellChanged = { [weak self] cell in self?.cellChanges.append(cell) }
|
|
service.scheduleTimer = { [weak self] delay, work in
|
|
self?.scheduledTimers.append((delay, work))
|
|
}
|
|
if enabled {
|
|
service.setEnabled(true)
|
|
}
|
|
}
|
|
|
|
func advance(_ seconds: TimeInterval) {
|
|
clock.now = clock.now.addingTimeInterval(seconds)
|
|
}
|
|
|
|
func fireScheduledTimers() {
|
|
let due = scheduledTimers
|
|
scheduledTimers.removeAll()
|
|
for item in due { item.work() }
|
|
}
|
|
}
|
|
|
|
// MARK: Event helpers
|
|
|
|
private func makeRemoteEvent(
|
|
cell: String = BridgeServiceTests.cell,
|
|
content: String = "hi \(UUID().uuidString.prefix(8))",
|
|
meshMessageID: String? = UUID().uuidString
|
|
) throws -> NostrEvent {
|
|
let identity = try NostrIdentity.generate()
|
|
return try NostrProtocol.createBridgeMeshEvent(
|
|
content: content,
|
|
cell: cell,
|
|
senderIdentity: identity,
|
|
nickname: "remote",
|
|
meshMessageID: meshMessageID
|
|
)
|
|
}
|
|
|
|
private func makePresenceEvent(cell: String = BridgeServiceTests.cell) throws -> NostrEvent {
|
|
try NostrProtocol.createBridgePresenceEvent(cell: cell, senderIdentity: NostrIdentity.generate())
|
|
}
|
|
|
|
private func carrier(
|
|
_ event: NostrEvent,
|
|
direction: NostrCarrierPacket.Direction,
|
|
cell: String = BridgeServiceTests.cell
|
|
) throws -> NostrCarrierPacket {
|
|
try #require(NostrCarrierPacket(direction: direction, geohash: cell, event: event))
|
|
}
|
|
|
|
// MARK: - Lifecycle & rendezvous
|
|
|
|
@Test func enablingOpensSubscriptionForCellAndNeighbors() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
|
|
#expect(fixture.service.activeCell == Self.cell)
|
|
let cells = try #require(fixture.openedSubscriptions.first)
|
|
#expect(cells.first == Self.cell)
|
|
#expect(cells.count == 9) // own cell + 8 neighbors
|
|
#expect(fixture.service.subscribedCells.count == 9)
|
|
}
|
|
|
|
@Test func missingCellRequestsALocationFix() {
|
|
// Field bug: the bridge waited passively for availableChannels,
|
|
// which only flow while some other feature pumps location. Bridging
|
|
// without a cell must ask for a fix itself.
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.locationCell = nil
|
|
fixture.service.refreshRendezvous()
|
|
|
|
#expect(fixture.locationFixRequests >= 1)
|
|
#expect(fixture.service.activeCell == nil)
|
|
|
|
// The fix lands, channels flow, and the sink re-enters here:
|
|
fixture.locationCell = Self.cell
|
|
fixture.service.refreshRendezvous()
|
|
#expect(fixture.service.activeCell == Self.cell)
|
|
}
|
|
|
|
@Test func noLocationFallsBackToMeshAdvertisedCell() {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.locationCell = nil
|
|
fixture.meshAdvertisedCell = "u4prux"
|
|
fixture.service.refreshRendezvous()
|
|
|
|
#expect(fixture.service.activeCell == "u4prux")
|
|
}
|
|
|
|
@Test func disablingClosesSubscriptionAndClearsState() {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
fixture.service.setEnabled(false)
|
|
|
|
#expect(fixture.closedSubscriptions >= 1)
|
|
#expect(fixture.service.activeCell == nil)
|
|
#expect(fixture.service.bridgedPeerCount == 0)
|
|
}
|
|
|
|
@Test func togglePersistsAcrossInstances() {
|
|
let fixture = Fixture(enabled: true)
|
|
let revived = BridgeService(defaults: fixture.defaults)
|
|
#expect(revived.isEnabled)
|
|
}
|
|
|
|
// MARK: - Outgoing
|
|
|
|
@Test func outgoingPublishesSignedRendezvousEventWithMeshMessageID() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
let messageID = UUID().uuidString
|
|
|
|
fixture.service.bridgeOutgoing(content: "hello hill", messageID: messageID)
|
|
|
|
let published = try #require(fixture.published.last)
|
|
#expect(published.cell == Self.cell)
|
|
#expect(published.event.isValidSignature())
|
|
#expect(published.event.content == "hello hill")
|
|
#expect(published.event.tags.contains(["r", Self.cell]))
|
|
#expect(published.event.tags.contains(["m", messageID]))
|
|
#expect(published.event.tags.contains(["n", "tester"]))
|
|
}
|
|
|
|
@Test func nearbyOnlySuppressesTheBridgedCopy() {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
fixture.service.nearbyOnly = true
|
|
|
|
fixture.service.bridgeOutgoing(content: "just us", messageID: UUID().uuidString)
|
|
|
|
#expect(fixture.publishedMessages.isEmpty)
|
|
#expect(fixture.uplinkSends.isEmpty)
|
|
}
|
|
|
|
@Test func outgoingWithoutRelaysDepositsWithBridgePeer() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
fixture.relaysConnected = false
|
|
fixture.bridgePeers = [PeerID(str: "abcdef0123456789")]
|
|
|
|
fixture.service.bridgeOutgoing(content: "no internet here", messageID: UUID().uuidString)
|
|
|
|
#expect(fixture.publishedMessages.isEmpty)
|
|
let sent = try #require(fixture.uplinkSends.first)
|
|
let carrier = try #require(NostrCarrierPacket.decode(sent.payload))
|
|
#expect(carrier.direction == .toBridge)
|
|
#expect(carrier.geohash == Self.cell)
|
|
}
|
|
|
|
@Test func ownRelayBackfilledEventIsIgnoredAfterRestart() throws {
|
|
// Field bug: a relaunch wipes the published-ID cache, and relay
|
|
// backfill then re-delivered the device's own pre-restart events as
|
|
// "bridged". Self-recognition by the deterministic rendezvous pubkey
|
|
// must catch them with no cache state at all.
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
let ownOldEvent = try NostrProtocol.createBridgeMeshEvent(
|
|
content: "sent before the restart",
|
|
cell: Self.cell,
|
|
senderIdentity: fixture.identity, // == deriveIdentity(cell)
|
|
nickname: "tester",
|
|
meshMessageID: UUID().uuidString
|
|
)
|
|
|
|
fixture.service.handleRendezvousEvent(ownOldEvent)
|
|
|
|
#expect(fixture.injected.isEmpty)
|
|
#expect(fixture.broadcasts.isEmpty)
|
|
#expect(fixture.service.bridgedPeerCount == 0)
|
|
}
|
|
|
|
@Test func ownEventComingBackFromSubscriptionIsIgnored() {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
fixture.service.bridgeOutgoing(content: "echo me", messageID: UUID().uuidString)
|
|
let ownEvent = fixture.published[0].event
|
|
|
|
fixture.service.handleRendezvousEvent(ownEvent)
|
|
|
|
#expect(fixture.injected.isEmpty)
|
|
#expect(fixture.broadcasts.isEmpty)
|
|
#expect(fixture.service.bridgedPeerCount == 0)
|
|
}
|
|
|
|
// MARK: - Subscription ingress
|
|
|
|
@Test func remoteMessageInjectsAndDownlinks() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
let event = try makeRemoteEvent()
|
|
|
|
fixture.service.handleRendezvousEvent(event)
|
|
|
|
#expect(fixture.injected.count == 1)
|
|
#expect(fixture.injected.first?.content == event.content)
|
|
#expect(fixture.service.bridgedPeerCount == 1)
|
|
// Serving duty: after the jitter holdoff, the remote event rides out
|
|
// as a fromBridge broadcast — one switch, no gateway toggle.
|
|
#expect(fixture.broadcasts.isEmpty)
|
|
fixture.fireScheduledTimers()
|
|
let broadcast = try #require(fixture.broadcasts.first)
|
|
let carrier = try #require(NostrCarrierPacket.decode(broadcast))
|
|
#expect(carrier.direction == .fromBridge)
|
|
}
|
|
|
|
@Test func jitterHoldoffSuppressesAlreadyBroadcastEvents() throws {
|
|
// Two gateways, one island: while our drain waits out the jitter,
|
|
// the other gateway's fromBridge broadcast arrives — ours must yield.
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
let event = try makeRemoteEvent()
|
|
|
|
fixture.service.handleRendezvousEvent(event) // queued behind jitter
|
|
fixture.service.handleMeshCarrier(
|
|
try carrier(event, direction: .fromBridge),
|
|
from: PeerID(str: "aabbccdd00112233"),
|
|
directedToUs: false
|
|
)
|
|
fixture.fireScheduledTimers()
|
|
|
|
#expect(fixture.broadcasts.isEmpty)
|
|
#expect(fixture.injected.count == 1) // rendered once, either path
|
|
}
|
|
|
|
@Test func neighborCellEventIsAccepted() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
let neighbor = try #require(Geohash.neighbors(of: Self.cell).first)
|
|
let event = try makeRemoteEvent(cell: neighbor)
|
|
|
|
fixture.service.handleRendezvousEvent(event)
|
|
|
|
#expect(fixture.injected.count == 1)
|
|
}
|
|
|
|
@Test func outOfRingCellEventIsRejected() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
let event = try makeRemoteEvent(cell: "9q8yyk")
|
|
|
|
fixture.service.handleRendezvousEvent(event)
|
|
|
|
#expect(fixture.injected.isEmpty)
|
|
#expect(fixture.broadcasts.isEmpty)
|
|
}
|
|
|
|
@Test func locallySeenMessageIsNeitherInjectedNorDownlinked() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
let messageID = UUID().uuidString
|
|
fixture.locallySeenMessageIDs = [messageID]
|
|
let event = try makeRemoteEvent(meshMessageID: messageID)
|
|
|
|
fixture.service.handleRendezvousEvent(event)
|
|
|
|
// The island already heard this over radio: no duplicate render, no
|
|
// wasted airtime — but the sender still counts as a (local)
|
|
// participant, never a bridged one.
|
|
#expect(fixture.injected.isEmpty)
|
|
#expect(fixture.broadcasts.isEmpty)
|
|
#expect(fixture.service.bridgedPeerCount == 0)
|
|
}
|
|
|
|
@Test func duplicateSubscriptionEventInjectsOnce() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
let event = try makeRemoteEvent()
|
|
|
|
fixture.service.handleRendezvousEvent(event)
|
|
fixture.service.handleRendezvousEvent(event)
|
|
fixture.fireScheduledTimers()
|
|
|
|
#expect(fixture.injected.count == 1)
|
|
#expect(fixture.broadcasts.count == 1)
|
|
}
|
|
|
|
@Test func presenceCountsParticipantWithoutInjection() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
|
|
fixture.service.handleRendezvousEvent(try makePresenceEvent())
|
|
|
|
#expect(fixture.injected.isEmpty)
|
|
#expect(fixture.service.bridgedPeerCount == 1)
|
|
}
|
|
|
|
@Test func staleParticipantsAgeOutOfTheCount() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
fixture.service.handleRendezvousEvent(try makePresenceEvent())
|
|
#expect(fixture.service.bridgedPeerCount == 1)
|
|
|
|
fixture.advance(BridgeService.Limits.participantFreshnessSeconds + 1)
|
|
fixture.service.publishPresence() // any activity recomputes via prune path
|
|
fixture.fireScheduledTimers()
|
|
|
|
#expect(fixture.service.bridgedPeerCount == 0)
|
|
}
|
|
|
|
@Test func staleEventIsRejected() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
let event = try makeRemoteEvent()
|
|
fixture.advance(BridgeService.Limits.maxEventAgeSeconds + 60)
|
|
|
|
fixture.service.handleRendezvousEvent(event)
|
|
|
|
#expect(fixture.injected.isEmpty)
|
|
}
|
|
|
|
// MARK: - Downlink budget
|
|
|
|
@Test func downlinkRespectsPerMinuteBudgetAndDrainsLater() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
|
|
for _ in 0..<(BridgeService.Limits.downlinkEventsPerMinute + 5) {
|
|
fixture.service.handleRendezvousEvent(try makeRemoteEvent())
|
|
}
|
|
fixture.fireScheduledTimers() // jitter holdoff elapses
|
|
|
|
#expect(fixture.broadcasts.count == BridgeService.Limits.downlinkEventsPerMinute)
|
|
// Window frees: the re-armed timer drains the backlog.
|
|
fixture.advance(61)
|
|
fixture.fireScheduledTimers()
|
|
#expect(fixture.broadcasts.count == BridgeService.Limits.downlinkEventsPerMinute + 5)
|
|
}
|
|
|
|
// MARK: - Mesh carrier ingress (receiver role)
|
|
|
|
@Test func fromBridgeBroadcastInjectsForMeshOnlyReceiver() throws {
|
|
// Reception is not gated on the toggle: passive radio.
|
|
let fixture = Fixture(enabled: false)
|
|
let event = try makeRemoteEvent()
|
|
|
|
fixture.service.handleMeshCarrier(
|
|
try carrier(event, direction: .fromBridge),
|
|
from: PeerID(str: "aabbccdd00112233"),
|
|
directedToUs: false
|
|
)
|
|
|
|
#expect(fixture.injected.count == 1)
|
|
#expect(fixture.service.bridgedPeerCount == 1)
|
|
}
|
|
|
|
@Test func fromBridgeBroadcastDedupsAcrossMeshPaths() throws {
|
|
let fixture = Fixture(enabled: false)
|
|
let event = try makeRemoteEvent()
|
|
let packet = try carrier(event, direction: .fromBridge)
|
|
let peer = PeerID(str: "aabbccdd00112233")
|
|
|
|
fixture.service.handleMeshCarrier(packet, from: peer, directedToUs: false)
|
|
fixture.service.handleMeshCarrier(packet, from: peer, directedToUs: false)
|
|
|
|
#expect(fixture.injected.count == 1)
|
|
}
|
|
|
|
@Test func meshCarriedEventIsNeverRebroadcast() throws {
|
|
// Loop rule 1: a second gateway hearing a fromBridge broadcast must
|
|
// not downlink the same event when its own subscription delivers it.
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
let event = try makeRemoteEvent()
|
|
|
|
fixture.service.handleMeshCarrier(
|
|
try carrier(event, direction: .fromBridge),
|
|
from: PeerID(str: "aabbccdd00112233"),
|
|
directedToUs: false
|
|
)
|
|
fixture.service.handleRendezvousEvent(event)
|
|
fixture.fireScheduledTimers()
|
|
|
|
#expect(fixture.broadcasts.isEmpty)
|
|
#expect(fixture.injected.count == 1)
|
|
}
|
|
|
|
@Test func directedFromBridgeIsMalformedAndDropped() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
|
|
fixture.service.handleMeshCarrier(
|
|
try carrier(makeRemoteEvent(), direction: .fromBridge),
|
|
from: PeerID(str: "aabbccdd00112233"),
|
|
directedToUs: true
|
|
)
|
|
|
|
#expect(fixture.injected.isEmpty)
|
|
}
|
|
|
|
@Test func tamperedCarrierEventIsRejected() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
let event = try makeRemoteEvent()
|
|
let dict: [String: Any] = [
|
|
"id": event.id,
|
|
"pubkey": event.pubkey,
|
|
"created_at": event.created_at,
|
|
"kind": event.kind,
|
|
"tags": event.tags,
|
|
"content": event.content + " (tampered)",
|
|
"sig": event.sig ?? "",
|
|
]
|
|
let forged = try NostrEvent(from: dict)
|
|
|
|
fixture.service.handleMeshCarrier(
|
|
try carrier(forged, direction: .fromBridge),
|
|
from: PeerID(str: "aabbccdd00112233"),
|
|
directedToUs: false
|
|
)
|
|
|
|
#expect(fixture.injected.isEmpty)
|
|
}
|
|
|
|
// MARK: - Uplink deposits (gateway role)
|
|
|
|
@Test func validDepositIsPublishedWhenRelaysUp() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
let event = try makeRemoteEvent()
|
|
|
|
fixture.service.handleMeshCarrier(
|
|
try carrier(event, direction: .toBridge),
|
|
from: PeerID(str: "aabbccdd00112233"),
|
|
directedToUs: true
|
|
)
|
|
|
|
#expect(fixture.published.contains { $0.event.id == event.id })
|
|
// Deposits never inject: the depositor's radio broadcast already
|
|
// carried the message to this island.
|
|
#expect(fixture.injected.isEmpty)
|
|
}
|
|
|
|
@Test func depositQueuesWhileRelaysDownAndFlushesOnReconnect() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
fixture.relaysConnected = false
|
|
let event = try makeRemoteEvent()
|
|
|
|
fixture.service.handleMeshCarrier(
|
|
try carrier(event, direction: .toBridge),
|
|
from: PeerID(str: "aabbccdd00112233"),
|
|
directedToUs: true
|
|
)
|
|
#expect(fixture.publishedMessages.isEmpty)
|
|
#expect(fixture.service.queuedUplinks.count == 1)
|
|
|
|
fixture.relaysConnected = true
|
|
fixture.service.flushQueuedUplinks()
|
|
#expect(fixture.published.contains { $0.event.id == event.id })
|
|
}
|
|
|
|
@Test func depositRequiresBridgeToggle() throws {
|
|
let fixture = Fixture(enabled: false)
|
|
|
|
fixture.service.handleMeshCarrier(
|
|
try carrier(makeRemoteEvent(), direction: .toBridge),
|
|
from: PeerID(str: "aabbccdd00112233"),
|
|
directedToUs: true
|
|
)
|
|
|
|
#expect(fixture.publishedMessages.isEmpty)
|
|
#expect(fixture.service.queuedUplinks.isEmpty)
|
|
}
|
|
|
|
@Test func depositRateLimitBoundsPerDepositor() throws {
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
let depositor = PeerID(str: "aabbccdd00112233")
|
|
|
|
for _ in 0..<(BridgeService.Limits.uplinkEventsPerMinutePerDepositor + 4) {
|
|
fixture.service.handleMeshCarrier(
|
|
try carrier(makeRemoteEvent(), direction: .toBridge),
|
|
from: depositor,
|
|
directedToUs: true
|
|
)
|
|
}
|
|
|
|
#expect(fixture.publishedMessages.count == BridgeService.Limits.uplinkEventsPerMinutePerDepositor)
|
|
}
|
|
|
|
@Test func depositedEventIsNeverDownlinkedBack() throws {
|
|
// Loop rule 2: our own relay subscription redelivering an event we
|
|
// uplinked must not burn airtime broadcasting it back.
|
|
let fixture = Fixture(enabled: true)
|
|
fixture.service.refreshRendezvous()
|
|
let event = try makeRemoteEvent()
|
|
|
|
fixture.service.handleMeshCarrier(
|
|
try carrier(event, direction: .toBridge),
|
|
from: PeerID(str: "aabbccdd00112233"),
|
|
directedToUs: true
|
|
)
|
|
fixture.service.handleRendezvousEvent(event)
|
|
fixture.fireScheduledTimers()
|
|
|
|
#expect(fixture.broadcasts.isEmpty)
|
|
}
|
|
}
|