Compare commits

..
Author SHA1 Message Date
0152196ac2 Deflake CI, and make the flake class unrepeatable (#1491)
* Deflake two iOS-sim CI tests with unbounded timing assumptions

Both failed on main-adjacent CI runs during this session's PRs. Neither
was a product bug; both asserted things about real time that a loaded
runner is under no obligation to honour.

**NetworkReachabilityGateTests: a wall-clock upper bound.**
test_monitor_duplicateUpdatesDoNotPostponeOfflineCommit slept 500ms for
real, then asserted total elapsed time was under 1.4s to prove a duplicate
mid-window had not restarted the 1.0s debounce. One CI run took 3.75s. No
wall-clock bound can separate "deadline preserved" from "runner is slow",
because Task.sleep and the asyncAfter flush are both real time and neither
is bounded above.

The deadline property was already covered deterministically one level
down: test_debounce_duplicateObservationsPreservePendingDeadline drives
ReachabilityDebounce with injected timestamps and checks pendingRemaining
directly. So the monitor test now asserts only what needs a real monitor —
that a duplicate still yields exactly one committed false through the
debounce — with an injected clock for the arithmetic and a generous
liveness budget. Renamed to say what it actually checks. No coverage lost,
and it runs in 0.14s instead of ~3.8s because the real sleep is gone.

**NoiseEncryptionServiceTests: injected timeouts that also arm during
setup.** #1483 diagnosed and fixed exactly this in the quarantine-restore
test, but two sibling tests kept the shape. Their injected
ordinaryResponderHandshakeTimeout (0.04 and 0.06) also arms during the
establishSessions setup handshake, where bob is the responder — so a
preempted runner fires it mid-setup, tears down the half-open responder,
and message 3 gets answered as a fresh initiation. The CI failure named
setup's own `#expect(finalMessage == nil)` seeing a 96-byte message 2,
which is precisely the signature #1483 recorded.

Raised both to 1.0s, matching #1483's remedy: the scenarios still need the
responder timeout to fire, and it still does, just with room for setup to
complete first. Thin 1-second waitUntil budgets in the file now use the
shared TestConstants.longTimeout; every one of them backs a positive
assertion, so waitUntil still returns the moment the condition holds and
nothing gets slower in the passing case.

No assertion weakened in either file. Verified 3x sequentially and 3x with
all 18 cores saturated.

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

* Raise two more starvation-prone test deadlines

Both surfaced on the CI runs for this PR and #1487, both in tests neither
PR touches, both the same shape as the two already fixed here: a deadline
sized for the work rather than for a runner executing many suites at once.

VoiceNotePlaybackControllerTests waited 5s for a @MainActor Task that
playback schedules for the session acquire and its failure path. When that
Task is not scheduled in time the helper reports *two* failures — the wait,
and the `!isPlaying` the un-run failure path has not reset yet — which
reads like a playback bug rather than a starved scheduler. That is exactly
what CI showed.

GeoRelayDirectoryTests waited 10s for work the directory runs in
Task.detached(priority: .utility); utility priority competes with every
other suite. The retry-scheduling case timed out at exactly 10.06s with the
retry never scheduled, reading like a missing retry rather than a starved
background task.

Raised to 30s each with the reasoning recorded at the helper. Both helpers
return as soon as their condition holds, so nothing slows down when tests
pass — only the genuine-failure case takes longer to report.

Verified 3x with all cores saturated: both suites clean.

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

* Make the flake class unrepeatable, not just fixed

Raising four deadlines fixed the four tests that happened to fire. The
class was still there: fourteen separate waitUntil helpers, most defaulting
to 1.0s, plus wait call sites with literal budgets. The fifth instance
would have landed the same way, on someone else's unrelated PR.

The rule, now written down in TestConstants.settleTimeout: **a wait
deadline is not a latency budget.** It exists so a genuine hang eventually
fails the suite, so size it for the worst-case scheduler, never for how
long the operation should take. Waits return as soon as their condition
holds, so a generous deadline is free in the passing case and only extends
genuine failures.

- Every wait helper now defaults to TestConstants.settleTimeout (30s), and
  the literal wait call sites below the floor were converted too — sixteen
  sites across ten files.
- TestTimingHygieneTests enforces it by scanning the test sources: wait
  defaults and wait call sites must be at least minimumSettleTimeout, and
  no test may assert an upper bound on elapsed wall-clock time (the
  assertion that started this, which cannot separate correct behaviour from
  a slow machine).
- Both rules waive per line with "test-timing-ok: <reason>", accepted on
  the line or in the comment block above it so the reason has room to be a
  sentence. One legitimate use so far: a NEGATIVE wait in NoiseCoverageTests
  asserting a promotion has *not* completed within 50ms, where a long
  deadline would only make the suite slow while still passing.

Injected production timeouts are deliberately not matched — the Noise
handshake timeouts are the behaviour under test, and short values are
correct there.

Verified the guard actually fails: a canary file with both banned shapes
was flagged with file and line, and the suite went green again once it was
removed. Full suite passes with all 18 cores saturated.

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

* Close the guard's blind spot: named short timeouts

A fifth flake landed on CI while the first guard was in review —
GossipSyncBoardTests timing out at 1.03s — and the guard did not catch it,
because the deadline was `TestConstants.shortTimeout` rather than a
literal. A literals-only scan cannot see a short value behind a symbol,
which is the more common way it is written: 81 wait sites used
shortTimeout (1s) or defaultTimeout (5s), every one of them below the
floor.

Rather than guess which of those were safe to raise, all 81 were converted
and the suite timed. Runtime went 15s -> 72s, which located the genuine
negative waits precisely: ten tests that assert something does *not*
happen and therefore always run their deadline out. Measurement instead of
a heuristic, since a mis-guess in either direction is invisible — too
short reintroduces the flake, too long silently costs a minute a run.

Those 28 sites now use `TestConstants.negativeWaitWindow`, a named
constant whose doc explains the inverted reasoning: for a negative wait,
starvation can only make the assertion *more* likely to hold, so short is
correct, and the name states the polarity instead of leaving a bare
literal that reads like the mistake. Suite is back to 15.3s.

The guard now also rejects `timeout: TestConstants.shortTimeout` and
`defaultTimeout`, while accepting `negativeWaitWindow` by name.

Re-verified with a canary carrying every banned shape — literal default,
both named constants, and an elapsed-time upper bound. All four were
flagged with file and line; the suite went green again on removal.

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

* Delete shortTimeout now that nothing may use it

The hygiene guard bans `TestConstants.shortTimeout` at every wait site
and the last users were converted, so Periphery correctly flagged the
constant itself as dead and failed CI. Remove it from both TestConstants
copies; the banned-name entry stays so the symbol cannot quietly return.

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

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 23:45:20 +01:00
14e7b428d9 Add a real security policy (#1489)
* Add a real security policy

Two drive-by template PRs (#1118, #1482) tried to fill this gap with
unedited boilerplate. This is the actual policy: private vulnerability
reporting (now enabled on the repo) as the channel, honest expectations
for a volunteer project, and a scope section that separates the
properties the app promises from the documented design behaviors that
keep getting reported as vulnerabilities.

Closes #1081

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

* Address Codex review: name the Nostr envelope format precisely

'Gift-wrapped' reads as NIP-59, and the scope section is exactly where
a researcher calibrates expectations. Say what it is: bitchat's own
private-envelope scheme, explicitly not NIP-17/44/59.

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>
2026-07-26 21:33:59 +02:00
c671e3df66 Keep the composer focused after sending with the return key (#1490)
* Keep the composer focused after sending with the return key

On iOS, return sends and then drops the keyboard, so every message in a
back-and-forth costs an extra tap to reopen it. sendMessage() is the
onSubmit handler; reasserting the FocusState there keeps the keyboard up
between messages. macOS already refocuses on appear and is unaffected.

Fixes #457

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

* Address Codex review: refocus only on return-key submission

The reassert moves from sendMessage() into the TextField's onSubmit, so
the send button no longer reopens a deliberately dismissed keyboard on
iOS and never moves focus on macOS.

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>
2026-07-26 21:19:12 +02:00
132120a88e Close the three holes the #1486 review found (#1488)
* Fix the three follow-ups from the #1486 review

Three defects shipped with the censorship-resilience merge, all
confirmed against main:

1. Source-manifest verification silently accepted added files.
   shasum -c checks only the files the manifest lists, and the Xcode
   project compiles every source file present in the tree — so a
   hostile mirror could pass verification by adding a file rather than
   modifying one. The manifest header and VERIFYING-A-BUILD.md now
   require the completeness check (git status --porcelain, or a path
   diff for tarballs) alongside the hash check.

2. A relay removed while Tor was bootstrapping reconnected anyway.
   dropRelays never subtracted from pendingTorConnectionURLs, and a
   custom relay passes the allow-list filter, so draining the pending
   queue resurrected a relay someone had explicitly deleted.

3. Turning Tor off mid-bootstrap read as 'network may be blocking tor'.
   shutdownCompletely left the detached 75s poll loop running, which
   then stamped bootstrapDidStall over the clean shutdown state; and
   the stall handler guarded on torEnforced, which is compile-time true
   in release, instead of the runtime preference. The poll loop is now
   generation-fenced (shutdown, dormancy, and restart each invalidate
   it) and the handler consults persistedTorPreference().

Both app-side fixes carry regression tests proven to fail pre-fix.

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

* Address Codex review: ignored files and manifest placement

git status --porcelain omits ignored paths, and .gitignore covers
build/ — a planted bitchat/build/Evil.swift would compile via the
synchronized group while the documented check stayed silent. The
checkout check now uses --ignored.

The downloaded manifest also has to live outside the tree, or it trips
the completeness checks itself; the doc now says so and references it
at /tmp throughout.

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>
2026-07-26 21:01:38 +02:00
44 changed files with 604 additions and 1587 deletions
+7 -1
View File
@@ -63,7 +63,13 @@ jobs:
echo "#"
echo "# Verify a checkout of this ref with:"
echo "# shasum -a 256 -c files.sha256"
echo "# The git tree hash above is the single value that covers all of it:"
echo "# Hash checking alone ignores files this manifest does not list, and"
echo "# the Xcode project compiles any source file present in the tree. So"
echo "# also confirm nothing extra is present:"
echo "# git status --porcelain --ignored # git checkout: must print nothing"
echo "# or, for a tarball, diff this manifest's path list against find(1)."
echo "# Full instructions: docs/VERIFYING-A-BUILD.md"
echo "# The git tree hash above is the single value covering all tracked content:"
echo "# git rev-parse HEAD^{tree}"
echo "#"
} > SOURCE-MANIFEST.txt
+45
View File
@@ -0,0 +1,45 @@
# Security policy
bitchat is a security-focused messenger, and reports about its security are taken seriously. This page says how to report, what counts as a vulnerability here, and what to expect.
## Reporting a vulnerability
**Use GitHub's private vulnerability reporting:** [Report a vulnerability](https://github.com/permissionlesstech/bitchat/security/advisories/new) (Security tab → "Report a vulnerability").
Please do not open a public issue for anything that could put people at risk before a fix ships. bitchat is used by people in hostile network environments; a public proof-of-concept can be acted on faster than a patch can reach them.
A useful report says what an attacker can do, against which build (App Store version or commit hash), and how to reproduce it. A failing test or a packet capture is worth more than speculation about impact.
## What to expect
This is a volunteer-maintained project. The aim is to acknowledge reports within a week and to move on confirmed vulnerabilities immediately — historically, confirmed protocol and key-handling issues have been fixed within days. You'll be kept in the loop in the advisory thread, and credited in the fix unless you'd rather not be. There is no bug bounty.
## Supported versions
Fixes ship to the latest App Store release and `main`. Older releases are not patched; the fix is to update.
## Scope
In scope — the properties the app promises:
- Confidentiality and integrity of private messages and media (Noise sessions over BLE; over Nostr, bitchat's own ephemeral private-envelope format — a proprietary scheme, *not* NIP-17/NIP-44/NIP-59, see `WHITEPAPER.md`)
- Identity: key handling, verification, impersonation, session binding
- The panic wipe actually destroying what it claims to destroy
- Metadata exposure beyond what the documentation already discloses (see `PRIVACY_POLICY.md` and `docs/privacy-assessment.md`)
- Downgrade paths: anything that silently moves traffic from an encrypted path to a plaintext one
- Tor routing: anything that makes traffic bypass Tor while the Tor preference is on
- Supply-chain integrity of the source and its vendored binaries (see `docs/VERIFYING-A-BUILD.md`)
Out of scope — documented design properties, not vulnerabilities:
- Public visibility of mesh announces and geohash channels: broadcast content, nicknames, and public keys are public by design
- Bluetooth proximity being observable: anyone in radio range can tell a BLE device is present
- Mesh flooding/relay behavior inherent to a broadcast mesh (rate limits exist; the topology is what it is)
- Behavior of third-party Nostr relays
- Denial of service requiring physical proximity, and battery-drain attacks in general
If you're unsure whether something is in scope, report it privately anyway — a false alarm costs a few minutes; a real issue reported publicly can cost much more.
## Verifying what you're running
If your concern is that the app or source you have has been tampered with, that has its own document: `docs/VERIFYING-A-BUILD.md`.
+3
View File
@@ -848,6 +848,9 @@ final class NostrRelayManager: ObservableObject {
}
}
messageQueueLock.unlock()
// A relay queued while Tor bootstraps would otherwise reconnect when
// the queue drains, overriding the explicit removal.
pendingTorConnectionURLs.subtract(urls)
relays.removeAll { urls.contains($0.url) }
updateConnectionStatus()
}
@@ -15,15 +15,7 @@ enum BLEOutboundPacketPolicy {
// voiceFrame is deliberately unpadded: padding to the 512 block would
// push every ~490-byte signed voice packet over the MTU into the
// fragment path.
//
// announceV2 is unpadded too, but for a different reason and it is worth
// revisiting: it is ~75 bytes, so the smallest bucket would triple the
// airtime of the most frequently sent packet in the protocol. Its length
// is already near-constant by construction (the tag block is fixed
// width); the residual variation is the capability width and whether a
// bridge geohash is present. Making those fixed-width would be cheaper
// than padding. See docs/PEER-ID-ROTATION.md.
case .none, .announce, .announceV2, .message, .leave, .requestSync, .fragment, .fileTransfer, .courierEnvelope, .boardPost, .ping, .pong, .nostrCarrier, .prekeyBundle, .groupMessage, .voiceFrame:
case .none, .announce, .message, .leave, .requestSync, .fragment, .fileTransfer, .courierEnvelope, .boardPost, .ping, .pong, .nostrCarrier, .prekeyBundle, .groupMessage, .voiceFrame:
return false
}
}
@@ -35,13 +27,6 @@ enum BLEOutboundPacketPolicy {
return .fragment(totalFragments: fragmentTotalCount(from: packet.payload))
case .fileTransfer:
return .fileTransfer
case .announceV2:
// Stated rather than inherited from `default`. Presence is small,
// time-bounded to its epoch, and useless once stale, so it belongs
// with the other control traffic at high priority but that should
// be a decision on the record, not a fall-through, since this type
// is not emitted yet and nobody would notice the choice being made.
return .high
default:
return .high
}
+1 -10
View File
@@ -7025,16 +7025,7 @@ extension BLEService {
switch context.messageType {
case .announce:
handleAnnounce(packet, from: senderID)
case .announceV2:
// Parsed and ignored on purpose. The wire format and derivations are
// implemented and tested (see PeerIDRotation, AnnounceV2Packet), but
// consuming presence from it needs the replacement identity binding
// and the peer-list policy for unverified presence, both of which are
// still open questions in docs/PEER-ID-ROTATION.md. Accepting it now
// would add unauthenticated entries to the peer list.
break
case .message:
handleMessage(packet, from: senderID)
-5
View File
@@ -57,11 +57,6 @@ struct SyncTypeFlags: OptionSet {
// Live voice is only useful now; replaying stale audio frames via
// sync would waste airtime (receivers drop them as stale anyway).
case .voiceFrame: return nil
// Rotating-ID presence is valid only inside its epoch, and gossiping it
// would defeat the point: a synced announce would let a device that was
// never in radio range collect tag blocks, turning a local presence
// beacon into a network-wide one.
case .announceV2: return nil
// Prekey bundles gossip like board posts. The bitfield is a
// wire-tolerant little-endian UInt64 (1-8 bytes, unknown high bits
// ignored by `type(forBit:)`), so bits 8+ need no format change: old
@@ -64,6 +64,10 @@ extension ChatViewModel {
@objc func handleTorBootstrapDidStall() {
Task { @MainActor in
guard TorManager.shared.torEnforced else { return }
// torEnforced is a compile-time constant in release builds; the
// runtime preference is what says whether anyone is waiting on
// Tor. Turning Tor off mid-bootstrap must not read as blocking.
guard NetworkActivationService.persistedTorPreference() else { return }
guard !self.torStallAnnounced else { return }
self.torStallAnnounced = true
self.addGeohashOnlySystemMessage(
+8 -1
View File
@@ -73,7 +73,14 @@ struct ContentComposerView: View {
.textInputAutocapitalization(.sentences)
#endif
.submitLabel(.send)
.onSubmit(onSendMessage)
.onSubmit {
onSendMessage()
// Only the return-key path: it steals focus on iOS, so
// every message would cost a tap to reopen the keyboard.
// The send button must not reopen a deliberately
// dismissed keyboard, so it stays out of this.
isTextFieldFocused.wrappedValue = true
}
.padding(.vertical, theme.usesGlassChrome ? 8 : 4)
.padding(.horizontal, 6)
.themedInputBackground()
+5 -5
View File
@@ -39,7 +39,7 @@ struct BLEServiceCoreTests {
ble._test_handlePacket(packet, fromPeerID: sender, signingPublicKey: signingKey)
let receivedDuplicate = await TestHelpers.waitUntil(
{ delegate.publicMessagesSnapshot().count > 1 },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!receivedDuplicate)
@@ -117,7 +117,7 @@ struct BLEServiceCoreTests {
let unsignedRelayed = await TestHelpers.waitUntil(
{ outbound.count(ofType: .leave) > 0 },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!unsignedRelayed)
#expect(ble.currentPeerSnapshots().contains { $0.peerID == alicePeerID })
@@ -133,7 +133,7 @@ struct BLEServiceCoreTests {
let badSignatureRelayed = await TestHelpers.waitUntil(
{ outbound.count(ofType: .leave) > 0 },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!badSignatureRelayed)
#expect(ble.currentPeerSnapshots().contains { $0.peerID == alicePeerID })
@@ -1209,7 +1209,7 @@ struct BLEServiceCoreTests {
let didObservePanicClosure = await withCheckedContinuation { continuation in
DispatchQueue.global(qos: .userInitiated).async {
let didObserveClosure = panicIngressObserver.waitUntilClosed(
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
gate.release()
continuation.resume(returning: didObserveClosure)
@@ -1340,7 +1340,7 @@ struct BLEServiceCoreTests {
// rotated sender IDs never bought a sixth response.
let exceededBudget = await TestHelpers.waitUntil(
{ outbound.count(ofType: .pong) > budget },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!exceededBudget)
#expect(outbound.count(ofType: .pong) == budget)
@@ -1374,3 +1374,37 @@ private func makeImageData() throws -> Data {
return data
#endif
}
// MARK: - Tor Extension Tests
struct ChatViewModelTorExtensionTests {
/// Turning Tor off mid-bootstrap must not read as "the network is
/// blocking tor": `torEnforced` is a compile-time constant, so the stall
/// handler has to consult the runtime preference before announcing.
@Test @MainActor
func bootstrapStall_withTorPreferenceOff_announcesNothing() async {
let key = NetworkActivationService.torPreferenceKey
let previous = UserDefaults.standard.object(forKey: key)
defer {
if let previous {
UserDefaults.standard.set(previous, forKey: key)
} else {
UserDefaults.standard.removeObject(forKey: key)
}
}
let (viewModel, _) = makeTestableViewModel()
UserDefaults.standard.set(false, forKey: key)
viewModel.handleTorBootstrapDidStall()
try? await Task.sleep(nanoseconds: 50_000_000)
#expect(viewModel.torStallAnnounced == false)
// The same stall with the preference on (the persisted default) is
// exactly what must still be announced.
UserDefaults.standard.set(true, forKey: key)
viewModel.handleTorBootstrapDidStall()
try? await Task.sleep(nanoseconds: 50_000_000)
#expect(viewModel.torStallAnnounced == true)
}
}
@@ -43,14 +43,14 @@ struct ChatViewModelRefactoringTests {
transport.simulateConnect(peerID, nickname: "alice")
let didResolve = await TestHelpers.waitUntil({ viewModel.getPeerIDForNickname("alice") != nil },
timeout: TestConstants.shortTimeout)
timeout: TestConstants.settleTimeout)
#expect(didResolve)
// Action: User types /msg command
viewModel.sendMessage("/msg @alice Hello Private World")
let didSend = await TestHelpers.waitUntil({ transport.sentPrivateMessages.count == 1 },
timeout: TestConstants.shortTimeout)
timeout: TestConstants.settleTimeout)
#expect(didSend)
// Assert:
@@ -74,7 +74,7 @@ struct ChatViewModelRefactoringTests {
transport.simulateConnect(peerID, nickname: "troll")
let didResolve = await TestHelpers.waitUntil({ viewModel.getPeerIDForNickname("troll") != nil },
timeout: TestConstants.shortTimeout)
timeout: TestConstants.settleTimeout)
#expect(didResolve)
// Action
@@ -83,7 +83,7 @@ struct ChatViewModelRefactoringTests {
// Assert
// Verify identity manager was called to block "fingerprint_123"
let didBlock = await TestHelpers.waitUntil({ identity.isBlocked(fingerprint: "fingerprint_123") },
timeout: TestConstants.shortTimeout)
timeout: TestConstants.settleTimeout)
#expect(didBlock)
}
@@ -114,7 +114,7 @@ struct ChatViewModelRefactoringTests {
// Wait for async processing with proper timeout
let found = await TestHelpers.waitUntil(
{ viewModel.privateChats[senderID]?.first?.content == "Secret" },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
// Assert
@@ -140,7 +140,7 @@ struct ChatViewModelRefactoringTests {
{
viewModel.publicMessages(for: .mesh).contains(where: { $0.content == "Public Hi" })
},
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
// Assert
+10 -10
View File
@@ -321,7 +321,7 @@ struct ChatViewModelCommandTests {
transport.simulateConnect(peerID, nickname: "Alice")
let resolved = await TestHelpers.waitUntil({
viewModel.getPeerIDForNickname("Alice") == peerID
}, timeout: TestConstants.defaultTimeout)
}, timeout: TestConstants.negativeWaitWindow)
#expect(resolved)
viewModel.handleCommand("/msg Alice")
@@ -422,7 +422,7 @@ struct ChatViewModelServiceLifecycleTests {
transport.sentReadReceipts.contains {
$0.peerID == peerID && $0.receipt.originalMessageID == "read-1"
}
}, timeout: TestConstants.defaultTimeout)
}, timeout: TestConstants.negativeWaitWindow)
#expect(sentReadReceipt)
#expect(!viewModel.unreadPrivateMessages.contains(peerID))
@@ -506,7 +506,7 @@ struct ChatViewModelReceivingTests {
let found = await TestHelpers.waitUntil({
viewModel.publicMessages(for: .mesh).contains { $0.content == "Public hello from Bob" }
}, timeout: TestConstants.defaultTimeout)
}, timeout: TestConstants.settleTimeout)
#expect(found)
}
@@ -535,11 +535,11 @@ struct ChatViewModelNoisePayloadTests {
let stored = await TestHelpers.waitUntil({
viewModel.privateChats[peerID]?.contains(where: { $0.id == "pm-noise-1" && $0.content == "Secret hello" }) == true
}, timeout: TestConstants.defaultTimeout)
}, timeout: TestConstants.settleTimeout)
let acked = await TestHelpers.waitUntil({
transport.sentDeliveryAcks.contains { $0.messageID == "pm-noise-1" && $0.peerID == peerID }
}, timeout: TestConstants.defaultTimeout)
}, timeout: TestConstants.settleTimeout)
#expect(stored)
#expect(acked)
@@ -579,7 +579,7 @@ struct ChatViewModelNoisePayloadTests {
return name == "Bob"
}
return false
}, timeout: TestConstants.defaultTimeout)
}, timeout: TestConstants.settleTimeout)
#expect(delivered)
}
@@ -617,7 +617,7 @@ struct ChatViewModelNoisePayloadTests {
return true
}
return false
}, timeout: TestConstants.defaultTimeout)
}, timeout: TestConstants.settleTimeout)
let conversationStoreUpdated = await TestHelpers.waitUntil({
let messages = viewModel.conversations.conversationsByID[.directPeer(peerID)]?.messages ?? []
@@ -626,7 +626,7 @@ struct ChatViewModelNoisePayloadTests {
return true
}
return false
}, timeout: TestConstants.defaultTimeout)
}, timeout: TestConstants.settleTimeout)
#expect(privateChatUpdated)
#expect(conversationStoreUpdated)
@@ -730,7 +730,7 @@ struct ChatViewModelVerificationTests {
let bound = await TestHelpers.waitUntil({
viewModel.unifiedPeerService.peers.contains { $0.peerID == peerID }
}, timeout: TestConstants.defaultTimeout)
}, timeout: TestConstants.settleTimeout)
#expect(bound)
let qr = VerificationService.VerificationQR(
@@ -982,7 +982,7 @@ struct ChatViewModelPeerTests {
let cleaned = await TestHelpers.waitUntil({
!viewModel.unreadPrivateMessages.contains(stalePeer)
}, timeout: TestConstants.defaultTimeout)
}, timeout: TestConstants.settleTimeout)
#expect(cleaned)
}
@@ -142,7 +142,7 @@ struct CourierEndToEndTests {
))
let deposited = await TestHelpers.waitUntil(
{ aliceOut.first(ofType: .courierEnvelope) != nil },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(deposited)
let depositPacket = try #require(aliceOut.first(ofType: .courierEnvelope))
@@ -151,7 +151,7 @@ struct CourierEndToEndTests {
carol._test_handlePacket(depositPacket, fromPeerID: alice.myPeerID, signingPublicKey: alice.noiseSigningPublicKeyData())
let carried = await TestHelpers.waitUntil(
{ !carol.courierStore.isEmpty },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(carried)
@@ -161,7 +161,7 @@ struct CourierEndToEndTests {
bob.sendBroadcastAnnounce()
let announced = await TestHelpers.waitUntil(
{ bobOut.first(ofType: .announce) != nil },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(announced)
let announcePacket = try #require(bobOut.first(ofType: .announce))
@@ -169,7 +169,7 @@ struct CourierEndToEndTests {
let handedOver = await TestHelpers.waitUntil(
{ carolOut.first(ofType: .courierEnvelope) != nil },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(handedOver)
// With CoreBluetooth disabled there is no physical link for the send
@@ -183,7 +183,7 @@ struct CourierEndToEndTests {
bob._test_handlePacket(handoverPacket, fromPeerID: carol.myPeerID)
let received = await TestHelpers.waitUntil(
{ !bobDelegate.snapshot().isEmpty },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(received)
@@ -229,7 +229,7 @@ struct CourierEndToEndTests {
))
let deposited = await TestHelpers.waitUntil(
{ aliceOut.first(ofType: .courierEnvelope) != nil },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(deposited)
let depositPacket = try #require(aliceOut.first(ofType: .courierEnvelope))
@@ -237,7 +237,7 @@ struct CourierEndToEndTests {
carol._test_handlePacket(depositPacket, fromPeerID: alice.myPeerID, signingPublicKey: alice.noiseSigningPublicKeyData())
let carried = await TestHelpers.waitUntil(
{ !carol.courierStore.isEmpty },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(carried)
@@ -245,7 +245,7 @@ struct CourierEndToEndTests {
bob.sendBroadcastAnnounce()
let announced = await TestHelpers.waitUntil(
{ bobOut.first(ofType: .announce) != nil },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(announced)
let announcePacket = try #require(bobOut.first(ofType: .announce))
@@ -253,7 +253,7 @@ struct CourierEndToEndTests {
let handedOver = await TestHelpers.waitUntil(
{ carolOut.first(ofType: .courierEnvelope) != nil },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(handedOver)
let handoverPacket = try #require(carolOut.first(ofType: .courierEnvelope))
@@ -265,7 +265,7 @@ struct CourierEndToEndTests {
bob._test_handlePacket(handoverPacket, fromPeerID: carol.myPeerID)
let delivered = await TestHelpers.waitUntil(
{ !bobDelegate.snapshot().isEmpty },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!delivered)
}
@@ -293,7 +293,7 @@ struct CourierEndToEndTests {
))
let deposited = await TestHelpers.waitUntil(
{ aliceOut.first(ofType: .courierEnvelope) != nil },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(deposited)
let depositPacket = try #require(aliceOut.first(ofType: .courierEnvelope))
@@ -301,7 +301,7 @@ struct CourierEndToEndTests {
carol._test_handlePacket(depositPacket, fromPeerID: alice.myPeerID, signingPublicKey: alice.noiseSigningPublicKeyData())
let carried = await TestHelpers.waitUntil(
{ !carol.courierStore.isEmpty },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(carried)
@@ -310,7 +310,7 @@ struct CourierEndToEndTests {
let leakedOnUnverifiedAnnounce = await TestHelpers.waitUntil(
{ carolOut.count(ofType: .courierEnvelope) > 0 },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!leakedOnUnverifiedAnnounce)
#expect(!carol.courierStore.isEmpty)
@@ -318,7 +318,7 @@ struct CourierEndToEndTests {
bob.sendBroadcastAnnounce()
let announced = await TestHelpers.waitUntil(
{ bobOut.first(ofType: .announce) != nil },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(announced)
let verifiedAnnounce = try #require(bobOut.first(ofType: .announce))
@@ -326,7 +326,7 @@ struct CourierEndToEndTests {
let handedOver = await TestHelpers.waitUntil(
{ carolOut.count(ofType: .courierEnvelope) == 1 },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(handedOver)
#expect(!carol.courierStore.isEmpty)
@@ -355,7 +355,7 @@ struct CourierEndToEndTests {
))
let deposited = await TestHelpers.waitUntil(
{ aliceOut.first(ofType: .courierEnvelope) != nil },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(deposited)
let depositPacket = try #require(aliceOut.first(ofType: .courierEnvelope))
@@ -363,14 +363,14 @@ struct CourierEndToEndTests {
carol._test_handlePacket(depositPacket, fromPeerID: alice.myPeerID, signingPublicKey: alice.noiseSigningPublicKeyData())
let carried = await TestHelpers.waitUntil(
{ !carol.courierStore.isEmpty },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(carried)
bob.sendBroadcastAnnounce()
let announced = await TestHelpers.waitUntil(
{ bobOut.first(ofType: .announce) != nil },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(announced)
let directAnnounce = try #require(bobOut.first(ofType: .announce))
@@ -385,7 +385,7 @@ struct CourierEndToEndTests {
let remoteHandover = await TestHelpers.waitUntil(
{ carolOut.count(ofType: .courierEnvelope) == 1 },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(remoteHandover)
#expect(!carol.courierStore.isEmpty)
@@ -398,7 +398,7 @@ struct CourierEndToEndTests {
bob.sendBroadcastAnnounce()
let reannounced = await TestHelpers.waitUntil(
{ bobOut.all(ofType: .announce).contains { $0.timestamp != directAnnounce.timestamp } },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(reannounced)
let freshAnnounce = try #require(
@@ -410,7 +410,7 @@ struct CourierEndToEndTests {
let refloodedInCooldown = await TestHelpers.waitUntil(
{ carolOut.count(ofType: .courierEnvelope) > 1 },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!refloodedInCooldown)
#expect(!carol.courierStore.isEmpty)
@@ -424,7 +424,7 @@ struct CourierEndToEndTests {
bob.sendBroadcastAnnounce()
let announcedAgain = await TestHelpers.waitUntil(
{ bobOut.all(ofType: .announce).contains { $0.timestamp != directAnnounce.timestamp && $0.timestamp != freshAnnounce.timestamp } },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(announcedAgain)
let directAgain = try #require(
@@ -434,7 +434,7 @@ struct CourierEndToEndTests {
let handedOverWithoutLinkProof = await TestHelpers.waitUntil(
{ carolOut.count(ofType: .courierEnvelope) > 1 },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!handedOverWithoutLinkProof)
#expect(!carol.courierStore.isEmpty)
@@ -457,7 +457,7 @@ struct CourierEndToEndTests {
let queuedPacket = await TestHelpers.waitUntil(
{ aliceOut.first(ofType: .courierEnvelope) != nil },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!queuedPacket)
}
@@ -494,7 +494,7 @@ struct CourierEndToEndTests {
carol._test_handlePacket(packet, fromPeerID: alicePeerID, signingPublicKey: alice.getSigningPublicKeyData())
let stored = await TestHelpers.waitUntil(
{ !carol.courierStore.isEmpty },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!stored)
}
@@ -532,7 +532,7 @@ struct CourierEndToEndTests {
carol._test_handlePacket(packet, fromPeerID: alicePeerID, signingPublicKey: alice.getSigningPublicKeyData())
let stored = await TestHelpers.waitUntil(
{ !carol.courierStore.isEmpty },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!stored)
}
@@ -575,7 +575,7 @@ struct CourierEndToEndTests {
carol._test_handlePacket(packet, fromPeerID: mallory.myPeerID, preseedPeer: false)
let stored = await TestHelpers.waitUntil(
{ !carol.courierStore.isEmpty },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!stored)
}
@@ -602,14 +602,14 @@ struct CourierEndToEndTests {
let delivered = await TestHelpers.waitUntil(
{ !bobDelegate.snapshot().isEmpty },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(delivered)
// Give a duplicate delivery a chance to surface, then confirm the
// second copy never reached the delegate.
let duplicated = await TestHelpers.waitUntil(
{ bobDelegate.snapshot().count > 1 },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!duplicated)
#expect(bobDelegate.snapshot().count == 1)
@@ -629,7 +629,7 @@ struct CourierEndToEndTests {
let initiated = await TestHelpers.waitUntil(
{ outbound.count(ofType: .noiseHandshake) > 0 },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!initiated)
@@ -639,7 +639,7 @@ struct CourierEndToEndTests {
ble.sendDeliveryAck(for: "msg-2", to: present)
let initiatedForPresent = await TestHelpers.waitUntil(
{ outbound.count(ofType: .noiseHandshake) > 0 },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(initiatedForPresent)
}
+15 -15
View File
@@ -87,7 +87,7 @@ struct PrekeyEndToEndTests {
peer.sendBroadcastAnnounce()
let published = await TestHelpers.waitUntil(
{ tap.first(ofType: .announce) != nil && tap.first(ofType: .prekeyBundle) != nil },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(published)
return (
@@ -124,7 +124,7 @@ struct PrekeyEndToEndTests {
let cached = await TestHelpers.waitUntil(
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(cached)
@@ -138,7 +138,7 @@ struct PrekeyEndToEndTests {
))
let deposited = await TestHelpers.waitUntil(
{ aliceOut.first(ofType: .courierEnvelope) != nil },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(deposited)
let depositPacket = try #require(aliceOut.first(ofType: .courierEnvelope))
@@ -149,7 +149,7 @@ struct PrekeyEndToEndTests {
carol._test_handlePacket(depositPacket, fromPeerID: alice.myPeerID, signingPublicKey: alice.noiseSigningPublicKeyData())
let carried = await TestHelpers.waitUntil(
{ !carol.courierStore.isEmpty },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(carried)
@@ -158,7 +158,7 @@ struct PrekeyEndToEndTests {
bob.sendBroadcastAnnounce()
let reannounced = await TestHelpers.waitUntil(
{ bobOut.first(ofType: .announce) != nil },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(reannounced)
let handoverTrigger = try #require(bobOut.first(ofType: .announce))
@@ -166,7 +166,7 @@ struct PrekeyEndToEndTests {
let handedOver = await TestHelpers.waitUntil(
{ carolOut.first(ofType: .courierEnvelope) != nil },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(handedOver)
let handoverPacket = try #require(carolOut.first(ofType: .courierEnvelope))
@@ -178,7 +178,7 @@ struct PrekeyEndToEndTests {
bob._test_handlePacket(handoverPacket, fromPeerID: carol.myPeerID)
let received = await TestHelpers.waitUntil(
{ !bobDelegate.snapshot().isEmpty },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(received)
@@ -207,7 +207,7 @@ struct PrekeyEndToEndTests {
bob._test_handlePacket(redelivery, fromPeerID: carol.myPeerID)
let redelivered = await TestHelpers.waitUntil(
{ bobDelegate.snapshot().count == 2 },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!redelivered)
#expect(bobDelegate.snapshot().count == 1)
@@ -235,7 +235,7 @@ struct PrekeyEndToEndTests {
))
let deposited = await TestHelpers.waitUntil(
{ aliceOut.first(ofType: .courierEnvelope) != nil },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(deposited)
let depositPacket = try #require(aliceOut.first(ofType: .courierEnvelope))
@@ -248,7 +248,7 @@ struct PrekeyEndToEndTests {
bob._test_handlePacket(depositPacket, fromPeerID: alice.myPeerID, preseedPeer: false)
let received = await TestHelpers.waitUntil(
{ !bobDelegate.snapshot().isEmpty },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(received)
let delivered = try #require(bobDelegate.snapshot().first)
@@ -272,7 +272,7 @@ struct PrekeyEndToEndTests {
let cached = await TestHelpers.waitUntil(
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!cached)
}
@@ -310,7 +310,7 @@ struct PrekeyEndToEndTests {
let cached = await TestHelpers.waitUntil(
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!cached)
}
@@ -328,7 +328,7 @@ struct PrekeyEndToEndTests {
let cached = await TestHelpers.waitUntil(
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
timeout: TestConstants.defaultTimeout
timeout: TestConstants.settleTimeout
)
#expect(cached)
// The verified bundle now participates in Alice's sync rounds.
@@ -364,7 +364,7 @@ struct PrekeyEndToEndTests {
let cached = await TestHelpers.waitUntil(
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!cached)
#expect(!alice._test_hasGossipPrekeyBundle(for: bob.myPeerID))
@@ -396,7 +396,7 @@ struct PrekeyEndToEndTests {
let cached = await TestHelpers.waitUntil(
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!cached)
#expect(!alice._test_hasGossipPrekeyBundle(for: bob.myPeerID))
+10 -10
View File
@@ -37,7 +37,7 @@ struct GossipSyncManagerTests {
}
manager.scheduleInitialSyncToPeer(PeerID(str: "FFFFFFFFFFFFFFFF"), delaySeconds: 0.0)
try await TestHelpers.waitFor({ delegate.lastPacket != nil }, timeout: TestConstants.shortTimeout)
try await TestHelpers.waitFor({ delegate.lastPacket != nil }, timeout: TestConstants.settleTimeout)
}
let lastPacket = try #require(delegate.lastPacket, "Expected sync packet to be sent")
@@ -394,7 +394,7 @@ struct GossipSyncManagerTests {
)
manager.handleRequestSync(from: peer, request: request)
try await TestHelpers.waitFor({ delegate.packets.count == 2 }, timeout: TestConstants.shortTimeout)
try await TestHelpers.waitFor({ delegate.packets.count == 2 }, timeout: TestConstants.settleTimeout)
// Barrier: flush the sync queue so a late third packet would be visible.
manager._performMaintenanceSynchronously(now: Date())
let sentPackets = delegate.packets
@@ -477,7 +477,7 @@ struct GossipSyncManagerTests {
manager.handleRequestSync(from: peer, request: request)
manager.handleRequestSync(from: peer, request: request)
try await TestHelpers.waitFor({ delegate.packets.count >= 1 }, timeout: TestConstants.shortTimeout)
try await TestHelpers.waitFor({ delegate.packets.count >= 1 }, timeout: TestConstants.settleTimeout)
// Barrier: both requests have been processed once this returns.
manager._performMaintenanceSynchronously(now: Date())
#expect(delegate.packets.count == 1)
@@ -498,7 +498,7 @@ struct GossipSyncManagerTests {
manager.scheduleInitialSyncToPeer(PeerID(str: "FFFFFFFFFFFFFFFF"), delaySeconds: 0.0)
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.settleTimeout)
let packet = try #require(delegate.packets.first)
let request = try #require(RequestSyncPacket.decode(from: packet.payload))
let types = try #require(request.types)
@@ -553,7 +553,7 @@ struct GossipSyncManagerTests {
let request = RequestSyncPacket(p: 4, m: 1, data: Data(), types: .fragment)
manager.handleRequestSync(from: peer, request: request)
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.settleTimeout)
let sentPackets = delegate.packets
#expect(sentPackets.count == 1)
#expect(sentPackets[0].type == MessageType.fragment.rawValue)
@@ -615,7 +615,7 @@ struct GossipSyncManagerTests {
)
manager.handleRequestSync(from: PeerID(str: "FFFFFFFFFFFFFFFF"), request: request)
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.settleTimeout)
// Barrier: flush the sync queue so a late second packet would be visible.
manager._performMaintenanceSynchronously(now: Date())
let sentPackets = delegate.packets
@@ -641,7 +641,7 @@ struct GossipSyncManagerTests {
let stalledID = try #require(Data(hexString: "0102030405060708"))
manager.requestMissingFragments(fragmentIDs: [stalledID])
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.settleTimeout)
let sent = try #require(delegate.packets.first)
#expect(sent.type == MessageType.requestSync.rawValue)
#expect(sent.ttl == 0)
@@ -697,7 +697,7 @@ struct GossipSyncManagerTests {
// And a .prekeyBundle sync request is answered with the stored packet.
let request = RequestSyncPacket(p: 7, m: 1, data: Data(), types: .prekeyBundle)
manager.handleRequestSync(from: PeerID(str: "FFFFFFFFFFFFFFFF"), request: request)
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.settleTimeout)
let served = try #require(delegate.packets.first)
#expect(served.type == MessageType.prekeyBundle.rawValue)
#expect(served.isRSR)
@@ -774,7 +774,7 @@ struct GossipSyncManagerTests {
)
let restored = await TestHelpers.waitUntil(
{ second._messageCount(for: PeerID(hexData: senderID)) == 1 },
timeout: TestConstants.shortTimeout
timeout: TestConstants.settleTimeout
)
#expect(restored)
}
@@ -844,7 +844,7 @@ struct GossipSyncManagerTests {
!FileManager.default.fileExists(atPath: fileURL.path)
&& manager._messageCount(for: PeerID(hexData: senderID)) == 0
},
timeout: TestConstants.shortTimeout
timeout: TestConstants.settleTimeout
)
#expect(erased)
}
+1 -1
View File
@@ -392,7 +392,7 @@ final class NearbyNotesCounterTests: XCTestCase {
}
private func waitUntil(
timeout: TimeInterval = 1.0,
timeout: TimeInterval = TestConstants.settleTimeout,
condition: @escaping @MainActor () -> Bool
) async -> Bool {
let deadline = Date().addingTimeInterval(timeout)
+9 -5
View File
@@ -723,9 +723,9 @@ struct NoiseCoverageTests {
// A failed startup requirement must not strand a late thread in
// the blocking test double after the test has returned.
oldSession.resumeDecrypt()
_ = decryptResult.wait(timeout: 5)
_ = decryptResult.wait(timeout: TestConstants.settleTimeout)
if let promotionResultForCleanup {
_ = promotionResultForCleanup.wait(timeout: 5)
_ = promotionResultForCleanup.wait(timeout: TestConstants.settleTimeout)
}
}
@@ -751,15 +751,19 @@ struct NoiseCoverageTests {
promotionThread.name = "NoiseCoverageTests.staleDecrypt.promote"
promotionThread.qualityOfService = .userInitiated
promotionThread.start()
try #require(promotionStarted.wait(timeout: .now() + 5) == .success)
try #require(promotionStarted.wait(timeout: .now() + TestConstants.settleTimeout) == .success)
#expect(
// test-timing-ok: a NEGATIVE wait it asserts the promotion has
// NOT completed yet, so a long deadline would only make the suite
// slow while still passing. A starved runner can only make this
// more likely to hold, never less.
promotionResult.wait(timeout: 0.05) == nil,
"Promotion must wait for the exact decrypting-session lease"
)
oldSession.resumeDecrypt()
let decrypted = try #require(decryptResult.wait(timeout: 5)).get()
_ = try #require(promotionResult.wait(timeout: 5)).get()
let decrypted = try #require(decryptResult.wait(timeout: TestConstants.settleTimeout)).get()
_ = try #require(promotionResult.wait(timeout: TestConstants.settleTimeout)).get()
#expect(decrypted.plaintext == Data("old session".utf8))
#expect(decrypted.sessionGeneration == oldGeneration)
@@ -580,8 +580,16 @@ final class GeoRelayDirectoryTests: XCTestCase {
/// constrained CI runners (2-core, serialized testing) can starve the
/// detached utility-priority fetch task for seconds before it runs, and
/// a successful wait returns as soon as the condition becomes true.
/// Default deliberately far larger than the work being awaited.
///
/// The directory performs its fetch in a `Task.detached(priority: .utility)`,
/// and utility priority competes with every other suite on a CI runner. At
/// ten seconds the retry-scheduling test timed out at exactly 10.06s with
/// the retry never scheduled which reads like a missing retry rather than
/// a starved background task. Returning as soon as the condition holds means
/// a longer deadline only extends the genuine-failure case.
private func waitUntil(
timeout: TimeInterval = 10.0,
timeout: TimeInterval = TestConstants.settleTimeout,
condition: @escaping @MainActor () async -> Bool
) async -> Bool {
let deadline = Date().addingTimeInterval(timeout)
+1 -1
View File
@@ -188,7 +188,7 @@ struct PTTBurstPlayerTests {
_ condition: () -> Bool,
sourceLocation: SourceLocation = #_sourceLocation
) async {
let deadline = ContinuousClock.now.advanced(by: .seconds(5))
let deadline = ContinuousClock.now.advanced(by: .seconds(TestConstants.settleTimeout))
while !condition(), ContinuousClock.now < deadline {
await Task.yield()
try? await Task.sleep(nanoseconds: 1_000_000)
@@ -15,7 +15,7 @@ final class FavoritesPersistenceServiceTests: XCTestCase {
service.addFavorite(peerNoisePublicKey: peerKey, peerNostrPublicKey: "npub1alice", peerNickname: "Alice")
wait(for: [expectation], timeout: 1.0)
wait(for: [expectation], timeout: TestConstants.settleTimeout)
XCTAssertTrue(service.isFavorite(peerKey))
XCTAssertEqual(service.getFavoriteStatus(for: peerKey)?.peerNickname, "Alice")
XCTAssertNotNil(keychain.load(key: storageKey, service: serviceKey))
@@ -227,7 +227,7 @@ final class GeohashPresenceServiceTests: XCTestCase {
}
private func waitUntil(
timeout: TimeInterval = 1.0,
timeout: TimeInterval = TestConstants.settleTimeout,
condition: @escaping @MainActor () -> Bool
) async -> Bool {
let deadline = Date().addingTimeInterval(timeout)
@@ -355,7 +355,7 @@ final class LocationStateManagerTests: XCTestCase {
}
private func waitUntil(
timeout: TimeInterval = 1.0,
timeout: TimeInterval = TestConstants.settleTimeout,
condition: @escaping @MainActor () -> Bool
) async -> Bool {
let deadline = Date().addingTimeInterval(timeout)
@@ -63,7 +63,7 @@ final class NetworkActivationServiceTests: XCTestCase {
context.service.start()
context.service.setUserTorEnabled(false)
wait(for: [notified], timeout: 1.0)
wait(for: [notified], timeout: TestConstants.negativeWaitWindow)
context.notificationCenter.removeObserver(token)
XCTAssertFalse(context.service.userTorEnabled)
@@ -243,7 +243,7 @@ final class NetworkActivationServiceTests: XCTestCase {
}
private func waitUntil(
timeout: TimeInterval = 1.0,
timeout: TimeInterval = TestConstants.settleTimeout,
condition: @escaping @MainActor () -> Bool
) async -> Bool {
let deadline = Date().addingTimeInterval(timeout)
@@ -69,25 +69,45 @@ final class NetworkReachabilityGateTests: XCTestCase {
XCTAssertNil(d.pendingRemaining(at: t0.addingTimeInterval(2.5)))
}
func test_monitor_duplicateUpdatesDoNotPostponeOfflineCommit() async {
let monitor = NWPathReachabilityMonitor(debounceInterval: 1.0)
/// Wiring only: a duplicate mid-window still yields exactly one committed
/// `false`, published through the monitor's debounce.
///
/// This deliberately makes no assertion about *when* the flush fires. It
/// used to bound elapsed wall-clock time at 1.4 s to prove the deadline was
/// not restarted, which flaked on loaded CI runners one observed run took
/// 3.75 s, because `Task.sleep` and the `asyncAfter` flush are both real
/// time and neither is bounded above on a busy machine. No wall-clock bound
/// can distinguish "deadline preserved" from "runner is slow", so the timing
/// property is asserted where it is computable instead:
/// `test_debounce_duplicateObservationsPreservePendingDeadline` drives
/// `ReachabilityDebounce` with injected timestamps and checks
/// `pendingRemaining` directly.
///
/// The clock is injected here so the debounce arithmetic is deterministic
/// even though the flush itself is scheduled in real time.
func test_monitor_duplicateUpdatesCommitOnceThroughTheDebounce() async {
let clock = MutableDate(now: Date(timeIntervalSince1970: 1_784_000_000))
let monitor = NWPathReachabilityMonitor(
debounceInterval: 0.2,
now: { clock.now }
)
var received: [Bool] = []
let cancellable = monitor.reachabilityPublisher.sink { received.append($0) }
defer { cancellable.cancel() }
let start = Date()
monitor.ingest(reachable: false)
try? await Task.sleep(nanoseconds: 500_000_000)
// Duplicate unsatisfied update mid-window (e.g. interface detail change
// while still offline) must not restart the debounce window.
// Duplicate unsatisfied update mid-window (e.g. an interface detail
// change while still offline).
clock.now = clock.now.addingTimeInterval(0.1)
monitor.ingest(reachable: false)
// Past the original deadline, so the scheduled flush commits.
clock.now = clock.now.addingTimeInterval(0.2)
let committed = await waitUntil(timeout: 2.0) { !received.isEmpty }
// Generous: this is a liveness check, not a latency bound. A real
// regression never committing still fails, just later.
let committed = await waitUntil(timeout: 10.0) { !received.isEmpty }
XCTAssertTrue(committed)
XCTAssertEqual(received, [false])
// The flush must fire at the original ~1.0s deadline, not ~1.5s
// (a full interval after the duplicate).
XCTAssertLessThan(Date().timeIntervalSince(start), 1.4)
}
// MARK: - Service gating
@@ -179,7 +199,7 @@ final class NetworkReachabilityGateTests: XCTestCase {
}
private func waitUntil(
timeout: TimeInterval = 1.0,
timeout: TimeInterval = TestConstants.settleTimeout,
condition: @escaping @MainActor () -> Bool
) async -> Bool {
let deadline = Date().addingTimeInterval(timeout)
@@ -239,3 +259,13 @@ private final class GateMockProxyController: NetworkActivationProxyControlling {
private(set) var proxyModes: [Bool] = []
func setProxyMode(useTor: Bool) { proxyModes.append(useTor) }
}
/// Controllable clock, so debounce arithmetic is deterministic even where the
/// flush itself is scheduled in real time.
private final class MutableDate: @unchecked Sendable {
var now: Date
init(now: Date) {
self.now = now
}
}
@@ -105,11 +105,11 @@ struct NoiseEncryptionServiceTests {
try establishSessions(alice: alice, bob: bob)
let authenticated = await TestHelpers.waitUntil({ recorder.count >= 2 }, timeout: 5.0)
let authenticated = await TestHelpers.waitUntil({ recorder.count >= 2 }, timeout: TestConstants.settleTimeout)
#expect(authenticated)
let generationAuthenticated = await TestHelpers.waitUntil(
{ recorder.generationCount >= 1 },
timeout: 5.0
timeout: TestConstants.settleTimeout
)
#expect(generationAuthenticated)
#expect(alice.hasEstablishedSession(with: bobPeerID))
@@ -166,7 +166,7 @@ struct NoiseEncryptionServiceTests {
#expect(!receiver.hasSession(with: claimedAlicePeerID))
let emittedAuthentication = await TestHelpers.waitUntil(
{ recorder.count > 0 },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!emittedAuthentication)
}
@@ -216,7 +216,7 @@ struct NoiseEncryptionServiceTests {
#expect(try receiver.decrypt(after, from: alicePeerID) == Data("after".utf8))
let emittedReplacementAuthentication = await TestHelpers.waitUntil(
{ recorder.count > 1 },
timeout: TestConstants.shortTimeout
timeout: TestConstants.negativeWaitWindow
)
#expect(!emittedReplacementAuthentication)
}
@@ -652,12 +652,12 @@ struct NoiseEncryptionServiceTests {
)
let retried = await TestHelpers.waitUntil(
{ recorder.messages.count == 1 },
timeout: 1
timeout: TestConstants.longTimeout
)
#expect(retried)
let retryExpired = await TestHelpers.waitUntil(
{ !service.hasSession(with: peerID) },
timeout: 1
timeout: TestConstants.longTimeout
)
#expect(retryExpired)
#expect(recorder.timeoutCount == 1)
@@ -710,7 +710,12 @@ struct NoiseEncryptionServiceTests {
let alice = NoiseEncryptionService(keychain: MockKeychain())
let bob = NoiseEncryptionService(
keychain: MockKeychain(),
ordinaryResponderHandshakeTimeout: 0.06,
// Generous for the same reason as the quarantine-restore test
// (#1483): this timeout also arms during the `establishSessions`
// setup handshake below, where bob is the responder. At 0.06 a
// preempted runner could fire it mid-setup, tear down the half-open
// responder, and make message 3 be answered as a fresh initiation.
ordinaryResponderHandshakeTimeout: 1.0,
ordinaryReconnectRollbackCooldown: 0.3
)
let mallory = NoiseEncryptionService(keychain: MockKeychain())
@@ -741,12 +746,12 @@ struct NoiseEncryptionServiceTests {
let restored = await TestHelpers.waitUntil(
{ bob.hasEstablishedSession(with: alicePeerID) },
timeout: 1
timeout: TestConstants.longTimeout
)
#expect(restored)
let callbackArrived = await TestHelpers.waitUntil(
{ recovery.timeoutCount == 1 },
timeout: 1
timeout: TestConstants.longTimeout
)
#expect(callbackArrived)
@@ -780,7 +785,13 @@ struct NoiseEncryptionServiceTests {
let bob = NoiseEncryptionService(
keychain: MockKeychain(),
ordinaryHandshakeTimeout: 0.04,
ordinaryResponderHandshakeTimeout: 0.04
// Also arms during the `establishSessions` setup handshake below,
// where bob is the responder. Observed failing on a loaded CI
// runner with exactly the signature #1483 documented: the setup's
// `#expect(finalMessage == nil)` saw a 96-byte message 2, because
// the half-open responder had already been torn down and message 3
// was answered as a fresh initiation.
ordinaryResponderHandshakeTimeout: 1.0
)
let alicePeerID = PeerID(publicKey: alice.getStaticPublicKeyData())
let bobPeerID = PeerID(publicKey: bob.getStaticPublicKeyData())
@@ -814,12 +825,12 @@ struct NoiseEncryptionServiceTests {
// initiates one bounded convergence retry; drop that message 1 too.
let retryPrepared = await TestHelpers.waitUntil(
{ recovery.messages.count == 1 },
timeout: 1
timeout: TestConstants.longTimeout
)
#expect(retryPrepared)
let retryExpired = await TestHelpers.waitUntil(
{ !bob.hasSession(with: alicePeerID) },
timeout: 1
timeout: TestConstants.longTimeout
)
#expect(retryExpired)
#expect(recovery.timeoutCount == 1)
@@ -1026,7 +1037,7 @@ struct NoiseEncryptionServiceTests {
let requested = await TestHelpers.waitUntil(
{ recovery.messages.count == 1 },
timeout: 1
timeout: TestConstants.longTimeout
)
#expect(requested)
let retryMessage1 = try #require(recovery.messages.first)
@@ -44,6 +44,46 @@ final class NostrRelayManagerTests: XCTestCase {
XCTAssertTrue(context.sessionFactory.allConnections.allSatisfy { $0.cancelCallCount >= 1 })
}
/// A relay removed while its connection is queued behind Tor bootstrap
/// must stay removed: draining the pending set used to resurrect it,
/// because `dropRelays` never touched `pendingTorConnectionURLs` and a
/// custom relay is in neither the default set nor the allow-list filter.
func test_relayRemovedWhileWaitingForTor_staysRemovedWhenTorBecomesReady() async {
let customURL = "wss://custom-removed.example"
let center = NotificationCenter()
let customRelays = MutableRelayList(urls: [customURL])
let context = makeContext(
permission: .authorized,
userTorEnabled: true,
torEnforced: true,
torIsReady: false,
notificationCenter: center,
customRelays: customRelays
)
// Defaults plus the custom relay all queue while Tor bootstraps.
context.manager.connect()
XCTAssertTrue(context.sessionFactory.requestedURLs.isEmpty)
XCTAssertEqual(context.torWaiter.awaitCallCount, 1)
// The relay is removed by hand before Tor is ready.
customRelays.urls = []
center.post(name: NostrRelaySettings.didChangeNotification, object: nil)
// The settings sink hops through the main queue; let it land.
try? await Task.sleep(nanoseconds: 20_000_000)
context.torWaiter.resolve(true)
let defaultsConnected = await waitUntil {
context.sessionFactory.requestedURLs.count == self.expectedDefaultRelayCount
}
XCTAssertTrue(defaultsConnected)
XCTAssertFalse(
context.sessionFactory.requestedURLs.contains(customURL),
"a relay removed while Tor was bootstrapping must not reconnect when the pending queue drains"
)
}
func test_connect_waitsForTorReadinessBeforeCreatingSessions() async {
let context = makeContext(permission: .authorized, userTorEnabled: true, torEnforced: true, torIsReady: false)
@@ -920,7 +960,7 @@ final class NostrRelayManagerTests: XCTestCase {
try context.sessionFactory.latestConnection(for: relayURL)?.emitEventMessage(subscriptionID: "ordered", event: event)
}
let allDelivered = await waitUntil(timeout: 5.0) {
let allDelivered = await waitUntil(timeout: TestConstants.settleTimeout) {
receivedIDs.count == events.count
}
XCTAssertTrue(allDelivered)
@@ -966,7 +1006,7 @@ final class NostrRelayManagerTests: XCTestCase {
}
try context.sessionFactory.latestConnection(for: quietRelayURL)?.emitEventMessage(subscriptionID: "quiet", event: quietEvent)
let quietDelivered = await waitUntil(timeout: 5.0) { quietDeliveredAfterBusyCount >= 0 }
let quietDelivered = await waitUntil(timeout: TestConstants.settleTimeout) { quietDeliveredAfterBusyCount >= 0 }
XCTAssertTrue(quietDelivered, "relay B's event was never delivered")
// The signal: B did not have to wait for A's entire backlog. If the two
@@ -979,7 +1019,7 @@ final class NostrRelayManagerTests: XCTestCase {
)
// Both relays still drain fully and in order.
let allDelivered = await waitUntil(timeout: 5.0) {
let allDelivered = await waitUntil(timeout: TestConstants.settleTimeout) {
busyDeliveredCount == busyEvents.count
}
XCTAssertTrue(allDelivered)
@@ -1867,7 +1907,7 @@ final class NostrRelayManagerTests: XCTestCase {
}
private func waitUntil(
timeout: TimeInterval = 1.0,
timeout: TimeInterval = TestConstants.settleTimeout,
condition: @escaping @MainActor () -> Bool
) async -> Bool {
let deadline = Date().addingTimeInterval(timeout)
@@ -164,7 +164,7 @@ struct NostrTransportTests {
transport.sendPrivateMessage("hello over nostr", to: shortPeerID, recipientNickname: "Carol", messageID: "pm-1")
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: 5.0)
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: TestConstants.settleTimeout)
#expect(didSend)
let result = try decodeEmbeddedPayload(from: probe.sentEvents[0], recipient: recipient)
let privateMessage = try decodePrivateMessage(from: result.payload)
@@ -209,7 +209,7 @@ struct NostrTransportTests {
transport.sendFavoriteNotification(to: fullPeerID, isFavorite: true)
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: 5.0)
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: TestConstants.settleTimeout)
#expect(didSend)
let result = try decodeEmbeddedPayload(from: probe.sentEvents[0], recipient: recipient)
let privateMessage = try decodePrivateMessage(from: result.payload)
@@ -250,7 +250,7 @@ struct NostrTransportTests {
transport.sendDeliveryAck(for: "ack-1", to: fullPeerID)
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: 5.0)
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: TestConstants.settleTimeout)
#expect(didSend)
let result = try decodeEmbeddedPayload(from: probe.sentEvents[0], recipient: recipient)
@@ -288,7 +288,7 @@ struct NostrTransportTests {
messageID: "geo-1"
)
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: 5.0)
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: TestConstants.settleTimeout)
#expect(didSend)
let event = probe.sentEvents[0]
let result = try decodeEmbeddedPayload(from: event, recipient: recipient)
@@ -562,7 +562,7 @@ final class SecureIdentityStateManagerTests: XCTestCase {
}
private func waitUntil(
timeout: TimeInterval = 1.0,
timeout: TimeInterval = TestConstants.settleTimeout,
condition: @escaping () -> Bool
) async -> Bool {
let deadline = Date().addingTimeInterval(timeout)
@@ -320,7 +320,7 @@ struct SecureIdentityStateManagerVouchTests {
// MARK: - Helpers
private func waitUntil(
timeout: TimeInterval = 1.0,
timeout: TimeInterval = TestConstants.settleTimeout,
condition: @escaping () -> Bool
) async -> Bool {
let deadline = Date().addingTimeInterval(timeout)
+2 -2
View File
@@ -48,7 +48,7 @@ struct GossipSyncBoardTests {
let request = RequestSyncPacket(p: 4, m: 1, data: Data(), types: .board)
manager.handleRequestSync(from: PeerID(str: "FFFFFFFFFFFFFFFF"), request: request)
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.settleTimeout)
let sent = try #require(delegate.packets.first)
#expect(sent.type == MessageType.boardPost.rawValue)
#expect(sent.isRSR)
@@ -69,7 +69,7 @@ struct GossipSyncBoardTests {
let boardRequest = RequestSyncPacket(p: 4, m: 1, data: Data(), types: .board)
manager.handleRequestSync(from: PeerID(str: "FFFFFFFFFFFFFFFF"), request: boardRequest)
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.settleTimeout)
#expect(delegate.packets.count == 1)
#expect(delegate.packets.first?.type == MessageType.boardPost.rawValue)
}
@@ -63,7 +63,7 @@ final class RequestSyncManagerTests: XCTestCase {
}
private func waitUntil(
timeout: TimeInterval = 1.0,
timeout: TimeInterval = TestConstants.settleTimeout,
condition: @escaping () -> Bool
) async -> Bool {
let deadline = Date().addingTimeInterval(timeout)
+42 -2
View File
@@ -11,14 +11,54 @@ import Foundation
struct TestConstants {
static let defaultTimeout: TimeInterval = 5.0
static let shortTimeout: TimeInterval = 1.0
/// For positive waits on work that hops through `Task.detached` or
/// background queues: those contend with every parallel test worker for
/// the global executor, so a loaded CI runner can exceed
/// `defaultTimeout`. `waitUntil` returns as soon as the condition holds,
/// so passing runs never pay the longer timeout.
static let longTimeout: TimeInterval = 10.0
/// **Default deadline for any "wait until this async thing settles" helper.**
///
/// Four separate tests flaked on CI during July 2026 with the same root
/// cause, and it is worth stating the rule rather than re-learning it a
/// fifth time: *a wait deadline is not a latency budget.* It exists so a
/// genuine hang eventually fails the suite. Size it for the worst-case
/// scheduler, never for how long the operation "should" take.
///
/// A CI runner executes many suites at once. Work behind `@MainActor`,
/// `Task.detached(priority: .utility)`, or a `DispatchQueue.asyncAfter` can
/// be starved for seconds one observed run took 3.75 s for a 1 s
/// operation. Deadlines sized to the operation (the old 1 s defaults) turn
/// that starvation into a red build that reads like a product bug.
///
/// This costs nothing when tests pass, because every helper returns as soon
/// as its condition holds. It only extends the genuine-failure case.
///
/// `TestTimingHygieneTests` enforces that wait helpers default to at least
/// `minimumSettleTimeout`.
static let settleTimeout: TimeInterval = 30.0
/// Floor enforced by `TestTimingHygieneTests`. Anything below this is a
/// latency assumption in disguise.
static let minimumSettleTimeout: TimeInterval = 10.0
/// For waits whose **expected outcome is `false`** "prove this does not
/// happen".
///
/// The floor above is wrong for these, and inverted: a negative wait always
/// runs its deadline out, so `settleTimeout` would spend 30 s per case
/// proving nothing extra. Starvation cannot cause a false failure here
/// either a starved runner only makes the thing *less* likely to happen,
/// so the assertion still holds. Short is correct, and naming it says the
/// polarity out loud instead of leaving a bare literal that reads like the
/// mistake this file exists to prevent.
///
/// `TestTimingHygieneTests` accepts this by name. Using it for a wait you
/// expect to succeed reintroduces exactly the flake class it sits next to.
static let negativeWaitWindow: TimeInterval = 1.0
static let testNickname1 = "Alice"
static let testNickname2 = "Bob"
static let testNickname3 = "Charlie"
@@ -0,0 +1,177 @@
import Foundation
import Testing
/// Guards the test suite against the flake class that produced four separate
/// red builds in July 2026: **treating a wait deadline as a latency budget.**
///
/// A CI runner executes many suites at once, so work behind `@MainActor`,
/// `Task.detached(priority: .utility)`, or `DispatchQueue.asyncAfter` can be
/// starved for seconds. One observed run took 3.75 s for a 1 s operation.
/// Deadlines sized to how long the operation "should" take turn that starvation
/// into a red build that reads like a product bug, and the debugging cost lands
/// on whoever opened an unrelated PR.
///
/// Two rules, both enforced below:
///
/// 1. A wait helper's default deadline must be at least
/// `TestConstants.minimumSettleTimeout`. Waits return as soon as their
/// condition holds, so a generous deadline is free in the passing case.
/// 2. No test asserts an *upper bound* on elapsed wall-clock time. Such an
/// assertion cannot distinguish the behaviour under test from a slow
/// machine, so it can only be flaky. Assert the property somewhere it is
/// computable with an injected clock, on the pure logic instead.
///
/// Both rules can be waived per line with `\(Self.waiver)` plus a reason, for
/// the rare case where the timing itself is genuinely the thing under test.
struct TestTimingHygieneTests {
/// Opt-out marker. Reviewers should expect a reason next to it.
static let waiver = "test-timing-ok:"
private static let testsRoot = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent() // TestUtilities
.deletingLastPathComponent() // bitchatTests
private struct Line {
let file: String
let number: Int
let text: String
/// True when the waiver appears on this line or in the comment block
/// immediately above it, so a reason can be written at readable length
/// rather than crammed onto the end of the code line.
let waived: Bool
}
private static func swiftLines() throws -> [Line] {
let enumerator = FileManager.default.enumerator(
at: testsRoot,
includingPropertiesForKeys: nil
)
var out: [Line] = []
while let url = enumerator?.nextObject() as? URL {
guard url.pathExtension == "swift" else { continue }
// This file necessarily contains the patterns it bans.
guard url.lastPathComponent != "TestTimingHygieneTests.swift" else { continue }
let name = url.lastPathComponent
let texts = try String(contentsOf: url, encoding: .utf8)
.components(separatedBy: .newlines)
for (index, text) in texts.enumerated() {
// Scan back over an unbroken run of comment lines.
var waived = text.contains(waiver)
var back = index - 1
while !waived, back >= 0 {
let above = texts[back].trimmingCharacters(in: .whitespaces)
guard above.hasPrefix("//") else { break }
waived = above.contains(waiver)
back -= 1
}
out.append(Line(file: name, number: index + 1, text: text, waived: waived))
}
}
return out
}
private static func isWaived(_ line: Line) -> Bool {
line.waived
}
/// Rule 1: no wait helper may default to a deadline below the floor.
@Test func waitHelpersDoNotDefaultToShortDeadlines() throws {
let lines = try Self.swiftLines()
#expect(!lines.isEmpty, "hygiene scan found no test sources — check the path")
// Two shapes, both of which have flaked here:
// a declaration default `timeout: TimeInterval = 2.5`
// a wait call site `wait(for:, timeout: 1.0)`, `waitUntil(timeout: 5.0)`
//
// Deliberately NOT matched: a bare `timeout:` label on something that is
// not a wait, such as the injected production handshake timeouts in the
// Noise tests. Those are the behaviour under test, and a short value is
// correct there.
let patterns = [
#"(?:timeout|deadline)\s*:\s*TimeInterval\s*=\s*([0-9]+(?:\.[0-9]+)?)"#,
#"(?:wait|waitUntil|waitFor|fulfillment)\s*\([^)]*\btimeout:\s*([0-9]+(?:\.[0-9]+)?)"#
].map { try? NSRegularExpression(pattern: $0) }.compactMap { $0 }
#expect(patterns.count == 2, "hygiene regexes failed to compile")
// Named constants hide the same mistake behind a symbol, and did: the
// fifth flake of the session was `timeout: TestConstants.shortTimeout`
// (1 s) on a positive wait, which a literals-only scan cannot see.
// `shortTimeout` itself is deleted (Periphery flagged it dead once its
// last wait site converted); the ban stays so it cannot come back.
// `negativeWaitWindow` is deliberately absent short is correct there.
let bannedConstants = ["shortTimeout", "defaultTimeout"]
var offenders: [String] = []
for line in lines where !Self.isWaived(line) {
let range = NSRange(line.text.startIndex..., in: line.text)
var flagged = false
for pattern in patterns {
guard let match = pattern.firstMatch(in: line.text, range: range),
let valueRange = Range(match.range(at: 1), in: line.text),
let value = TimeInterval(line.text[valueRange]),
value < TestConstants.minimumSettleTimeout else { continue }
offenders.append("\(line.file):\(line.number)\(value)s: \(line.text.trimmingCharacters(in: .whitespaces))")
flagged = true
break
}
guard !flagged else { continue }
for name in bannedConstants
where line.text.contains("timeout: TestConstants.\(name)") {
offenders.append("\(line.file):\(line.number) — TestConstants.\(name): \(line.text.trimmingCharacters(in: .whitespaces))")
break
}
}
#expect(
offenders.isEmpty,
"""
Wait deadlines below \(TestConstants.minimumSettleTimeout)s are latency \
assumptions and will flake on a loaded runner. Use \
TestConstants.settleTimeout, or add "\(Self.waiver) <reason>" if the \
timing really is what the test asserts.
\(offenders.joined(separator: "\n"))
"""
)
}
/// Rule 2: no test bounds elapsed wall-clock time from above.
///
/// This is the assertion that started it all `XCTAssertLessThan(
/// Date().timeIntervalSince(start), 1.4)` proving a debounce deadline was
/// not restarted. It cannot separate "behaved correctly" from "runner was
/// busy", so it only ever fails for the wrong reason.
@Test func testsDoNotAssertUpperBoundsOnElapsedTime() throws {
let lines = try Self.swiftLines()
let elapsedAssertion = try NSRegularExpression(
pattern: #"(?:XCTAssertLessThan|XCTAssertLessThanOrEqual)\s*\(\s*(?:Date\(\)\.timeIntervalSince|[A-Za-z_][A-Za-z0-9_]*\.timeIntervalSince|ContinuousClock)"#
)
var offenders: [String] = []
for line in lines where !Self.isWaived(line) {
let range = NSRange(line.text.startIndex..., in: line.text)
guard elapsedAssertion.firstMatch(in: line.text, range: range) != nil else { continue }
offenders.append("\(line.file):\(line.number)\(line.text.trimmingCharacters(in: .whitespaces))")
}
#expect(
offenders.isEmpty,
"""
An upper bound on elapsed wall-clock time cannot distinguish the \
behaviour under test from a slow machine. Assert the property where \
it is computable inject a clock, or test the pure logic or add \
"\(Self.waiver) <reason>".
\(offenders.joined(separator: "\n"))
"""
)
}
/// The floor must stay meaningfully above the operations being waited on,
/// and the default must satisfy the rule this file enforces.
@Test func settleTimeoutsAreSelfConsistent() {
#expect(TestConstants.settleTimeout >= TestConstants.minimumSettleTimeout)
#expect(TestConstants.minimumSettleTimeout > TestConstants.defaultTimeout)
}
}
+1 -1
View File
@@ -101,7 +101,7 @@ struct VoiceCaptureSessionTests {
_ condition: () -> Bool,
sourceLocation: SourceLocation = #_sourceLocation
) async {
let deadline = ContinuousClock.now.advanced(by: .seconds(5))
let deadline = ContinuousClock.now.advanced(by: .seconds(TestConstants.settleTimeout))
while !condition(), ContinuousClock.now < deadline {
await Task.yield()
try? await Task.sleep(nanoseconds: 1_000_000)
@@ -59,11 +59,24 @@ struct VoiceNotePlaybackControllerTests {
return url
}
/// Waits for an async settle, then asserts.
///
/// The deadline is deliberately far larger than the work it waits on. Every
/// condition here depends on a `@MainActor` Task that playback schedules
/// (the session acquire and its failure path), and on a CI runner executing
/// many suites in parallel that Task can simply not be scheduled for
/// seconds. At five seconds this timed out on CI and reported *two*
/// failures the wait itself, and the `!isPlaying` that the un-run failure
/// path had not yet reset which reads like a playback bug rather than a
/// starved scheduler.
///
/// A generous deadline costs nothing when the condition holds, since this
/// returns as soon as it does; it only extends the genuine-failure case.
private func waitUntil(
_ condition: () -> Bool,
sourceLocation: SourceLocation = #_sourceLocation
) async {
let deadline = ContinuousClock.now.advanced(by: .seconds(5))
let deadline = ContinuousClock.now.advanced(by: .seconds(TestConstants.settleTimeout))
while !condition(), ContinuousClock.now < deadline {
await Task.yield()
try? await Task.sleep(nanoseconds: 1_000_000)
-342
View File
@@ -1,342 +0,0 @@
# Peer ID Rotation Specification
**Status:** Draft for cross-platform review. The derivations and the wire format **are implemented and tested**; nothing is wired into the shipping mesh.
**Audience:** bitchat iOS and bitchat Android maintainers.
**Requires agreement before going further.** This changes the wire protocol, so neither platform can ship it alone.
**Where the code is:**
| Piece | File |
|---|---|
| Epochs, ID derivation, recognition tags, tag block, binding message | `localPackages/BitFoundation/Sources/BitFoundation/PeerIDRotation.swift` |
| `announceV2 = 0x2C` wire format | `localPackages/BitFoundation/Sources/BitFoundation/AnnounceV2Packet.swift` |
| Executable test vectors | `localPackages/BitFoundation/Tests/BitFoundationTests/PeerIDRotationTests.swift` |
| Wire-format tests | `localPackages/BitFoundation/Tests/BitFoundationTests/AnnounceV2PacketTests.swift` |
The code is deliberately an **opinionated working base, not a finished feature**. Every number and context string in it is a concrete proposal you can disagree with by changing one function and watching a test vector move. What is *not* implemented is the part that carries risk: nothing emits a v2 announce, and `BLEService` parses the type and explicitly ignores it, because consuming it needs both the replacement identity binding (§4.5) and a decision on how unverified presence appears in the peer list (O4).
Three policy decisions were forced by the compiler when the new message type was added, and are worth reviewing as part of this:
- **Not gossip-synced** (`SyncTypeFlags`). Syncing presence would defeat the purpose: a device never in radio range could collect tag blocks, turning a local beacon into a network-wide one.
- **Not padded** (`BLEOutboundPacketPolicy`). At ~75 bytes the smallest bucket would triple the airtime of the most frequent packet in the protocol. The format is already near-constant width; making the capability and geohash fields fixed-width would be cheaper than padding. Open for argument.
- **Parsed but ignored** on receive (`BLEService`), as above.
---
## 1. The problem
Today a passive listener with a BLE dongle, standing in a crowd, can do the following with no cryptographic attack and no active participation:
1. **Detect that a phone is running bitchat.** The service UUID is a fixed constant.
2. **Assign that phone a permanent identifier.** The 8-byte sender ID in every packet header is `SHA-256(noiseStaticPublicKey)[0..8]`, and the Noise static key is generated once and kept in the keychain. It does not rotate. Same phone, same bytes, next week, next city.
3. **Learn the phone's long-term public keys and its self-chosen nickname.** The announce carries the 32-byte Noise static key, the 32-byte Ed25519 signing key, and the nickname, all in cleartext, re-broadcast every 430 seconds and on demand to anything that connects and subscribes.
4. **Reconstruct who was standing near whom.** The announce also carries up to ten neighbour IDs, so one receiver gets the local adjacency graph without needing several receivers or signal-strength trilateration.
For the people this app is explicitly built for, (2) and (4) are the dangerous ones. A protest attendee's phone announces a stable pseudonym and its social graph to anyone within radio range.
iOS BLE address randomization does not help. It randomizes the link-layer address underneath an application layer that publishes a stable identifier above it.
**The correction that matters most:** rotating the peer ID *alone* accomplishes nothing. As long as the announce carries the static keys in cleartext, a rotated ID is re-linked to the same device on its first announce. Rotation and announce confidentiality have to land together or not at all.
## 2. Goals and non-goals
**Goals**
- **G1.** A passive listener cannot link two observations of the same device across rotation periods.
- **G2.** A passive listener cannot learn a device's long-term identity keys or nickname.
- **G3.** Peers who already know each other (mutual favourites) still recognise each other automatically, without an interactive handshake, so existing UX does not regress.
- **G4.** Strangers can still discover and handshake, so the mesh still forms among people who have never met.
- **G5.** Old and new clients interoperate. A mixed mesh keeps working, in both directions, with no flag day.
- **G6.** Rotation does not make identity spoofing easier than it is today.
**Non-goals, explicitly out of scope here**
- Hiding *that* bitchat is in use. The service UUID is a separate problem; BLE requires something discoverable. Tracked separately.
- Traffic-analysis resistance in general: padding coverage, send-time jitter, TTL randomization, and the neighbour-list leak each need their own change. Rotation does not fix them and they do not fix rotation.
- Resistance to an active attacker who connects and completes a handshake. Anyone you handshake with learns your identity; that is what a handshake is for.
## 3. What currently binds an identity, and why rotation breaks it
This is the part most likely to be underestimated, so it is stated precisely.
`peerID == SHA-256(noiseStaticPublicKey)[0..8]` is not merely a convention. It is **the mechanism that makes peer IDs unforgeable**, and it is enforced in two places:
**Announce preflight** — `BLEAnnounceHandlingPolicy.swift:32-35`:
```swift
let derivedPeerID = PeerID(publicKey: announcement.noisePublicKey)
guard derivedPeerID == peerID else { return .reject(.senderMismatch(derivedPeerID: derivedPeerID)) }
```
**Handshake completion** — `NoiseSessionManager.swift:1106-1122`:
```swift
private func authenticatedRemoteKey(_ remoteKey: Curve25519.KeyAgreement.PublicKey,
matches claimedPeerID: PeerID) -> Bool {
let rawKey = remoteKey.rawRepresentation
if claimedPeerID.isShort { return PeerID(publicKey: rawKey) == claimedPeerID }
}
```
Failure throws `NoiseSessionError.peerIdentityMismatch`.
If the peer ID becomes independent of the key, **both checks fail for every peer** and there is nothing left proving that a sender ID belongs to the sender. Any rotation design must therefore ship a *replacement* binding in the same change. This is why the work is a protocol revision and not a patch.
Note also what the existing announce signature does and does not prove. The packet signature covers the sender ID (`BitchatPacket.toBinaryDataForSigning()` zeroes only TTL and the RSR flag), but it is verified against the Ed25519 key carried *inside the same announce* — a self-signature. The code says so plainly (`BLEAnnounceHandlingPolicy.swift:94-103`): an attacker can replay a victim's peer ID and Noise key with their own signing key and a valid self-signature, and only trust-on-first-use pinning of the signing key stops it. So today's binding is "derived ID + TOFU", and a replacement must be at least that strong.
## 4. Design
### 4.1 Epochs
Rotation is on a wall-clock schedule so that two devices that have never met agree on the current period without negotiation.
```
epoch = floor(unixTimeSeconds / ROTATION_PERIOD)
ROTATION_PERIOD = 3600 (1 hour, proposed — see open question O1)
```
`epoch` is a `UInt32`, big-endian wherever it is hashed. Implementations MUST accept `epoch-1`, `epoch`, and `epoch+1` when matching (the ±1 window absorbs clock skew and boundary crossings), following the precedent already set by courier recipient tags (`CourierEnvelope.candidateTags`).
### 4.2 The rotating peer ID
```
K_rot = HKDF-SHA256(ikm: noiseStaticPrivateKey,
salt: "",
info: "bitchat-peer-rotation-v1",
length: 32)
peerID_e = HMAC-SHA256(key: K_rot,
message: "bitchat-peer-id-v2" || uint32be(epoch))[0..8]
```
Properties:
- Derived from the **private** key, so no observer can compute or predict it, and two epochs' IDs are unlinkable.
- Deterministic, so the device recomputes the same ID after a restart within the same epoch.
- Still 8 bytes, so the packet header layout is unchanged.
**It must be derived from private key material.** Deriving from the *public* key would let anyone who has ever seen that key compute every past and future ID, which is worse than doing nothing because it would look like protection. This mistake already exists in the codebase: `CourierEnvelope.recipientTag` is `HMAC(key: recipient's **public** static key, epochDay)`, and since that public key is broadcast in cleartext today, any observer in radio range can compute a peer's courier tags for any day. The whitepaper's claim that couriers "cannot link it across days" does not currently hold. Fixing that is out of scope here but should be tracked; do not copy the pattern.
### 4.3 Recognising peers you already know
With the static keys off the air, mutual favourites need another way to spot each other. Each announce carries a set of **pairwise recognition tags**. For a device A announcing under `peerID_e` to mutual favourite B:
```
S_AB = X25519(A_noiseStaticPrivate, B_noiseStaticPublic) // == X25519(B_priv, A_pub)
K_AB = HKDF-SHA256(ikm: S_AB, salt: "", info: "bitchat-recognition-v1", length: 32)
tag_A→B = HMAC-SHA256(key: K_AB,
message: uint32be(epoch)
|| A_noiseStaticPublic (32)
|| B_noiseStaticPublic (32)
|| peerID_e (8))[0..8]
```
A includes `tag_A→B` in its announce. B computes the same value independently — it holds the same shared secret and both public keys — and matches it against inbound announces. Only A and B can compute it, because it needs one of the two private keys.
Two properties of that MAC input are load-bearing, and an earlier draft of this document got both wrong. They were caught in review of #1487, which is the argument for shipping the code alongside the prose.
**Ordered keys make the tag directional.** The earlier form was `HMAC(K_AB, epoch)`, which is symmetric: A and B would broadcast the *identical* 8 bytes. An observer who saw one value appear in two different announces would learn that those two devices are mutual favourites, and could link their two rotating IDs to each other — handing over precisely the social graph this design exists to hide, and providing a cross-epoch correlation handle. Ordering the keys yields distinct A→B and B→A values, and both parties can still compute both directions because both hold both public keys.
**`peerID_e` binds the tag to the announce carrying it.** Without it a tag depends only on (pair, epoch), so an attacker could lift A's tag out of a recorded announce and replay it in a fresh announce under an ID of their own choosing; B would match and treat that ID as A. Because `epoch-1` is also accepted, the spoof would stay usable into the following period. Binding to the ID reduces this from impersonation-as-any-ID to replaying A's own presence.
**Residual risk, unfixable while announces are unsigned:** an attacker can rebroadcast A's exact announce within the epoch window, making A appear present when absent. Recognition is therefore a **hint only**. A match may populate presence, but anything consequential — routing a DM, showing a verified badge — MUST wait for a completed handshake whose static key equals the favourite that produced the match. See O4.
Rules:
- Tags are **unordered**. Implementations MUST NOT infer anything from position.
- The tag list MUST be padded with uniform random 8-byte values to a fixed count `TAG_SLOTS = 8`, so the number of tags does not disclose how many mutual favourites a device has. Random padding is indistinguishable from a real tag to anyone who cannot compute it.
- With more than `TAG_SLOTS` mutual favourites, a device MUST rotate which favourites occupy the slots across successive announces so all of them eventually see a tag. (Selection strategy is an implementation detail; convergence is not — see O2.)
- A device MUST NOT include a tag for a one-directional favourite, since that would disclose interest to someone who has not reciprocated.
### 4.4 Strangers
Nothing identifying is broadcast for strangers. Discovery still works:
1. A hears an announce from unknown `peerID_e` advertising the rotation capability.
2. A initiates Noise **XX** to that ID.
3. In XX, the responder's static key is sent in message 2 *after* `ee`, and the initiator's in message 3 — both encrypted. A passive observer learns neither.
4. On completion, both sides learn the peer's real static key and fingerprint, exactly as they do today (`handleSessionEstablished`), and the existing `AuthenticatedPeerStatePacket` (Noise payload `0x21`) carries the Ed25519 signing key and capability claims *inside* the session, where they are proven rather than asserted.
So the model becomes **handshake first, identify second**, for anyone who is not already a mutual favourite.
### 4.5 The replacement binding
Inside the completed handshake, each side proves that the rotating ID it was using belongs to its static key:
```
proof = Ed25519-Sign(signingPrivateKey,
"bitchat-peerid-binding-v1"
|| uint32be(epoch)
|| peerID_e (8 bytes)
|| noiseStaticPublicKey (32 bytes))
```
Sent as a new TLV in `AuthenticatedPeerStatePacket`, whose existing structure already carries a version byte, a canonicality-checked capability TLV, and the 32-byte signing key. The receiver verifies:
- **that the `noiseStaticPublicKey` inside the proof is byte-equal to the remote static key the Noise session actually established** — see below, this one is load-bearing, and
- the signature against the signing key in the same packet, **and**
- that the signing key matches whatever it has already pinned for this fingerprint, using the existing trust ladder (authenticated key, then TOFU pin), and
- that `peerID_e` equals the ID the session was actually conducted under, and
- that `epoch` is within the ±1 window.
An earlier draft of this list omitted the first check, which left a hole worth spelling out because it is the kind that survives review. The proof is a self-contained signed blob: nothing in the signature ties it to *the session it arrives on*. So a peer M who has observed A's proof — it travels inside a session, but M can be a peer A legitimately talked to — could replay A's proof verbatim inside M's own session with B. Without the static-key check, B verifies A's signature successfully, sees a well-formed binding, and on **first contact** TOFU-pins A's signing key against M's fingerprint. From then on B attributes M's identity to A's key. Comparing the proof's static key against the key the handshake actually produced closes it: M cannot substitute A's key without also being A.
This replaces `authenticatedRemoteKey`'s derivation check with an explicit signed statement. With the static-key check present it is strictly stronger than today's self-signed announce, because the signing key is checked against a pin rather than taken from the same message. Without it, it is weaker — a reminder that "signed" and "bound to this conversation" are different properties.
Note the canonical-bytes helper for this already half-exists: `NoiseEncryptionService.buildAnnounceSignature` / `verifyAnnounceSignature` / `canonicalAnnounceBytes`, with context `"bitchat-announce-v1"`, are present but unreferenced in production (only tests call them). They sign `context‖peerID(8)‖noiseKey(32)‖ed25519Key(32)‖nickname‖timestampMs`. The binding above is deliberately a **different context string** and a different field set, so the two can never be confused; the dead code should be deleted or repurposed explicitly rather than silently reused.
### 4.6 The announce, before and after
**Today** (`AnnouncementPacket`, TLVs in `Packets.swift:33-40`), all cleartext:
| T | Field | Width |
|---|---|---|
| `0x01` | nickname | var |
| `0x02` | Noise static public key | 32 |
| `0x03` | Ed25519 signing public key | 32 |
| `0x04` | direct neighbours | N × 8, max 10 |
| `0x05` | capabilities | 18 |
| `0x06` | bridge geohash | var |
`0x01`, `0x02`, `0x03` are **required** by the decoder (`Packets.swift:147`).
**Proposed v2 announce.** Because the existing decoder hard-requires the three identity TLVs, a v2 announce cannot simply omit them — that is a parse failure, not a graceful degrade. It therefore needs a distinct message type: **`announceV2 = 0x2C`**.
An earlier draft proposed `0x05` on the grounds that it is unassigned today and sits next to `announce = 0x01`. That was wrong. `0x05` has already been recycled twice — `announce`, then `bulkTransferResponse`, then `fragmentStart` until #446 — so a sufficiently old peer may still map it to a fragment header and misparse presence as a partial message. Values above `voiceFrame = 0x29` have only ever been allocated forward, which is the safe direction; `0x2A`/`0x2B` are spoken for by the courier spray-ack work, leaving `0x2C`. Verified never used anywhere in this repository's history (see O3).
TLVs, all cleartext but none identifying:
| T | Field | Width | Notes |
|---|---|---|---|
| `0x01` | epoch | 4 | `uint32be`; lets a receiver match without guessing |
| `0x02` | recognition tags | `TAG_SLOTS` × 8 = 64 | unordered, random-padded |
| `0x03` | capabilities | 18 | same minimal-LE encoding as today |
| `0x04` | bridge geohash | ≤12 | unchanged semantics |
Deliberately absent: nickname, both public keys, neighbour list.
Worth noting because it is counter-intuitive: **the v2 announce is smaller than the v1 announce**, despite carrying 64 bytes of tags. A v1 announce with a 10-byte nickname and a full neighbour list is roughly 165 payload bytes plus a 64-byte signature; a v2 announce is roughly 75 bytes and unsigned. Dropping two 32-byte keys, the neighbour list, and the signature more than pays for the tag block, so this reduces airtime rather than adding to it.
- **Nickname** moves inside the session (`AuthenticatedPeerStatePacket`). A nickname is a self-chosen, often reused human label; broadcasting it in cleartext is a linkage vector on its own.
- **Neighbour list** is dropped entirely. It exists to seed source routing, and its documented fallback is flooding. Publishing the adjacency graph of a crowd is not a reasonable price for routing efficiency. (Dropping it is independently backward compatible — the TLV is optional on decode — and can ship ahead of this spec.)
**The v2 announce is unsigned.** This is a real trade-off and needs review (O4). There is no key to verify a signature against without disclosing one, so a v2 announce asserts nothing except "somebody is here, and here are some tags". Consequences:
- An attacker can emit v2 announces with arbitrary IDs and random tags — cheap peer-list noise. This is bounded by the existing announce rate limiting, per-central subscription limiting, and connection rate limits, but it is weaker than today.
- An attacker **cannot** impersonate a specific known peer, because it cannot compute that peer's recognition tags without one of the two private keys.
- An attacker cannot get a Noise session, so it cannot send messages, only occupy a peer-list slot.
Mitigation for review: treat a v2 announce as *unverified presence* only, and do not surface it in the peer list until either a recognition tag matches or a handshake completes. That preserves today's property that the peer list reflects authenticated peers.
## 5. Compatibility and rollout
The repo already has the two mechanisms this needs, both proven in production.
**Capability bit.** `PeerCapabilities` is a `UInt64` `OptionSet` with minimal little-endian wire encoding, at least one byte, so "no TLV" and "empty set" stay distinguishable. Crucially `BLEPeerRegistry.capabilitiesWereExplicitlyAdvertised(for:)` distinguishes *old client that sent no TLV* from *new client with the bit off*. Add `peerIDRotation` at the next free bit (bit 11; bit 10 is burned and MUST NOT be reused).
**Observed-version gating.** `MeshTopologyTracker.recordObservedVersion(_:for:)` records the highest protocol version seen from each node, and `computeRoute(…, requiringVersion:)` refuses paths through nodes not observed at that version. `docs/SOURCE_ROUTING.md` records this as the shipped pattern for a compatible rollout. The same shape applies here.
**Phased plan.**
| Phase | Behaviour |
|---|---|
| 1 | Both platforms ship the ability to **parse** v2 announces and advertise the capability, while still sending v1. Purely additive; a v2 announce from a test build is understood rather than dropped. |
| 2 | Send v1 **and** v2 announces, alternating. New clients prefer v2 and ignore the v1 from a peer they have recognised via v2; old clients see only the v1. Costs airtime, buys a no-flag-day transition. |
| 3 | Once telemetry-free judgement says adoption is sufficient, a setting (default on) suppresses v1 announces. A device that suppresses v1 becomes invisible to old clients — that is the intended cost of unlinkability, and it must be stated in the UI, not buried. |
During phases 23 a device runs **both** a stable v1 ID and a rotating v2 ID. They must never appear as two peers; a peer recognised by both paths has to collapse to one entry. The repo has the beginnings of this in `MessageRouter.peerIDAliases` and `ChatPeerIdentityCoordinator.migrateChatState`, but they were built for panic-reset rotation, not steady-state rotation.
## 6. Impact inventory
This is what an implementer must handle. Every item below was verified against the iOS source; Android should expect its own equivalents.
### 6.1 Must be fixed or the feature is broken
| Area | Why | iOS reference |
|---|---|---|
| **Handshake identity check** | `authenticatedRemoteKey` re-derives the ID from the static key and fails for every peer once IDs are independent. Replace with §4.5. | `NoiseSessionManager.swift:1106-1122`, enforced `:714-718` |
| **Announce preflight** | Same derivation check rejects any announce whose ID is not the key's hash. | `BLEAnnounceHandlingPolicy.swift:32-35` |
| **Sealed message outbox** | Queued DM plaintext is keyed by peer ID on disk and survives app kill. A recipient's rotation orphans their queue. Needs re-keying by **fingerprint** (stable) with the peer ID as a lookup hint. This is the single worst offender. | `MessageOutboxStore.swift:66`, `:704-707`, `:746` |
| **Private-media durable IDs** | `stableID` hashes sender and recipient short IDs, and the durable receipt ledger keys accept/tombstone records on it. Rotation silently breaks dedup **and user deletion tombstones**, so deleted media could be re-accepted. | `BitchatFilePacket.swift:183-231`, `BLEPrivateMediaReceiptStore.swift` |
| **Initiator tie-break** | Crossed-initiation resolution compares `localPeerID < peerID`. Both sides must reach the same verdict; a rotation mid-negotiation flips it asymmetrically. Needs a rotation-stable comparison key (fingerprint). | `NoiseSessionManager.swift:83`, `:569`, `:582`, `:603` |
| **Fingerprint-prefix lookups** | Several paths recover a peer from `fingerprint.hasPrefix(peerID)`. These silently return empty, and one of them is what lets a public message from a not-yet-registered peer be accepted at all. | `SecureIdentityStateManager.swift:437-444`; `ChatGroupCoordinator.swift:98-102`, `:432`; `FavoritesPersistenceService.swift:188-195`; `BLEService.swift:2552`, `:2823` |
| **`PeerID.routingData`** | Falls back to `toShort()`, i.e. fingerprint-derived routing bytes. | `PeerID.swift:190-202` |
### 6.2 Degrades gracefully but needs handling
| Area | Effect | iOS reference |
|---|---|---|
| **Noise sessions** | A rotation mid-session leaves an established session under the old ID. Rotation should either be deferred while sessions are live or migrate them explicitly. | `NoiseEncryptionService.swift:1010-1019` |
| **Fragment reassembly** | The reassembly key mixes the 8-byte sender ID, so a rotation mid-transfer strands every in-flight assembly until the 30 s timeout. Defer rotation while fragments are in flight. | `BLEFragmentAssemblyBuffer.swift:4-47` |
| **Dedup LRU** | Keys embed the sender ID, so the same packet crossing a rotation boundary can be reprocessed once. Bounded and probably acceptable. | `BLEReceivePipeline.swift:21` |
| **Source routes / topology** | A remote rotation invalidates cached adjacency, and a rotated relay no longer finds itself in an in-flight v2 route, falling back to flooding. Already the documented fallback. | `MeshTopologyTracker.swift`, `BLERouteForwardingPolicy.swift:62` |
| **Gossip archive** | Archived raw packets keep the old sender ID forever, and packet IDs are sender-derived, so attribution and purge-by-peer break for pre-rotation history. | `GossipMessageArchive.swift`, `PacketIdUtil.swift:8-17` |
| **Read receipts** | The wire receipt carries an 8-byte `readerID`; one sent before and matched after a rotation will not correlate. | `ReadReceipt.swift:47-64` |
### 6.3 Already safe — no work needed
Keyed by fingerprint, Noise key, or Ed25519 key rather than peer ID: the identity cache and every map in it (social identities, verified fingerprints, vouches, blocks), favourites (keyed by Noise static key), courier envelopes and recipient tags, prekey bundles, board posts, bridge drop dedup, group rosters, vouch attestations, and all geohash/location state (keyed by Nostr pubkey). Peer registry, link state, and all Noise session maps are in-memory and session-scoped.
## 7. Test vectors
These live as assertions in `PeerIDRotationTests.swift`, so they run on every build rather than rotting in a table.
All three were **cross-checked against an independent implementation written from this document alone** — Python `hmac`/`hashlib`, HKDF as extract-then-expand with an empty salt — and matched byte for byte. That is the property that matters: the spec text is sufficient to reproduce the numbers without reading the Swift.
With `noiseStaticPrivateKey = 0102…20` (bytes 1 through 32):
```
rotationSecret = HKDF-SHA256(ikm: 0102…20, salt: <empty>,
info: "bitchat-peer-rotation-v1", len: 32)
= fb82dfec0c0a2a4677beca44e2f72c80e7c5de773dd5fce6ee47af83d3c25f09
peerID(epoch=100) = HMAC-SHA256(rotationSecret,
"bitchat-peer-id-v2" || uint32be(100))[0..8]
= f7c08c528506a374
```
With a recognition key derived from a shared secret of 32 × `0x42`, sender key
32 × `0x0A`, recipient key 32 × `0x0B`, and announced ID 8 × `0xA1`:
```
recognitionKey = HKDF-SHA256(ikm: 42×32, salt: <empty>,
info: "bitchat-recognition-v1", len: 32)
tag_A→B(epoch=100) = HMAC-SHA256(recognitionKey,
uint32be(100) || 0A×32 || 0B×32 || A1×8)[0..8]
= 4568f61d61d6cbfb
tag_B→A(epoch=100) (same key, keys swapped)
= 5313c7731f629959
```
Both directions are given because their *difference* is the security property: if
an implementation produces the same value for both, it has reintroduced the
symmetric-tag flaw.
Also asserted, and worth reproducing on Android because they are the properties rather than the numbers: both sides of a real X25519 pair derive the identical tag from opposite key halves; consecutive epochs produce unrelated IDs; the ±1 epoch window matches across a boundary but two epochs out does not; the tag block is always 64 bytes regardless of how many tags it carries; a match is found regardless of slot position; and the binding message is fixed-width so a short input cannot shift a later field into an earlier field's position.
Still to be written jointly: a full `announceV2` packet as a hex blob, and the §4.5 signature over a fixed key. Whichever platform writes a vector, the other MUST reproduce it from this document rather than from the first platform's code.
## 8. Open questions for review
- **O1 — Rotation period.** One hour is a guess balancing unlinkability against churn. Shorter means less linkable and more session/route disruption; longer the reverse. Is there a period that is clearly right, or should it be a build constant both platforms pin?
- **O2 — More than `TAG_SLOTS` favourites.** What is the required convergence guarantee — "every mutual favourite sees a tag within N announces"? Should the slot rotation be deterministic from the epoch so it is testable?
- **O3 — New message type vs. announce version byte.** A distinct `MessageType` is cleanest given the decoder's required TLVs, but it consumes a type value and means two announce paths. Would a version TLV inside the existing type, with the identity TLVs made optional on both platforms first, be preferable?
- **O4 — Unsigned v2 announces.** Binding tags to the announced peer ID removes impersonation-as-any-ID, but a recorded announce can still be rebroadcast verbatim within the epoch window, so a peer can be made to look present when absent. Is "presence is a hint; nothing consequential until a handshake whose static key matches the favourite that produced the match" acceptable? The alternatives are an ephemeral per-epoch signing key with a proof-of-continuity, or a freshness nonce echoed by the recipient — both more machinery and more bytes.
- **O5 — Rotation while a session is live.** Defer rotation until sessions are idle, or rotate and migrate? Deferring is simpler and safer, but a long-lived session pins the ID for its lifetime, which weakens G1 for exactly the people who talk most.
- **O6 — Nickname timing.** Moving the nickname into the session means a stranger's name appears only after a handshake. Is that acceptable UX on both platforms, or does the peer list need a "someone nearby" placeholder state?
- **O7 — Padding is a coordinated change, not a local one.** This started as a question about decoder tolerance and turned into something firmer. `BitchatPacket.toBinaryDataForSigning()` encodes with padding enabled, so **the padding bytes are inside the signed material for every signed packet**. Changing the padding algorithm therefore changes the signed byte stream, and signatures stop verifying against any peer that has not made the identical change. Both outstanding padding fixes are affected: extending coverage beyond `noiseEncrypted`/`noiseHandshake`, and closing the gap where a frame needing more than 255 bytes of padding is emitted unpadded (encoded *frames* of 241256, 497768 and 10091792 bytes ship at exact length today — the arithmetic is over the whole encoded packet that `pad` receives, not the payload alone). Two things to settle: whether Android's decoder also tolerates trailing bytes the way iOS's does (`guard offset <= buf.count`, plus an unpad retry), and whether padding changes ride this protocol revision or get their own capability-gated one.
- **O9 — A seized device recomputes every past peer ID.** `K_rot` is a long-lived secret, so `peerID_e = HMAC(K_rot, epoch)` is computable for *any* epoch by whoever holds it. Someone who seizes a phone, or extracts the Noise static key from a backup, can therefore take historical radio captures and identify which of them were this device — retroactively defeating the unlinkability for every past epoch. Rotation protects against the passive observer, not against later key compromise. A hash ratchet (`K_{e+1} = HKDF(K_e)`, discarding `K_e`) would give forward secrecy for the ID stream, at the cost of state that must survive restarts, tolerate clock jumps, and resynchronise after a gap — none of which is free, and all of which interacts with the ±1 window. Worth deciding deliberately rather than inheriting.
## 9. Relationship to other work
Rotation is the largest item in the radio-layer metadata cluster but not the only one, and the others are cheaper:
- **Drop the neighbour list** and **randomize origin TTL** — both landed separately, since neither needs agreement: see the radio-metadata PR.
- **Extend padding beyond Noise frames, and fix the length-marker gap** — only `noiseEncrypted` and `noiseHandshake` are padded, and `pad` silently declines when the required padding exceeds the single-byte marker, so frames well below their bucket ship unpadded. **Not unilateral**: padding is inside the signed bytes, so this needs both platforms. See O7.
None of these substitute for rotation, and rotation does not substitute for them: a device with a rotating ID that still publishes its neighbour list, or that still marks its own originated packets by TTL, remains linkable.
+21 -4
View File
@@ -18,26 +18,43 @@ In order of how much verification is possible:
Every tagged release has a `SOURCE-MANIFEST.txt` produced by `.github/workflows/source-manifest.yml`. It records the tag, the commit, the git tree hash, and a SHA-256 for every tracked file.
Check a copy of the source against it:
Keep the downloaded manifest *outside* the source tree (say, `/tmp`) — a stray copy inside the checkout would itself trip the completeness checks below. Then check a copy of the source against it:
```sh
# From the root of the source you obtained
grep -v '^#' SOURCE-MANIFEST.txt > /tmp/files.sha256
# From the root of the source you obtained, with the manifest at /tmp
grep -v '^#' /tmp/SOURCE-MANIFEST.txt > /tmp/files.sha256
shasum -a 256 -c /tmp/files.sha256
```
Any `FAILED` line means that file differs from the released source. Investigate before building.
That check alone is not enough. `shasum -c` verifies the files the manifest lists and says nothing about files it does not list — and the Xcode project compiles every source file present in the tree automatically, so a hostile mirror can pass the hash check by leaving every listed file intact and *adding* one. Confirm nothing extra is present:
```sh
# The manifest's path list must match the tree exactly — no missing files, no extras
grep -v '^#' /tmp/SOURCE-MANIFEST.txt | sed 's/^[0-9a-f]* //' | LC_ALL=C sort > /tmp/manifest-paths
find . -type f ! -path './.git/*' | sed 's|^\./||' | LC_ALL=C sort > /tmp/actual-paths
diff /tmp/manifest-paths /tmp/actual-paths # must print nothing
```
In a git checkout the same assurance is one command — it also catches extra files, because they show as untracked. `--ignored` matters: `.gitignore` covers paths like `build/`, plain `git status` would not report a planted file there, and Xcode compiles it all the same:
```sh
git status --porcelain --ignored # must print nothing before you build
```
The single value that covers the whole tree is the git tree hash in the manifest header:
```sh
git rev-parse HEAD^{tree} # must equal the "tree:" line in the manifest
```
Note the tree hash covers tracked content only; it does not see untracked files sitting in the working directory, which is why the emptiness checks above come first.
The manifest itself carries a provenance attestation tying it to the workflow run that produced it, so a manifest handed to you along with a mirror is checkable too:
```sh
gh attestation verify SOURCE-MANIFEST.txt --repo permissionlesstech/bitchat
gh attestation verify /tmp/SOURCE-MANIFEST.txt --repo permissionlesstech/bitchat
```
That last step is what makes this resistant to a hostile mirror. Without it, whoever gives you the source can give you a matching manifest.
+26 -18
View File
@@ -84,6 +84,10 @@ public final class TorManager: ObservableObject {
private var shutdownsInFlight = 0
private var startPendingAfterShutdown = false
private var bootstrapMonitorStarted = false
// Fences the detached poll loop: shutdown, dormancy, and restart each bump
// this, so a loop from a previous attempt cannot run out its deadline and
// report a stall over state that a newer lifecycle event already owns.
private var bootstrapGeneration = 0
private var pathMonitor: NWPathMonitor?
private var isAppForeground: Bool = true
private var lastRestartAt: Date? = nil
@@ -268,24 +272,25 @@ public final class TorManager: ObservableObject {
private func startBootstrapMonitor() {
guard !bootstrapMonitorStarted else { return }
bootstrapMonitorStarted = true
bootstrapGeneration += 1
let generation = bootstrapGeneration
Task.detached(priority: .utility) { [weak self] in
await self?.bootstrapPollLoop()
await self?.bootstrapPollLoop(generation: generation)
}
}
private func bootstrapPollLoop() async {
private func bootstrapPollLoop(generation: Int) async {
let deadline = Date().addingTimeInterval(75)
var didComplete = false
while Date() < deadline {
guard generation == bootstrapGeneration else { return }
let progress = Int(arti_bootstrap_progress())
let summary = getBootstrapSummary()
await MainActor.run {
self.bootstrapProgress = progress
self.bootstrapSummary = summary
if progress >= 100 { self.isStarting = false }
self.recomputeReady()
}
self.bootstrapProgress = progress
self.bootstrapSummary = summary
if progress >= 100 { self.isStarting = false }
self.recomputeReady()
if progress >= 100 {
didComplete = true
@@ -296,17 +301,17 @@ public final class TorManager: ObservableObject {
// Running out the deadline is a reportable outcome, not silence. The
// loop previously just ended, leaving `isStarting` true forever, so a
// blocked network was indistinguishable from a slow one.
// blocked network was indistinguishable from a slow one. A deliberate
// shutdown mid-bootstrap is not a stall, hence the generation check.
if !didComplete {
await MainActor.run {
self.isStarting = false
self.bootstrapDidStall = true
SecureLogger.warning(
"TorManager: bootstrap did not complete within its deadline (progress=\(self.bootstrapProgress)); network may be blocking Tor",
category: .session
)
NotificationCenter.default.post(name: .TorBootstrapDidStall, object: nil)
}
guard generation == bootstrapGeneration else { return }
self.isStarting = false
self.bootstrapDidStall = true
SecureLogger.warning(
"TorManager: bootstrap did not complete within its deadline (progress=\(self.bootstrapProgress)); network may be blocking Tor",
category: .session
)
NotificationCenter.default.post(name: .TorBootstrapDidStall, object: nil)
}
}
@@ -352,6 +357,7 @@ public final class TorManager: ObservableObject {
// Clear isStarting so foreground recovery can proceed if bootstrap was interrupted.
SecureLogger.debug("TorManager: goDormantOnBackground() called", category: .session)
Task { @MainActor in
self.bootstrapGeneration += 1
self.isReady = false
self.socksReady = false
self.isStarting = false
@@ -361,6 +367,7 @@ public final class TorManager: ObservableObject {
public func shutdownCompletely() {
SecureLogger.debug("TorManager: shutdownCompletely() called", category: .session)
startPendingAfterShutdown = false
bootstrapGeneration += 1
shutdownsInFlight += 1
Task.detached { [weak self] in
guard let self = self else { return }
@@ -398,6 +405,7 @@ public final class TorManager: ObservableObject {
SecureLogger.debug("TorManager: restartArti() starting", category: .session)
await MainActor.run {
NotificationCenter.default.post(name: .TorWillRestart, object: nil)
self.bootstrapGeneration += 1
self.isReady = false
self.socksReady = false
self.bootstrapProgress = 0
@@ -1,158 +0,0 @@
//
// AnnounceV2Packet.swift
// BitFoundation
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
/// Identity-free presence announcement for rotating peer IDs.
///
/// The v1 `AnnouncementPacket` broadcasts, in cleartext, every 430 seconds: the
/// nickname, the 32-byte Noise static public key, the 32-byte Ed25519 signing
/// key, and up to ten neighbour IDs. That is a permanent device fingerprint plus
/// the local social graph, free to anyone in radio range. This carries none of
/// it only an epoch, a fixed-size block of pairwise recognition tags, and
/// capability bits.
///
/// Deliberately absent, with reasons:
/// - **Public keys**: they are the linkage. Peers learn them inside the Noise XX
/// handshake, where they are already encrypted on the wire.
/// - **Nickname**: a self-chosen, frequently reused human label. It moves into
/// the session (`AuthenticatedPeerStatePacket`).
/// - **Neighbour list**: it seeds source routing, whose documented fallback is
/// flooding. Publishing a crowd's adjacency graph is not a reasonable price
/// for routing efficiency.
///
/// **Unsigned, on purpose and not without cost.** There is no key to verify a
/// signature against without disclosing one, so this asserts only "somebody is
/// here, and here are some tags". An attacker can therefore emit noise bounded
/// by existing announce and connection rate limits but cannot impersonate a
/// specific peer, because forging a recognition tag needs one of the two private
/// keys, and cannot send anything without completing a handshake. The intended
/// posture is to treat a v2 announce as *unverified presence* and not surface it
/// until a tag matches or a handshake completes. See open question O4 in
/// `docs/PEER-ID-ROTATION.md`.
///
/// Not emitted or consumed by the shipping mesh yet.
// periphery:ignore - intentionally unreferenced by production code; nothing
// emits or consumes this type yet, and BLEService parses it only to ignore it.
// Delete this annotation when the mesh starts using it.
public struct AnnounceV2Packet: Equatable, Sendable {
/// Rotation epoch this announce was built for. Carried explicitly so a
/// receiver matches against a stated epoch instead of guessing.
public let epoch: UInt32
/// Exactly `PeerIDRotation.tagSlots * PeerIDRotation.idLength` bytes.
public let tagBlock: Data
public let capabilities: PeerCapabilities?
/// Coarse rendezvous cell, when bridging. Same semantics as v1.
public let bridgeGeohash: String?
public init(
epoch: UInt32,
tagBlock: Data,
capabilities: PeerCapabilities? = nil,
bridgeGeohash: String? = nil
) {
self.epoch = epoch
self.tagBlock = tagBlock
self.capabilities = capabilities
self.bridgeGeohash = bridgeGeohash
}
private enum TLVType: UInt8 {
case epoch = 0x01
case tagBlock = 0x02
case capabilities = 0x03
case bridgeGeohash = 0x04
}
/// Expected tag-block width. A fixed size is load-bearing: it hides how many
/// mutual favourites a device has.
public static var tagBlockLength: Int {
PeerIDRotation.tagSlots * PeerIDRotation.idLength
}
public func encode() -> Data? {
guard tagBlock.count == Self.tagBlockLength else { return nil }
var data = Data()
data.append(TLVType.epoch.rawValue)
data.append(UInt8(4))
withUnsafeBytes(of: epoch.bigEndian) { data.append(contentsOf: $0) }
data.append(TLVType.tagBlock.rawValue)
data.append(UInt8(tagBlock.count))
data.append(tagBlock)
if let capabilities {
let bytes = capabilities.encoded()
guard bytes.count <= 255 else { return nil }
data.append(TLVType.capabilities.rawValue)
data.append(UInt8(bytes.count))
data.append(bytes)
}
if let bridgeGeohash, !bridgeGeohash.isEmpty {
let bytes = Data(bridgeGeohash.utf8)
guard bytes.count <= 12 else { return nil }
data.append(TLVType.bridgeGeohash.rawValue)
data.append(UInt8(bytes.count))
data.append(bytes)
}
return data
}
public static func decode(from data: Data) -> AnnounceV2Packet? {
var epoch: UInt32?
var tagBlock: Data?
var capabilities: PeerCapabilities?
var bridgeGeohash: String?
var offset = data.startIndex
while offset < data.endIndex {
guard data.distance(from: offset, to: data.endIndex) >= 2 else { return nil }
let rawType = data[offset]
let length = Int(data[data.index(after: offset)])
let valueStart = data.index(offset, offsetBy: 2)
guard data.distance(from: valueStart, to: data.endIndex) >= length else { return nil }
let value = data.subdata(in: valueStart..<data.index(valueStart, offsetBy: length))
switch TLVType(rawValue: rawType) {
case .epoch:
guard length == 4 else { return nil }
epoch = value.reduce(UInt32(0)) { ($0 << 8) | UInt32($1) }
case .tagBlock:
guard length == tagBlockLength else { return nil }
tagBlock = value
case .capabilities:
let decoded = PeerCapabilities(encoded: value)
// Canonicality check, matching AuthenticatedPeerStatePacket: a
// non-minimal encoding would let the same capability set travel
// as different bytes.
guard decoded.encoded() == value else { return nil }
capabilities = decoded
case .bridgeGeohash:
guard length <= 12, let text = String(data: value, encoding: .utf8) else { return nil }
bridgeGeohash = text
case nil:
// Unknown TLV: skip, for forward compatibility.
break
}
offset = data.index(valueStart, offsetBy: length)
}
guard let epoch, let tagBlock else { return nil }
return AnnounceV2Packet(
epoch: epoch,
tagBlock: tagBlock,
capabilities: capabilities,
bridgeGeohash: bridgeGeohash
)
}
}
@@ -40,27 +40,9 @@ public enum MessageType: UInt8 {
// never gossip-synced). Private bursts ride noiseEncrypted instead.
case voiceFrame = 0x29
/// Identity-free presence for rotating peer IDs. Carries an epoch, a fixed
/// block of pairwise recognition tags, and capabilities no nickname, no
/// public keys, no neighbour list. A separate type rather than a version of
/// `announce` because that decoder hard-requires the identity TLVs, so
/// omitting them is a parse failure rather than a graceful degrade.
///
/// `0x2C`, not the seemingly-free `0x05`: that value has been recycled
/// twice already (`announce`, then `bulkTransferResponse`, then
/// `fragmentStart` until #446), and a very old peer that still maps it to a
/// fragment header would misparse presence as a partial message. Values
/// after `voiceFrame` have only ever been allocated forward. `0x2A`/`0x2B`
/// are spoken for by the courier spray-ack work, hence `0x2C`.
///
/// Not emitted or consumed by the shipping mesh yet; see
/// `docs/PEER-ID-ROTATION.md`.
case announceV2 = 0x2C
public var description: String {
switch self {
case .announce: return "announce"
case .announceV2: return "announceV2"
case .message: return "message"
case .leave: return "leave"
case .courierEnvelope: return "courierEnvelope"
@@ -1,315 +0,0 @@
//
// PeerIDRotation.swift
// BitFoundation
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
private import CryptoKit
/// Derivations for rotating peer IDs and pairwise recognition tags.
///
/// See `docs/PEER-ID-ROTATION.md` for the design, the threat model, and the
/// open questions. This type is the executable half of that document: it is
/// deliberately pure (no I/O, no clock of its own, no dependency on the BLE
/// stack) so both platforms can agree on the numbers before anyone wires it
/// into a transport.
///
/// Nothing here is used by the shipping mesh yet.
///
/// ## Why the derivations look like this
///
/// The rotating ID comes from **private** key material. Deriving it from the
/// public key would let anyone who has ever seen that key compute every past
/// and future ID, which is worse than not rotating because it would look like
/// protection. The same mistake is live in `CourierEnvelope.recipientTag`,
/// which is keyed on the recipient's *public* static key and since that key
/// is broadcast in cleartext in every announce today, any observer in radio
/// range can compute a peer's courier tags for any day.
///
/// Recognition tags come from the X25519 shared secret between two static
/// keys, so exactly two parties can compute a given tag and an observer can
/// compute none of them.
// periphery:ignore - intentionally unreferenced by production code. These are
// the reviewable primitives for a protocol change that cannot ship until both
// platforms agree on it; wiring them into the transport is the next step, not
// this one. Delete this annotation when the mesh starts using them.
public enum PeerIDRotation {
// MARK: - Parameters
/// Seconds per rotation epoch. One hour is a starting position, not a
/// settled one: shorter is less linkable but churns sessions, routes, and
/// in-flight fragment reassembly more often. See open question O1.
public static let rotationPeriod: TimeInterval = 3600
/// Bytes of an ID or tag placed on the wire. Matches the existing 8-byte
/// header sender ID, so the packet layout is unchanged.
public static let idLength = 8
/// Fixed number of tag slots in an announce. Padding to a constant hides
/// how many mutual favourites a device has, which is itself identifying.
public static let tagSlots = 8
// MARK: - Context strings
//
// Distinct per use so a value derived for one purpose can never be
// substituted for another. `bitchat-announce-v1` is deliberately NOT reused:
// it belongs to the production-dead announce-signature helpers in
// NoiseEncryptionService, and confusing the two would be a real bug.
private static let rotationInfo = Data("bitchat-peer-rotation-v1".utf8)
private static let peerIDContext = Data("bitchat-peer-id-v2".utf8)
private static let recognitionInfo = Data("bitchat-recognition-v1".utf8)
private static let bindingContext = Data("bitchat-peerid-binding-v1".utf8)
// MARK: - Epochs
/// Epoch number for a point in time. Wall-clock derived so two devices that
/// have never met agree on the current epoch without negotiating.
public static func epoch(at date: Date) -> UInt32 {
let seconds = max(0, date.timeIntervalSince1970)
return UInt32(truncatingIfNeeded: Int(seconds / rotationPeriod))
}
/// Epochs to test when matching, oldest first.
///
/// The ±1 window absorbs clock skew and the moment either side crosses a
/// boundary, mirroring `CourierEnvelope.candidateTags`. Without it, two
/// devices a few seconds apart across a boundary would fail to recognise
/// each other for no reason a person could understand.
public static func candidateEpochs(around date: Date) -> [UInt32] {
let current = epoch(at: date)
return current == 0 ? [0, 1] : [current - 1, current, current + 1]
}
// MARK: - Rotating peer ID
/// Long-lived rotation secret for this device. Derived from the Noise
/// static **private** key, so it never leaves the device and no observer
/// can predict any ID it produces.
public static func rotationSecret(noiseStaticPrivateKey: Data) -> Data {
let derived = HKDF<SHA256>.deriveKey(
inputKeyMaterial: SymmetricKey(data: noiseStaticPrivateKey),
info: rotationInfo,
outputByteCount: 32
)
return derived.withUnsafeBytes { Data($0) }
}
/// This device's peer ID for a given epoch.
public static func peerID(rotationSecret: Data, epoch: UInt32) -> Data {
var message = peerIDContext
message.append(bigEndianBytes(epoch))
let mac = HMAC<SHA256>.authenticationCode(
for: message,
using: SymmetricKey(data: rotationSecret)
)
return Data(mac).prefix(idLength)
}
/// Convenience: the ID this device should be using at `date`.
public static func currentPeerID(noiseStaticPrivateKey: Data, at date: Date) -> Data {
peerID(
rotationSecret: rotationSecret(noiseStaticPrivateKey: noiseStaticPrivateKey),
epoch: epoch(at: date)
)
}
// MARK: - Pairwise recognition tags
/// Symmetric recognition key for a pair, from their X25519 shared secret.
///
/// Both sides compute the identical value from opposite key halves, which
/// is the whole point: recognition needs no round trip, and no third party
/// can derive it.
public static func recognitionKey(sharedSecret: Data) -> Data {
let derived = HKDF<SHA256>.deriveKey(
inputKeyMaterial: SymmetricKey(data: sharedSecret),
info: recognitionInfo,
outputByteCount: 32
)
return derived.withUnsafeBytes { Data($0) }
}
/// The tag `sender` puts in its announce for `recipient` this epoch.
///
/// Three inputs beyond the epoch, each load-bearing:
///
/// - **Ordered keys make the tag directional.** An earlier draft used
/// `HMAC(K_AB, epoch)`, which is symmetric so A and B broadcast the
/// *same* 8 bytes, and an observer who spots one value in two different
/// announces learns those two devices are mutual favourites and can link
/// their rotating IDs to each other. That hands over exactly the social
/// graph this design exists to hide. Ordering the keys gives AB and BA
/// distinct values; both parties can still compute both directions,
/// because both hold both public keys.
/// - **`peerID` binds the tag to the announce carrying it.** Without it the
/// tag depends only on (pair, epoch), so an attacker could lift a tag out
/// of A's announce and replay it under an ID of their choosing; the
/// recipient would match and believe that ID is A. Binding means a lifted
/// tag is only valid alongside A's own ID, which reduces the attack from
/// impersonation-as-any-ID to replaying A's presence.
///
/// Replaying A's own announce within the epoch window remains possible
/// unsigned announces cannot prevent it. Recognition is therefore a hint
/// only, and anything consequential must wait for a completed handshake.
/// See open question O4.
public static func recognitionTag(
recognitionKey: Data,
epoch: UInt32,
senderStaticPublicKey: Data,
recipientStaticPublicKey: Data,
peerID: Data
) -> Data {
var message = bigEndianBytes(epoch)
message.append(fixedWidth(senderStaticPublicKey, 32))
message.append(fixedWidth(recipientStaticPublicKey, 32))
message.append(fixedWidth(peerID, idLength))
let mac = HMAC<SHA256>.authenticationCode(
for: message,
using: SymmetricKey(data: recognitionKey)
)
return Data(mac).prefix(idLength)
}
// MARK: - Tag block
/// Packs tags into the fixed-size announce block, padding with uniform
/// random bytes.
///
/// Random padding is indistinguishable from a real tag to anyone who cannot
/// compute the real ones, so the block discloses neither how many mutual
/// favourites a device has nor which slot belongs to whom. Tags beyond
/// `tagSlots` are dropped here; choosing *which* to carry across successive
/// announces is the caller's problem (open question O2).
public static func tagBlock(
tags: [Data],
randomBytes: (Int) -> Data = Self.secureRandomBytes
) -> Data {
var slots = tags.prefix(tagSlots).map { $0.prefix(idLength) }
// Order must carry no information, so shuffle rather than appending
// real tags at the front.
slots.shuffle()
var block = Data()
for slot in slots {
block.append(slot)
if slot.count < idLength {
block.append(Data(repeating: 0, count: idLength - slot.count))
}
}
let padding = (tagSlots - slots.count) * idLength
if padding > 0 {
block.append(randomBytes(padding))
}
return block
}
/// Splits a received block back into candidate tags.
///
/// Returns nil for a block that is not exactly `tagSlots * idLength`, so a
/// malformed announce is rejected rather than partially interpreted.
public static func tags(fromBlock block: Data) -> [Data]? {
guard block.count == tagSlots * idLength else { return nil }
return stride(from: 0, to: block.count, by: idLength).map {
block.subdata(in: (block.startIndex + $0)..<(block.startIndex + $0 + idLength))
}
}
/// Whether any slot in `block` holds the tag we expect a specific peer to
/// have put there, for an announce carrying `peerID`.
///
/// `senderStaticPublicKey` is the peer we hope sent this (so we compute the
/// direction they would use) and `recipientStaticPublicKey` is our own.
/// Passing them the other way round tests the opposite direction and will
/// not match, which is the point of making tags directional.
///
/// Comparison is constant-time per candidate, and every slot is examined
/// even after a match, so neither the presence of a match nor its slot
/// index is observable through timing.
public static func blockMatches(
_ block: Data,
recognitionKey: Data,
senderStaticPublicKey: Data,
recipientStaticPublicKey: Data,
peerID: Data,
at date: Date
) -> Bool {
guard let slots = tags(fromBlock: block) else { return false }
let expected = candidateEpochs(around: date).map {
recognitionTag(
recognitionKey: recognitionKey,
epoch: $0,
senderStaticPublicKey: senderStaticPublicKey,
recipientStaticPublicKey: recipientStaticPublicKey,
peerID: peerID
)
}
var matched = false
for slot in slots {
for candidate in expected where constantTimeEquals(slot, candidate) {
matched = true
}
}
return matched
}
// MARK: - Identity binding
/// Canonical bytes proving a rotating ID belongs to a static key.
///
/// Signed with the Ed25519 identity key and exchanged **inside** a
/// completed Noise session, this replaces the derivation check that today
/// makes peer IDs unforgeable (`peerID == SHA-256(staticKey)[0..8]`, checked
/// in the announce preflight and again at handshake completion). Once IDs
/// are independent of the key, those checks fail for every peer, so a
/// replacement has to exist before rotation can ship.
///
/// Fixed-width fields throughout: no length prefixes are needed and no two
/// distinct inputs can produce the same bytes.
public static func bindingMessage(
epoch: UInt32,
peerID: Data,
noiseStaticPublicKey: Data
) -> Data {
var out = bindingContext
out.append(bigEndianBytes(epoch))
out.append(fixedWidth(peerID, idLength))
out.append(fixedWidth(noiseStaticPublicKey, 32))
return out
}
// MARK: - Helpers
/// Padding must be indistinguishable from a real tag, so it comes from the
/// system CSPRNG via key generation rather than a general-purpose RNG.
public static func secureRandomBytes(_ count: Int) -> Data {
guard count > 0 else { return Data() }
let key = SymmetricKey(size: SymmetricKeySize(bitCount: count * 8))
return key.withUnsafeBytes { Data($0) }
}
private static func bigEndianBytes(_ value: UInt32) -> Data {
withUnsafeBytes(of: value.bigEndian) { Data($0) }
}
private static func fixedWidth(_ data: Data, _ width: Int) -> Data {
var out = data.prefix(width)
if out.count < width {
out.append(Data(repeating: 0, count: width - out.count))
}
return Data(out)
}
/// Length-independent comparison, so a match cannot be found byte by byte
/// through timing.
private static func constantTimeEquals(_ lhs: Data, _ rhs: Data) -> Bool {
guard lhs.count == rhs.count else { return false }
var difference: UInt8 = 0
for (left, right) in zip(lhs, rhs) {
difference |= left ^ right
}
return difference == 0
}
}
@@ -1,159 +0,0 @@
import Foundation
import Testing
@testable import BitFoundation
/// Wire-format tests for the identity-free announce. These are the second half
/// of the cross-platform contract: Android must encode and decode byte-identical
/// packets, so anything asserted here is a promise, not an implementation detail.
struct AnnounceV2PacketTests {
private var block: Data {
Data(repeating: 0xAB, count: AnnounceV2Packet.tagBlockLength)
}
@Test func typeValueIsStable() {
// Changing this breaks every deployed decoder.
//
// Deliberately NOT 0x05, which merely looks free: it has been recycled
// twice already (announce, then bulkTransferResponse, then fragmentStart
// until #446), so an old peer could still map it to a fragment header
// and misparse presence as a partial message. Values above
// voiceFrame = 0x29 have only ever been allocated forward; 0x2A/0x2B
// belong to the courier spray-ack work.
#expect(MessageType.announceV2.rawValue == 0x2C)
#expect(MessageType(rawValue: 0x2C) == .announceV2)
#expect(MessageType.announceV2.description == "announceV2")
}
@Test func tagBlockIsSixtyFourBytes() {
#expect(AnnounceV2Packet.tagBlockLength == 64)
}
@Test func roundTripsWithEveryField() throws {
let packet = AnnounceV2Packet(
epoch: 495_555,
tagBlock: block,
capabilities: [.bridge, .prekeys],
bridgeGeohash: "u4pruy"
)
let encoded = try #require(packet.encode())
let decoded = try #require(AnnounceV2Packet.decode(from: encoded))
#expect(decoded == packet)
}
@Test func roundTripsWithOnlyRequiredFields() throws {
let packet = AnnounceV2Packet(epoch: 0, tagBlock: block)
let encoded = try #require(packet.encode())
let decoded = try #require(AnnounceV2Packet.decode(from: encoded))
#expect(decoded == packet)
#expect(decoded.capabilities == nil)
#expect(decoded.bridgeGeohash == nil)
}
@Test func epochIsBigEndianOnTheWire() throws {
let encoded = try #require(AnnounceV2Packet(epoch: 0x0102_0304, tagBlock: block).encode())
// TLV 0x01, length 4, then the epoch most-significant byte first.
#expect(Array(encoded.prefix(6)) == [0x01, 0x04, 0x01, 0x02, 0x03, 0x04])
}
/// The whole point of the format: none of the identifying v1 fields appear.
@Test func encodingCarriesNoIdentity() throws {
let noiseKey = Data(repeating: 0x11, count: 32)
let signingKey = Data(repeating: 0x22, count: 32)
let nickname = Data("alice".utf8)
let encoded = try #require(
AnnounceV2Packet(
epoch: 100,
tagBlock: block,
capabilities: [.bridge],
bridgeGeohash: "u4pruy"
).encode()
)
#expect(!encoded.contains(noiseKey))
#expect(!encoded.contains(signingKey))
#expect(encoded.range(of: nickname) == nil)
}
@Test func encodingIsSmallerThanAV1Announce() throws {
let v2 = try #require(
AnnounceV2Packet(epoch: 100, tagBlock: block, capabilities: [.bridge]).encode()
)
// v1 with a 10-byte nickname and a full neighbour list, before its
// 64-byte signature: nickname 12 + noise 34 + signing 34 + neighbours 82
// + capabilities 3.
let v1PayloadEstimate = 12 + 34 + 34 + 82 + 3
#expect(v2.count < v1PayloadEstimate)
}
// MARK: - Rejection
@Test func encodeRejectsAWrongWidthTagBlock() {
// A short block would disclose the favourite count, so it must never go
// on the wire.
#expect(AnnounceV2Packet(epoch: 1, tagBlock: Data(repeating: 0, count: 63)).encode() == nil)
#expect(AnnounceV2Packet(epoch: 1, tagBlock: Data(repeating: 0, count: 65)).encode() == nil)
#expect(AnnounceV2Packet(epoch: 1, tagBlock: Data()).encode() == nil)
}
@Test func encodeRejectsAnOversizedGeohash() {
#expect(AnnounceV2Packet(
epoch: 1,
tagBlock: block,
bridgeGeohash: String(repeating: "u", count: 13)
).encode() == nil)
}
@Test func decodeRequiresEpochAndTagBlock() throws {
// Capabilities alone is not a valid announce.
var onlyCapabilities = Data([0x03, 0x01])
onlyCapabilities.append(PeerCapabilities([.bridge]).encoded())
#expect(AnnounceV2Packet.decode(from: onlyCapabilities) == nil)
// Epoch without a tag block is not either.
let onlyEpoch = Data([0x01, 0x04, 0x00, 0x00, 0x00, 0x64])
#expect(AnnounceV2Packet.decode(from: onlyEpoch) == nil)
}
@Test func decodeRejectsTruncatedAndMalformedInput() {
#expect(AnnounceV2Packet.decode(from: Data()) == nil)
// Declares 4 bytes, supplies 2.
#expect(AnnounceV2Packet.decode(from: Data([0x01, 0x04, 0x00, 0x00])) == nil)
// Dangling type byte with no length.
#expect(AnnounceV2Packet.decode(from: Data([0x01])) == nil)
// Wrong epoch width.
#expect(AnnounceV2Packet.decode(from: Data([0x01, 0x02, 0x00, 0x64])) == nil)
}
@Test func decodeRejectsAWrongWidthTagBlock() {
var data = Data([0x01, 0x04, 0x00, 0x00, 0x00, 0x64])
data.append(0x02)
data.append(UInt8(63))
data.append(Data(repeating: 0xAB, count: 63))
#expect(AnnounceV2Packet.decode(from: data) == nil)
}
@Test func decodeRejectsNonCanonicalCapabilities() throws {
// Same capability set, non-minimal encoding: it must not be accepted, or
// one set could travel as several distinct byte strings.
var data = Data([0x01, 0x04, 0x00, 0x00, 0x00, 0x64])
data.append(0x02)
data.append(UInt8(AnnounceV2Packet.tagBlockLength))
data.append(block)
data.append(0x03)
data.append(UInt8(3))
data.append(Data([0x80, 0x00, 0x00])) // trailing zero bytes are non-minimal
#expect(AnnounceV2Packet.decode(from: data) == nil)
}
@Test func unknownTLVsAreSkippedForForwardCompatibility() throws {
var data = try #require(AnnounceV2Packet(epoch: 100, tagBlock: block).encode())
data.append(0x7F) // a type this build has never heard of
data.append(UInt8(3))
data.append(Data([0x01, 0x02, 0x03]))
let decoded = try #require(AnnounceV2Packet.decode(from: data))
#expect(decoded.epoch == 100)
#expect(decoded.tagBlock == block)
}
}
@@ -1,408 +0,0 @@
import Foundation
import Testing
import CryptoKit
@testable import BitFoundation
/// Executable test vectors for peer ID rotation.
///
/// These are the numbers the Android implementation must reproduce. Two rules
/// for keeping them useful:
///
/// 1. **Reproduce them from `docs/PEER-ID-ROTATION.md`, not from this code.**
/// Deriving the expected values by reading the other platform's
/// implementation proves only that both share a bug.
/// 2. **If a derivation changes, the hex here changes too, deliberately.** A
/// vector that gets "fixed" to match new behavior has stopped being a vector.
///
/// The three `VECTOR:` values below were cross-checked against an independent
/// HKDF/HMAC implementation written from the specification alone (Python
/// `hmac`/`hashlib`, empty salt, extract-then-expand) and matched byte for byte.
/// So the spec text is sufficient to reproduce them without reading this code
/// which is the property Android needs.
struct PeerIDRotationTests {
// A fixed, obviously-fake private key so the vectors are stable.
private let staticPrivateA = Data((0..<32).map { UInt8($0 + 1) }) // 01..20
private let staticPrivateB = Data((0..<32).map { UInt8(0xA0 &+ $0) }) // a0..bf
private func hex(_ data: Data) -> String {
data.map { String(format: "%02x", $0) }.joined()
}
// MARK: - Epochs
@Test func epochIsWallClockDivision() {
#expect(PeerIDRotation.rotationPeriod == 3600)
#expect(PeerIDRotation.epoch(at: Date(timeIntervalSince1970: 0)) == 0)
#expect(PeerIDRotation.epoch(at: Date(timeIntervalSince1970: 3599)) == 0)
#expect(PeerIDRotation.epoch(at: Date(timeIntervalSince1970: 3600)) == 1)
// 2026-07-26T00:00:00Z
#expect(PeerIDRotation.epoch(at: Date(timeIntervalSince1970: 1_784_000_000)) == 495_555)
}
@Test func candidateEpochsCoverTheBoundaryBothWays() {
// Two devices seconds apart across a boundary must still recognise each
// other, so the window spans the neighbouring epochs.
let date = Date(timeIntervalSince1970: 3600 * 100)
#expect(PeerIDRotation.candidateEpochs(around: date) == [99, 100, 101])
}
@Test func candidateEpochsDoNotUnderflowAtTheOrigin() {
// UInt32 underflow here would produce 4294967295 and break matching.
#expect(PeerIDRotation.candidateEpochs(around: Date(timeIntervalSince1970: 0)) == [0, 1])
}
// MARK: - Rotating peer ID
@Test func rotationSecretIsStableForAKey() {
let first = PeerIDRotation.rotationSecret(noiseStaticPrivateKey: staticPrivateA)
let second = PeerIDRotation.rotationSecret(noiseStaticPrivateKey: staticPrivateA)
#expect(first == second)
#expect(first.count == 32)
// VECTOR: HKDF-SHA256(ikm: 01..20, salt: empty, info: "bitchat-peer-rotation-v1", 32)
#expect(hex(first) == "fb82dfec0c0a2a4677beca44e2f72c80e7c5de773dd5fce6ee47af83d3c25f09")
}
@Test func peerIDIsEightBytesAndEpochDependent() {
let secret = PeerIDRotation.rotationSecret(noiseStaticPrivateKey: staticPrivateA)
let a = PeerIDRotation.peerID(rotationSecret: secret, epoch: 100)
let b = PeerIDRotation.peerID(rotationSecret: secret, epoch: 101)
#expect(a.count == PeerIDRotation.idLength)
#expect(b.count == PeerIDRotation.idLength)
// VECTOR: HMAC-SHA256(rotationSecret, "bitchat-peer-id-v2" || uint32be(100))[0..8]
#expect(hex(a) == "f7c08c528506a374")
// The whole point: consecutive epochs are unrelated to an observer.
#expect(a != b)
// Deterministic within an epoch, so a restart keeps the same ID.
#expect(a == PeerIDRotation.peerID(rotationSecret: secret, epoch: 100))
}
@Test func peerIDDiffersBetweenDevices() {
let secretA = PeerIDRotation.rotationSecret(noiseStaticPrivateKey: staticPrivateA)
let secretB = PeerIDRotation.rotationSecret(noiseStaticPrivateKey: staticPrivateB)
#expect(PeerIDRotation.peerID(rotationSecret: secretA, epoch: 100)
!= PeerIDRotation.peerID(rotationSecret: secretB, epoch: 100))
}
@Test func currentPeerIDMatchesTheExplicitEpochForm() {
let date = Date(timeIntervalSince1970: 3600 * 100 + 17)
let viaConvenience = PeerIDRotation.currentPeerID(
noiseStaticPrivateKey: staticPrivateA,
at: date
)
let viaParts = PeerIDRotation.peerID(
rotationSecret: PeerIDRotation.rotationSecret(noiseStaticPrivateKey: staticPrivateA),
epoch: 100
)
#expect(viaConvenience == viaParts)
}
// MARK: - Recognition tags
private var pubA: Data { Data(repeating: 0x0A, count: 32) }
private var pubB: Data { Data(repeating: 0x0B, count: 32) }
private var idA: Data { Data(repeating: 0xA1, count: 8) }
/// The property that makes handshake-free recognition possible: both sides
/// reach the same tag from opposite halves of the key pair.
@Test func bothSidesDeriveTheSameRecognitionTag() throws {
let privA = try Curve25519.KeyAgreement.PrivateKey(rawRepresentation: staticPrivateA)
let privB = try Curve25519.KeyAgreement.PrivateKey(rawRepresentation: staticPrivateB)
let sharedFromA = try privA.sharedSecretFromKeyAgreement(with: privB.publicKey)
let sharedFromB = try privB.sharedSecretFromKeyAgreement(with: privA.publicKey)
let rawA = sharedFromA.withUnsafeBytes { Data($0) }
let rawB = sharedFromB.withUnsafeBytes { Data($0) }
#expect(rawA == rawB)
let keyA = PeerIDRotation.recognitionKey(sharedSecret: rawA)
let keyB = PeerIDRotation.recognitionKey(sharedSecret: rawB)
#expect(keyA == keyB)
// A emits its A->B tag; B computes the same value to look for it.
let emitted = PeerIDRotation.recognitionTag(
recognitionKey: keyA, epoch: 100,
senderStaticPublicKey: privA.publicKey.rawRepresentation,
recipientStaticPublicKey: privB.publicKey.rawRepresentation,
peerID: idA
)
let expected = PeerIDRotation.recognitionTag(
recognitionKey: keyB, epoch: 100,
senderStaticPublicKey: privA.publicKey.rawRepresentation,
recipientStaticPublicKey: privB.publicKey.rawRepresentation,
peerID: idA
)
#expect(emitted == expected)
#expect(emitted.count == PeerIDRotation.idLength)
}
/// Regression, Codex #1487 P1: a symmetric tag means A and B broadcast the
/// identical 8 bytes, so an observer who sees one value in two announces
/// learns those two are mutual favourites and can link their rotating IDs.
/// Tags must therefore differ by direction.
@Test func recognitionTagsAreDirectional() {
let key = PeerIDRotation.recognitionKey(sharedSecret: Data(repeating: 0x42, count: 32))
let aToB = PeerIDRotation.recognitionTag(
recognitionKey: key, epoch: 100,
senderStaticPublicKey: pubA, recipientStaticPublicKey: pubB, peerID: idA
)
let bToA = PeerIDRotation.recognitionTag(
recognitionKey: key, epoch: 100,
senderStaticPublicKey: pubB, recipientStaticPublicKey: pubA, peerID: idA
)
#expect(aToB != bToA)
}
/// Regression, Codex #1487 P1: without the peer ID in the MAC, a tag lifted
/// from someone's announce could be replayed under an attacker-chosen ID and
/// the recipient would accept that ID as the favourite.
@Test func recognitionTagIsBoundToTheAnnouncedPeerID() {
let key = PeerIDRotation.recognitionKey(sharedSecret: Data(repeating: 0x42, count: 32))
let real = PeerIDRotation.recognitionTag(
recognitionKey: key, epoch: 100,
senderStaticPublicKey: pubA, recipientStaticPublicKey: pubB, peerID: idA
)
let underAttackerID = PeerIDRotation.recognitionTag(
recognitionKey: key, epoch: 100,
senderStaticPublicKey: pubA, recipientStaticPublicKey: pubB,
peerID: Data(repeating: 0xFF, count: 8)
)
#expect(real != underAttackerID)
// And the lifted tag must not verify against the attacker's ID.
let block = PeerIDRotation.tagBlock(tags: [real])
#expect(!PeerIDRotation.blockMatches(
block, recognitionKey: key,
senderStaticPublicKey: pubA, recipientStaticPublicKey: pubB,
peerID: Data(repeating: 0xFF, count: 8),
at: Date(timeIntervalSince1970: 3600 * 100)
))
}
@Test func recognitionTagRotatesWithTheEpoch() {
let key = PeerIDRotation.recognitionKey(sharedSecret: Data(repeating: 0x42, count: 32))
let now = PeerIDRotation.recognitionTag(
recognitionKey: key, epoch: 100,
senderStaticPublicKey: pubA, recipientStaticPublicKey: pubB, peerID: idA
)
let next = PeerIDRotation.recognitionTag(
recognitionKey: key, epoch: 101,
senderStaticPublicKey: pubA, recipientStaticPublicKey: pubB, peerID: idA
)
#expect(now != next)
// VECTOR: HMAC-SHA256(HKDF(ikm: 0x42*32, info: "bitchat-recognition-v1"),
// uint32be(100) || 0x0A*32 || 0x0B*32 || 0xA1*8)[0..8]
#expect(hex(now) == "4568f61d61d6cbfb")
}
@Test func aThirdPartyCannotDeriveAPairsTag() {
// An observer holding a *different* shared secret gets a different tag,
// which is what stops it from tracking the pair.
let pair = PeerIDRotation.recognitionKey(sharedSecret: Data(repeating: 0x01, count: 32))
let other = PeerIDRotation.recognitionKey(sharedSecret: Data(repeating: 0x02, count: 32))
#expect(PeerIDRotation.recognitionTag(
recognitionKey: pair, epoch: 7,
senderStaticPublicKey: pubA, recipientStaticPublicKey: pubB, peerID: idA
) != PeerIDRotation.recognitionTag(
recognitionKey: other, epoch: 7,
senderStaticPublicKey: pubA, recipientStaticPublicKey: pubB, peerID: idA
))
}
// MARK: - Tag block
@Test func tagBlockIsAlwaysFullWidth() {
let expected = PeerIDRotation.tagSlots * PeerIDRotation.idLength
for count in 0...PeerIDRotation.tagSlots {
let tags = (0..<count).map { Data(repeating: UInt8($0 + 1), count: 8) }
#expect(PeerIDRotation.tagBlock(tags: tags).count == expected)
}
}
/// A device with one favourite and a device with six must be
/// indistinguishable from the block, or the block leaks social-graph size.
@Test func tagBlockHidesHowManyFavouritesThereAre() {
let one = PeerIDRotation.tagBlock(tags: [Data(repeating: 0xAA, count: 8)])
let six = PeerIDRotation.tagBlock(
tags: (1...6).map { Data(repeating: UInt8($0), count: 8) }
)
#expect(one.count == six.count)
}
@Test func tagBlockDropsOverflowRatherThanGrowing() {
let tags = (1...(PeerIDRotation.tagSlots + 5)).map { Data(repeating: UInt8($0), count: 8) }
#expect(PeerIDRotation.tagBlock(tags: tags).count == PeerIDRotation.tagSlots * 8)
}
@Test func padOnlyBlockUsesFreshRandomnessEachTime() {
// Repeated identical padding would make an empty block recognisable.
let first = PeerIDRotation.tagBlock(tags: [])
let second = PeerIDRotation.tagBlock(tags: [])
#expect(first != second)
}
@Test func tagsRoundTripThroughTheBlock() throws {
let real = Data(repeating: 0xC3, count: 8)
let block = PeerIDRotation.tagBlock(
tags: [real],
randomBytes: { Data(repeating: 0x00, count: $0) }
)
let slots = try #require(PeerIDRotation.tags(fromBlock: block))
#expect(slots.count == PeerIDRotation.tagSlots)
#expect(slots.contains(real))
}
@Test func malformedBlockIsRejectedRatherThanPartiallyRead() {
#expect(PeerIDRotation.tags(fromBlock: Data()) == nil)
#expect(PeerIDRotation.tags(fromBlock: Data(repeating: 0, count: 7)) == nil)
#expect(PeerIDRotation.tags(fromBlock: Data(repeating: 0, count: 65)) == nil)
}
// MARK: - Matching
private func matchFixture() -> (key: Data, tag: Data, date: Date) {
let date = Date(timeIntervalSince1970: 3600 * 100)
let key = PeerIDRotation.recognitionKey(sharedSecret: Data(repeating: 0x77, count: 32))
let tag = PeerIDRotation.recognitionTag(
recognitionKey: key,
epoch: PeerIDRotation.epoch(at: date),
senderStaticPublicKey: pubA,
recipientStaticPublicKey: pubB,
peerID: idA
)
return (key, tag, date)
}
@Test func blockMatchesRecogniseAPeerAnywhereInTheBlock() {
let (key, tag, date) = matchFixture()
// Slot order must not matter, so assert across many shuffles.
for _ in 0..<20 {
let block = PeerIDRotation.tagBlock(tags: [tag])
#expect(PeerIDRotation.blockMatches(
block, recognitionKey: key,
senderStaticPublicKey: pubA, recipientStaticPublicKey: pubB,
peerID: idA, at: date
))
}
}
/// Testing the wrong direction must fail, or the directional fix would be
/// cosmetic.
@Test func blockDoesNotMatchTheOppositeDirection() {
let (key, tag, date) = matchFixture()
let block = PeerIDRotation.tagBlock(tags: [tag])
#expect(!PeerIDRotation.blockMatches(
block, recognitionKey: key,
senderStaticPublicKey: pubB, recipientStaticPublicKey: pubA,
peerID: idA, at: date
))
}
@Test func blockMatchesToleratesTheEpochBoundary() {
let date = Date(timeIntervalSince1970: 3600 * 100)
let key = PeerIDRotation.recognitionKey(sharedSecret: Data(repeating: 0x11, count: 32))
func tag(epoch: UInt32) -> Data {
PeerIDRotation.recognitionTag(
recognitionKey: key, epoch: epoch,
senderStaticPublicKey: pubA, recipientStaticPublicKey: pubB, peerID: idA
)
}
func matches(_ candidate: Data) -> Bool {
PeerIDRotation.blockMatches(
PeerIDRotation.tagBlock(tags: [candidate]), recognitionKey: key,
senderStaticPublicKey: pubA, recipientStaticPublicKey: pubB,
peerID: idA, at: date
)
}
// A peer whose clock has already ticked over still matches.
#expect(matches(tag(epoch: 101)))
// Two epochs out is outside the window and must not.
#expect(!matches(tag(epoch: 98)))
}
@Test func randomBlockDoesNotMatch() {
let (key, _, date) = matchFixture()
#expect(!PeerIDRotation.blockMatches(
PeerIDRotation.tagBlock(tags: []), recognitionKey: key,
senderStaticPublicKey: pubA, recipientStaticPublicKey: pubB,
peerID: idA, at: date
))
}
// MARK: - Identity binding
@Test func bindingMessageIsFixedWidthAndContextSeparated() {
let message = PeerIDRotation.bindingMessage(
epoch: 100,
peerID: Data(repeating: 0xAB, count: 8),
noiseStaticPublicKey: Data(repeating: 0xCD, count: 32)
)
let context = Data("bitchat-peerid-binding-v1".utf8)
#expect(message.count == context.count + 4 + 8 + 32)
#expect(message.starts(with: context))
// Must not collide with the production-dead announce-signature helpers,
// which use "bitchat-announce-v1".
#expect(!message.starts(with: Data("bitchat-announce-v1".utf8)))
}
@Test func bindingMessagePadsShortInputsRatherThanShifting() {
// Fixed-width fields mean a short ID cannot shift the key into the ID's
// position and produce a message that verifies for the wrong pairing.
let short = PeerIDRotation.bindingMessage(
epoch: 1,
peerID: Data([0x01]),
noiseStaticPublicKey: Data([0x02])
)
let padded = PeerIDRotation.bindingMessage(
epoch: 1,
peerID: Data([0x01]) + Data(repeating: 0, count: 7),
noiseStaticPublicKey: Data([0x02]) + Data(repeating: 0, count: 31)
)
#expect(short == padded)
}
@Test func bindingMessageChangesWithEveryField() {
let base = PeerIDRotation.bindingMessage(
epoch: 1,
peerID: Data(repeating: 0x01, count: 8),
noiseStaticPublicKey: Data(repeating: 0x02, count: 32)
)
#expect(base != PeerIDRotation.bindingMessage(
epoch: 2,
peerID: Data(repeating: 0x01, count: 8),
noiseStaticPublicKey: Data(repeating: 0x02, count: 32)
))
#expect(base != PeerIDRotation.bindingMessage(
epoch: 1,
peerID: Data(repeating: 0x03, count: 8),
noiseStaticPublicKey: Data(repeating: 0x02, count: 32)
))
#expect(base != PeerIDRotation.bindingMessage(
epoch: 1,
peerID: Data(repeating: 0x01, count: 8),
noiseStaticPublicKey: Data(repeating: 0x04, count: 32)
))
}
@Test func bindingMessageVerifiesUnderTheIdentityKey() throws {
let signing = Curve25519.Signing.PrivateKey()
let message = PeerIDRotation.bindingMessage(
epoch: 100,
peerID: Data(repeating: 0xAB, count: 8),
noiseStaticPublicKey: Data(repeating: 0xCD, count: 32)
)
let signature = try signing.signature(for: message)
#expect(signing.publicKey.isValidSignature(signature, for: message))
// A different epoch must not verify: replaying a binding into a later
// epoch is exactly what this prevents.
let other = PeerIDRotation.bindingMessage(
epoch: 101,
peerID: Data(repeating: 0xAB, count: 8),
noiseStaticPublicKey: Data(repeating: 0xCD, count: 32)
)
#expect(!signing.publicKey.isValidSignature(signature, for: other))
}
}
@@ -11,7 +11,6 @@ import Foundation
// Kept local until the test-helper module is split out.
struct TestConstants {
static let defaultTimeout: TimeInterval = 5.0
static let shortTimeout: TimeInterval = 1.0
static let longTimeout: TimeInterval = 10.0
static let testNickname1 = "Alice"