mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-26 01:45:18 +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>
469 lines
23 KiB
Swift
469 lines
23 KiB
Swift
//
|
|
// GatewayService.swift
|
|
// bitchat
|
|
//
|
|
// This is free and unencumbered software released into the public domain.
|
|
// For more information, see <https://unlicense.org>
|
|
//
|
|
|
|
import BitFoundation
|
|
import BitLogger
|
|
import Combine
|
|
import Foundation
|
|
|
|
/// Policy engine for gateway mode: an opt-in "share my internet with the
|
|
/// mesh" bridge. While the toggle is on, this device advertises the
|
|
/// `.gateway` capability bit, publishes signed geohash events deposited by
|
|
/// mesh-only peers to Nostr relays (uplink), and rebroadcasts inbound relay
|
|
/// events onto the mesh (downlink) so mesh-only peers can take part in the
|
|
/// local geohash channel. Mesh-only peers need no toggle: their uplink
|
|
/// engages automatically when relays are unreachable and a gateway peer
|
|
/// exists.
|
|
///
|
|
/// Threat model:
|
|
/// - Keys never leave the originating device. Mesh-only senders sign events
|
|
/// locally with their per-geohash ephemeral identity; the gateway carries
|
|
/// only the finished, signed event.
|
|
/// - The gateway cannot forge or alter events: every carried event is
|
|
/// Schnorr-verified here before it is published or rebroadcast, and again
|
|
/// independently by relays and receivers.
|
|
/// - Carried contents are public geohash chat, already plaintext on Nostr,
|
|
/// so the mesh carrier adds no confidentiality loss.
|
|
///
|
|
/// Loop-prevention rules:
|
|
/// 1. An event learned from a `fromGateway` mesh broadcast is never
|
|
/// re-published to relays, never re-uplinked, and never rebroadcast
|
|
/// (`meshBroadcastEventIDs`), so a second gateway on the same mesh cannot
|
|
/// echo mesh-carried traffic back out. Mesh-level propagation of the
|
|
/// original broadcast packet is the TTL relay's job, not ours.
|
|
/// 2. An uplink deposit is published at most once (`publishedEventIDs`) and
|
|
/// a relay event is rebroadcast at most once (`rebroadcastEventIDs`), so
|
|
/// repeat deposits and relay echoes are absorbed. An event this gateway
|
|
/// itself uplinked (`publishedEventIDs`) is additionally never
|
|
/// downlink-rebroadcast: it originated on this mesh, so echoing it back
|
|
/// when our own relay subscription redelivers it would double BLE airtime
|
|
/// (the device-confirmed self-echo bug).
|
|
/// 3. Uplink is only attempted for locally composed events at the send site
|
|
/// (`GeohashSubscriptionManager.sendGeohash`); events received over the
|
|
/// carrier never re-enter the uplink path. This is a call-site convention;
|
|
/// the `meshBroadcastEventIDs`/`publishedEventIDs` backstops in
|
|
/// `uplinkViaMesh` enforce it defensively and are unit-tested.
|
|
/// Rules 1 and 2 are enforced here and unit-tested.
|
|
/// Rebroadcast storms at the mesh layer are additionally bounded by the BLE
|
|
/// `MessageDeduplicator` and packet TTL, and receivers dedup carried events
|
|
/// against their own relay subscriptions via the Nostr event-ID cache in
|
|
/// `NostrInboundPipeline`.
|
|
///
|
|
/// All dependencies are closure-injected (repo convention) so the policy
|
|
/// layer is unit-testable without relays or radios.
|
|
@MainActor
|
|
final class GatewayService: ObservableObject {
|
|
enum Limits {
|
|
/// Uplink deposits held while relays are unreachable (CourierStore-style
|
|
/// bounded mailbag: bounded total, bounded per depositor).
|
|
static let maxQueuedUplinks = 20
|
|
static let maxQueuedUplinksPerDepositor = 5
|
|
/// Uplink deposits accepted per depositor per minute.
|
|
static let uplinkEventsPerMinutePerDepositor = 10
|
|
/// Downlink mesh rebroadcasts per minute — BLE airtime is precious.
|
|
/// Beyond the budget events queue (bounded, drop-oldest) and drain on
|
|
/// a scheduled timer once the window frees (also re-driven by the next
|
|
/// inbound relay event); a quiet channel does not strand its backlog.
|
|
static let downlinkEventsPerMinute = 30
|
|
static let maxPendingDownlinks = 30
|
|
/// Accepted clock skew for a carried ephemeral event; anything older
|
|
/// is stale replay the relays would drop anyway.
|
|
static let maxEventAgeSeconds: TimeInterval = 15 * 60
|
|
/// Bounded loop-prevention ID caches (oldest evicted).
|
|
static let maxTrackedEventIDs = 512
|
|
}
|
|
|
|
struct QueuedUplink {
|
|
let depositor: PeerID
|
|
let geohash: String
|
|
let event: NostrEvent
|
|
}
|
|
|
|
static let shared = GatewayService()
|
|
|
|
/// The user toggle. While true this device advertises `.gateway` and
|
|
/// bridges mesh <-> Nostr for geohash channels.
|
|
@Published private(set) var isEnabled: Bool
|
|
|
|
// MARK: Wiring (set once by the bootstrapper; fakes in tests)
|
|
|
|
/// Publishes a verified event to the geo relays for a geohash.
|
|
var publishToRelays: (@MainActor (NostrEvent, String) -> Void)?
|
|
/// Broadcasts an encoded `fromGateway` carrier payload on the mesh.
|
|
var broadcastToMesh: (@MainActor (Data) -> Void)?
|
|
/// Sends an encoded `toGateway` carrier payload directed to a gateway
|
|
/// peer. Returns false when the transport could not accept it.
|
|
var sendToGatewayPeer: (@MainActor (Data, PeerID) -> Bool)?
|
|
/// Reachable mesh peers currently advertising the `.gateway` capability.
|
|
var availableGatewayPeers: (@MainActor () -> [PeerID])?
|
|
/// Whether any Nostr relay connection is currently working.
|
|
var relaysConnected: (@MainActor () -> Bool)?
|
|
/// The geohash channel the local user is viewing, if any.
|
|
var currentGeohash: (@MainActor () -> String?)?
|
|
/// Injects a verified carried event into the same inbound pipeline as
|
|
/// relay-received events (blocking, rate limits, dedup, rendering).
|
|
var injectInbound: (@MainActor (NostrEvent) -> Void)?
|
|
/// Fired on toggle changes (advertise/withdraw the capability bit and
|
|
/// force a re-announce).
|
|
var onEnabledChanged: (@MainActor (Bool) -> Void)?
|
|
/// Schedules a downlink-drain closure to run after a delay. Injected so
|
|
/// the drain timer is deterministic in tests; nil arms a real `Task`.
|
|
var scheduleDrainTimer: (@MainActor (TimeInterval, @escaping @MainActor () -> Void) -> Void)?
|
|
|
|
// MARK: State
|
|
|
|
/// Loop rule 1: event IDs seen in `fromGateway` mesh broadcasts.
|
|
private var meshBroadcastEventIDs: BoundedIDSet
|
|
/// Loop rule 2 (uplink): event IDs this gateway already published.
|
|
private var publishedEventIDs: BoundedIDSet
|
|
/// Loop rule 2 (downlink): event IDs this gateway already rebroadcast.
|
|
private var rebroadcastEventIDs: BoundedIDSet
|
|
|
|
private(set) var queuedUplinks: [QueuedUplink] = []
|
|
private var uplinkDepositTimes: [PeerID: [Date]] = [:]
|
|
private var downlinkSendTimes: [Date] = []
|
|
private var pendingDownlinks: [(event: NostrEvent, geohash: String)] = []
|
|
/// True while a drain timer is armed, so a burst schedules at most one.
|
|
private var downlinkDrainScheduled = false
|
|
|
|
private let defaults: UserDefaults
|
|
private let now: () -> Date
|
|
private static let enabledKey = "gateway.userEnabled"
|
|
|
|
init(defaults: UserDefaults = .standard, now: @escaping () -> Date = Date.init) {
|
|
self.defaults = defaults
|
|
self.now = now
|
|
self.isEnabled = defaults.bool(forKey: Self.enabledKey)
|
|
self.meshBroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
|
|
self.publishedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
|
|
self.rebroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
|
|
}
|
|
|
|
// MARK: - Toggle
|
|
|
|
func setEnabled(_ enabled: Bool) {
|
|
guard enabled != isEnabled else { return }
|
|
isEnabled = enabled
|
|
defaults.set(enabled, forKey: Self.enabledKey)
|
|
if !enabled {
|
|
queuedUplinks.removeAll()
|
|
pendingDownlinks.removeAll()
|
|
uplinkDepositTimes.removeAll()
|
|
}
|
|
SecureLogger.info("🌐 Gateway mode \(enabled ? "enabled" : "disabled")", category: .session)
|
|
onEnabledChanged?(enabled)
|
|
}
|
|
|
|
// MARK: - Mesh carrier ingress (both roles)
|
|
|
|
/// Entry point for received `nostrCarrier` packets. `directedToUs` is
|
|
/// true for packets addressed to this device (uplink deposits); false
|
|
/// for broadcasts (downlink rebroadcasts from a gateway).
|
|
func handleMeshCarrier(_ payload: Data, from peerID: PeerID, directedToUs: Bool) {
|
|
guard let carrier = NostrCarrierPacket.decode(payload) else {
|
|
SecureLogger.debug("🌐 Gateway: dropping undecodable carrier from \(peerID.id.prefix(8))…", category: .session)
|
|
return
|
|
}
|
|
switch carrier.direction {
|
|
case .toGateway:
|
|
// Uplink deposits are directed; a broadcast toGateway is malformed.
|
|
guard directedToUs else { return }
|
|
handleUplinkDeposit(carrier, from: peerID)
|
|
case .fromGateway:
|
|
// Downlink rides broadcast only; a directed fromGateway is malformed.
|
|
guard !directedToUs else { return }
|
|
handleDownlinkBroadcast(carrier)
|
|
case .toBridge, .fromBridge:
|
|
// Mesh-bridge carriers are BridgeService territory; the ingress
|
|
// router dispatches them there.
|
|
return
|
|
}
|
|
}
|
|
|
|
// MARK: - Uplink (gateway role: mesh peer -> internet)
|
|
|
|
private func handleUplinkDeposit(_ carrier: NostrCarrierPacket, from depositor: PeerID) {
|
|
guard isEnabled else { return }
|
|
// Cheap structural checks first (parse, size, geohash, kind, #g tag,
|
|
// age) — no crypto — so junk and stale replays are dropped before we
|
|
// ever pay for a MainActor Schnorr verify.
|
|
guard let event = structurallyValidEvent(from: carrier) else {
|
|
SecureLogger.debug("🌐 Gateway: rejected uplink deposit from \(depositor.id.prefix(8))… (failed validation)", category: .security)
|
|
return
|
|
}
|
|
// Dedup by the carried event ID BEFORE verification. Loop rule 1: a
|
|
// fromGateway-learned event is mesh-carried and must never be
|
|
// re-published. Loop rule 2: repeat deposits of an already handled
|
|
// event are absorbed. A replay of one valid deposit is short-circuited
|
|
// here without a per-packet signature verify.
|
|
guard !meshBroadcastEventIDs.contains(event.id),
|
|
!publishedEventIDs.contains(event.id),
|
|
!queuedUplinks.contains(where: { $0.event.id == event.id }) else {
|
|
return
|
|
}
|
|
// Consume the per-depositor rate token BEFORE the expensive verify so
|
|
// a flood of distinct forged/junk deposits is bounded by cheap work,
|
|
// not by main-actor Schnorr verifications.
|
|
guard allowUplinkDeposit(from: depositor) else {
|
|
SecureLogger.debug("🌐 Gateway: rate-limited uplink deposit from \(depositor.id.prefix(8))…", category: .session)
|
|
return
|
|
}
|
|
// Only now pay for cryptographic verification; receivers verify again.
|
|
guard event.isValidSignature() else {
|
|
SecureLogger.debug("🌐 Gateway: rejected uplink deposit from \(depositor.id.prefix(8))… (bad signature)", category: .security)
|
|
return
|
|
}
|
|
|
|
let accepted: Bool
|
|
if relaysConnected?() ?? false {
|
|
publish(event, geohash: carrier.geohash)
|
|
accepted = true
|
|
} else {
|
|
accepted = enqueueUplink(QueuedUplink(depositor: depositor, geohash: carrier.geohash, event: event))
|
|
}
|
|
|
|
// Only render on our own timeline what we actually accepted for
|
|
// publish or queue: a quota-dropped deposit is never published and,
|
|
// being directed, no other peer will ever see it, so showing it would
|
|
// diverge our timeline permanently from what reached the channel.
|
|
if accepted, currentGeohash?() == carrier.geohash {
|
|
injectInbound?(event)
|
|
}
|
|
}
|
|
|
|
/// Publish everything queued while relays were unreachable. Called when
|
|
/// relay connectivity comes back.
|
|
func flushQueuedUplinks() {
|
|
guard isEnabled, relaysConnected?() ?? false, !queuedUplinks.isEmpty else { return }
|
|
let queued = queuedUplinks
|
|
queuedUplinks.removeAll()
|
|
for item in queued where !publishedEventIDs.contains(item.event.id) {
|
|
publish(item.event, geohash: item.geohash)
|
|
}
|
|
}
|
|
|
|
private func publish(_ event: NostrEvent, geohash: String) {
|
|
publishedEventIDs.insert(event.id)
|
|
publishToRelays?(event, geohash)
|
|
SecureLogger.info("🌐 Gateway: published carried event \(event.id.prefix(8))… to relays for #\(geohash)", category: .session)
|
|
}
|
|
|
|
/// Returns true when the item was actually stored for later publish.
|
|
@discardableResult
|
|
private func enqueueUplink(_ item: QueuedUplink) -> Bool {
|
|
let fromDepositor = queuedUplinks.filter { $0.depositor == item.depositor }.count
|
|
guard fromDepositor < Limits.maxQueuedUplinksPerDepositor else {
|
|
SecureLogger.debug("🌐 Gateway: uplink queue quota reached for \(item.depositor.id.prefix(8))…", category: .session)
|
|
return false
|
|
}
|
|
if queuedUplinks.count >= Limits.maxQueuedUplinks {
|
|
queuedUplinks.removeFirst(queuedUplinks.count - Limits.maxQueuedUplinks + 1)
|
|
}
|
|
queuedUplinks.append(item)
|
|
return true
|
|
}
|
|
|
|
private func allowUplinkDeposit(from depositor: PeerID) -> Bool {
|
|
let cutoff = now().addingTimeInterval(-60)
|
|
var times = uplinkDepositTimes[depositor, default: []]
|
|
times.removeAll { $0 < cutoff }
|
|
guard times.count < Limits.uplinkEventsPerMinutePerDepositor else {
|
|
uplinkDepositTimes[depositor] = times
|
|
return false
|
|
}
|
|
times.append(now())
|
|
uplinkDepositTimes[depositor] = times
|
|
// Bound the tracker itself against a churn of spoofed depositors.
|
|
if uplinkDepositTimes.count > Limits.maxTrackedEventIDs {
|
|
uplinkDepositTimes = uplinkDepositTimes.filter { !$0.value.isEmpty && $0.value.contains { $0 >= cutoff } }
|
|
}
|
|
return true
|
|
}
|
|
|
|
// MARK: - Downlink (gateway role: internet -> mesh)
|
|
|
|
/// Called for every event the gateway's own geohash-channel subscription
|
|
/// delivers. Wraps it in a `fromGateway` carrier and broadcasts it on
|
|
/// the mesh, within the airtime budget.
|
|
func rebroadcastRelayEvent(_ event: NostrEvent, geohash: String) {
|
|
guard isEnabled, broadcastToMesh != nil else { return }
|
|
guard event.kind == NostrProtocol.EventKind.ephemeralEvent.rawValue else { return }
|
|
// Freshness + geohash gate BEFORE spending any budget. A channel
|
|
// (re)subscribe backfills up to an hour of history (limit 200), but
|
|
// every receiver's `validatedEvent` drops anything older than the
|
|
// same window — so rebroadcasting backfill would burn the whole
|
|
// per-minute budget on events no mesh peer accepts. Also require the
|
|
// event's own `#g` tag to match the carrier geohash.
|
|
guard isFresh(event),
|
|
event.tags.contains(where: { $0.count >= 2 && $0[0] == "g" && $0[1] == geohash }) else {
|
|
return
|
|
}
|
|
// Loop rule 1: never rebroadcast mesh-carried events back onto the
|
|
// mesh. Loop rule 2 (self-echo): never rebroadcast an event this
|
|
// gateway itself uplinked (`publishedEventIDs`) — it originated on this
|
|
// very mesh, so our own relay subscription echoing it back must not
|
|
// double the BLE airtime by pushing it out again. Loop rule 2
|
|
// (downlink): rebroadcast each genuine inbound relay event at most once
|
|
// — but mark only AFTER it is actually sent (in `drainPendingDownlinks`),
|
|
// so an event dropped by the queue overflow stays retryable on relay
|
|
// redelivery. Guard against a redelivery re-queueing an event that is
|
|
// still waiting to be sent.
|
|
guard !meshBroadcastEventIDs.contains(event.id),
|
|
!publishedEventIDs.contains(event.id),
|
|
!rebroadcastEventIDs.contains(event.id),
|
|
!pendingDownlinks.contains(where: { $0.event.id == event.id }) else {
|
|
return
|
|
}
|
|
// Verify before spending BLE airtime; receivers verify again.
|
|
guard event.isValidSignature() else { return }
|
|
|
|
pendingDownlinks.append((event, geohash))
|
|
if pendingDownlinks.count > Limits.maxPendingDownlinks {
|
|
// Bandwidth guard: drop-oldest — fresher chat is worth more. The
|
|
// dropped event is not yet in `rebroadcastEventIDs`, so a later
|
|
// relay redelivery can still carry it.
|
|
pendingDownlinks.removeFirst(pendingDownlinks.count - Limits.maxPendingDownlinks)
|
|
}
|
|
drainPendingDownlinks()
|
|
}
|
|
|
|
private func drainPendingDownlinks() {
|
|
let cutoff = now().addingTimeInterval(-60)
|
|
downlinkSendTimes.removeAll { $0 < cutoff }
|
|
while !pendingDownlinks.isEmpty,
|
|
downlinkSendTimes.count < Limits.downlinkEventsPerMinute {
|
|
let (event, geohash) = pendingDownlinks.removeFirst()
|
|
// A queued event may have aged past the window while it waited;
|
|
// don't burn airtime on what receivers would now drop.
|
|
guard isFresh(event) else { continue }
|
|
guard let carrier = NostrCarrierPacket(direction: .fromGateway, geohash: geohash, event: event),
|
|
let payload = carrier.encode() else { continue }
|
|
broadcastToMesh?(payload)
|
|
// Mark-after-send: only now is the relay event definitively
|
|
// rebroadcast (loop rule 2).
|
|
rebroadcastEventIDs.insert(event.id)
|
|
downlinkSendTimes.append(now())
|
|
}
|
|
// Budget exhausted with events still queued: arm a timer to drain when
|
|
// the window frees, instead of stranding them until the next inbound
|
|
// relay event (which may never come on a channel that went quiet).
|
|
scheduleDownlinkDrainIfNeeded()
|
|
}
|
|
|
|
/// Arms a single timer to drain the backlog once the per-minute window
|
|
/// frees. No-op when nothing is pending or a drain is already scheduled.
|
|
private func scheduleDownlinkDrainIfNeeded() {
|
|
guard !pendingDownlinks.isEmpty, !downlinkDrainScheduled else { return }
|
|
// The window frees when the oldest recorded send ages out of 60s.
|
|
let oldest = downlinkSendTimes.min() ?? now()
|
|
let delay = max(0.05, 60 - now().timeIntervalSince(oldest))
|
|
downlinkDrainScheduled = true
|
|
let fire: @MainActor () -> Void = { [weak self] in
|
|
guard let self else { return }
|
|
self.downlinkDrainScheduled = false
|
|
self.drainPendingDownlinks()
|
|
}
|
|
if let scheduleDrainTimer {
|
|
scheduleDrainTimer(delay, fire)
|
|
} else {
|
|
Task { @MainActor in
|
|
try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
|
|
fire()
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Downlink (receiver role: carried event arrives over mesh)
|
|
|
|
private func handleDownlinkBroadcast(_ carrier: NostrCarrierPacket) {
|
|
guard let event = validatedEvent(from: carrier) else { return }
|
|
// Mark only AFTER signature verification, so a forged copy carrying a
|
|
// real event's ID cannot poison the never-republish set, and use the
|
|
// marking as dedup: the same broadcast relayed along several mesh
|
|
// paths injects once (the pipeline's Nostr event-ID cache additionally
|
|
// dedups against our own relay subscription).
|
|
guard meshBroadcastEventIDs.insert(event.id) else { return }
|
|
// Only inject events for the channel we're viewing; the inbound
|
|
// pipeline files public messages under the current geohash.
|
|
guard currentGeohash?() == carrier.geohash else { return }
|
|
injectInbound?(event)
|
|
}
|
|
|
|
// MARK: - Uplink (sender role: mesh-only peer with no relays)
|
|
|
|
/// Hands a locally signed event to a mesh gateway peer when we have no
|
|
/// working relay connection. Returns true when the event was sent.
|
|
///
|
|
/// v1 is deliberately fire-and-forget: no gateway ack. The event also
|
|
/// stays in `NostrRelayManager`'s own pending queue, so if our internet
|
|
/// comes back the relays dedup the duplicate publish by event ID.
|
|
///
|
|
/// Loop rule 3: call sites only pass freshly composed events (see
|
|
/// `GeohashSubscriptionManager.sendGeohash`); received carrier events
|
|
/// never reach this path, and the mesh-carried guard below backstops it.
|
|
func uplinkViaMesh(event: NostrEvent, geohash: String) -> Bool {
|
|
if relaysConnected?() ?? true { return false }
|
|
guard !meshBroadcastEventIDs.contains(event.id),
|
|
!publishedEventIDs.contains(event.id) else {
|
|
return false
|
|
}
|
|
// A single gateway is enough — relays fan out from there, and BLE
|
|
// airtime is precious.
|
|
guard let gateway = availableGatewayPeers?().first else { return false }
|
|
guard let carrier = NostrCarrierPacket(direction: .toGateway, geohash: geohash, event: event),
|
|
let payload = carrier.encode() else {
|
|
return false
|
|
}
|
|
guard sendToGatewayPeer?(payload, gateway) ?? false else { return false }
|
|
SecureLogger.info("🌐 Gateway: uplinked event \(event.id.prefix(8))… for #\(geohash) via mesh gateway \(gateway.id.prefix(8))…", category: .session)
|
|
return true
|
|
}
|
|
|
|
// MARK: - Validation
|
|
|
|
/// Structural and cryptographic checks every carried event must pass
|
|
/// before a gateway publishes it or a receiver displays it. Ordered
|
|
/// cheap-first; Schnorr verification runs last.
|
|
private func validatedEvent(from carrier: NostrCarrierPacket) -> NostrEvent? {
|
|
guard let event = structurallyValidEvent(from: carrier),
|
|
event.isValidSignature() else {
|
|
return nil
|
|
}
|
|
return event
|
|
}
|
|
|
|
/// The cheap half of `validatedEvent`: parse + size + geohash + kind +
|
|
/// `#g` tag + freshness, with NO signature verification. Callers that can
|
|
/// dedup or rate-limit on the carried ID run this first so the expensive
|
|
/// Schnorr verify is reached only for events that survive the cheap gates.
|
|
private func structurallyValidEvent(from carrier: NostrCarrierPacket) -> NostrEvent? {
|
|
guard carrier.eventJSON.count <= NostrCarrierPacket.maxEventJSONBytes,
|
|
Self.isValidGeohash(carrier.geohash),
|
|
let event = carrier.event(),
|
|
event.kind == NostrProtocol.EventKind.ephemeralEvent.rawValue,
|
|
event.tags.contains(where: { $0.count >= 2 && $0[0] == "g" && $0[1] == carrier.geohash }),
|
|
isFresh(event) else {
|
|
return nil
|
|
}
|
|
return event
|
|
}
|
|
|
|
/// True when `event.created_at` is within the accepted clock skew — the
|
|
/// SAME freshness window receivers enforce, so a gateway never spends
|
|
/// airtime on events every receiver would drop as stale.
|
|
private func isFresh(_ event: NostrEvent) -> Bool {
|
|
abs(now().timeIntervalSince1970 - TimeInterval(event.created_at)) <= Limits.maxEventAgeSeconds
|
|
}
|
|
|
|
static func isValidGeohash(_ geohash: String) -> Bool {
|
|
let allowed = Set("0123456789bcdefghjkmnpqrstuvwxyz")
|
|
return (1...NostrCarrierPacket.maxGeohashLength).contains(geohash.count)
|
|
&& geohash.allSatisfy { allowed.contains($0) }
|
|
}
|
|
}
|