mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-27 10:05:20 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ee52ce1e7 | ||
|
|
00af91ea17 | ||
|
|
6fd44086b3 | ||
|
|
1a411970f9 |
@@ -49,9 +49,44 @@ BitChat uses a **hybrid messaging architecture** with two complementary transpor
|
||||
|
||||
BitChat's private-envelope format is proprietary and is **not** NIP-17,
|
||||
NIP-44, or NIP-59 compatible. It uses Nostr as a relay transport but only
|
||||
interoperates with BitChat clients: private payloads travel inside kind-1059
|
||||
events whose `v2:`-prefixed content is a BitChat-specific XChaCha20-Poly1305
|
||||
construction, not NIP-44 encryption.
|
||||
interoperates with BitChat clients. New envelopes use provisional,
|
||||
BitChat-specific public kind 1402 (not a formally reserved Nostr kind),
|
||||
encrypted inner kinds 1403/1404, and the `bitchat-pm-v1:` content prefix.
|
||||
For mixed-version delivery, clients publish both the primary kind-1402
|
||||
envelope and a compatibility kind-1059 copy. There is no date-based cutoff:
|
||||
kind 1059 must remain enabled until a coordinated iOS/Android release confirms
|
||||
that supported older clients have migrated. Receivers subscribe to both kinds
|
||||
and deduplicate the authenticated embedded BitChat payload.
|
||||
|
||||
Private-envelope migration compatibility:
|
||||
|
||||
| Sender | Receiver | Delivery path |
|
||||
| --- | --- | --- |
|
||||
| New iOS | New iOS | Kind 1402 is primary; the kind-1059 twin is deduplicated |
|
||||
| New iOS | Released iOS | Compatibility kind 1059 |
|
||||
| New iOS | Current Android | Compatibility kind 1059 |
|
||||
| Released iOS | New iOS | Kind 1059 with the released empty inner-tag shape |
|
||||
| Current Android | New iOS | Kind 1059 with exactly the authenticated recipient `p` tag |
|
||||
|
||||
New kind-1402 envelopes require an empty inner tag list. The Android recipient
|
||||
tag exception is intentionally confined to legacy kind 1059 and accepts only
|
||||
the exact addressed recipient. Mailbox subscriptions cover the 24-hour
|
||||
delivery window plus Android's full 48-hour timestamp randomization and 15
|
||||
minutes of clock skew. Recovery uses
|
||||
one independent 500-event relay filter per wire kind so either format cannot
|
||||
consume the other's result budget.
|
||||
|
||||
The two outbound migration copies are admitted to the relay queue as one
|
||||
protected batch. Queue pressure evicts ephemeral traffic first, never one copy
|
||||
of a private pair; if protected capacity is exhausted, the entire new pair is
|
||||
rejected as a whole. User-message rejection becomes a visible failed delivery;
|
||||
acknowledgements and favorite notifications retain the exact pair in a
|
||||
process-wide 256-entry bounded retry queue. A sustained outage beyond that
|
||||
bound evicts the oldest whole control pair with an explicit warning, never half
|
||||
a pair.
|
||||
If either socket write fails, the same queued pair remains pending and both
|
||||
copies are replayed on the replacement connection. A terminal relay target is
|
||||
pruned after bounded retries so one dead relay cannot wedge healthy delivery.
|
||||
|
||||
### Channel Types
|
||||
|
||||
|
||||
+7
-3
@@ -78,9 +78,9 @@ Courier envelopes are sealed to the recipient's *static* key with the one-way No
|
||||
|
||||
### 5.3 Nostr Path
|
||||
|
||||
Private messages to mutual favorites use BitChat's proprietary private-envelope protocol. An unsigned inner message (kind 14) is encrypted and placed in a sender-signed seal (kind 13); that seal is encrypted again inside a public envelope (kind 1059) signed by a one-time key, so relays learn neither the stable sender identity nor the content. Each encrypted content field is `v2:` followed by base64url of a 24-byte nonce, XChaCha20-Poly1305 ciphertext, and its 16-byte tag. Keys come from secp256k1 ECDH and HKDF-SHA256 (the derivation reuses a "nip44-v2" info label but is not the NIP-44 key schedule).
|
||||
Private messages to mutual favorites use BitChat's proprietary private-envelope protocol. An unsigned inner message (kind 1404) is encrypted and placed in a sender-signed seal (kind 1403); that seal is encrypted again inside a public envelope (kind 1402) signed by a one-time key. Kind 1402 is a provisional BitChat-specific assignment, not a formally reserved Nostr kind. Each encrypted content field is `bitchat-pm-v1:` followed by base64url of a 24-byte nonce, XChaCha20-Poly1305 ciphertext, and its 16-byte tag. Keys come from secp256k1 ECDH and HKDF-SHA256 with a BitChat-specific domain separator.
|
||||
|
||||
This format reuses NIP-17/NIP-59 kind numbers but is **not NIP-17, NIP-44, or NIP-59 compatible** and interoperates only with BitChat clients. The outer `p` tag exposes the recipient's Nostr public key to relays; the plaintext and stable sender identity remain inside authenticated ciphertext. Public seal and envelope timestamps are randomized by up to ±15 minutes, while the actual message timestamp is encrypted. The protocol does not provide forward secrecy: compromise of the recipient's static Nostr private key can expose stored envelopes addressed to that key.
|
||||
This format is **not NIP-17, NIP-44, or NIP-59 compatible** and interoperates only with BitChat clients. The outer `p` tag exposes the recipient's Nostr public key to relays; the stable sender identity and plaintext remain inside authenticated ciphertext. New-format seal and envelope timestamps are randomized up to 15 minutes into the past, while the actual message timestamp is encrypted. Legacy Android envelopes can carry public-layer timestamps randomized across the preceding 48 hours. The protocol does not provide forward secrecy: compromise of the recipient's static Nostr private key can expose stored envelopes.
|
||||
|
||||
## 6. Store and Forward
|
||||
|
||||
@@ -107,7 +107,11 @@ Public broadcast messages are cached (1000 packets) and reconciled between peers
|
||||
|
||||
### 6.4 Nostr Mailboxes
|
||||
|
||||
BitChat private envelopes rest on Nostr relays; clients re-subscribe with a 24-hour lookback on reconnect, covering the both-devices-offline case for mutual favorites whenever either side touches the internet.
|
||||
BitChat private envelopes rest on Nostr relays; clients re-subscribe across the 24-hour delivery window plus the full 48-hour timestamp randomization used by deployed Android clients and 15 minutes of clock skew (72 hours 15 minutes total). During the rolling format migration, clients subscribe to both the provisional BitChat-specific kind 1402 and historical kind 1059. Recovery places the kinds in separate filters within one REQ, each with an independent 500-event limit, so traffic in one format cannot starve the other. Each logical payload is published first in the primary kind-1402 format and then as a compatibility legacy copy for older iOS and current Android clients. There is no calendar cutoff: legacy publication and reception remain until a coordinated cross-platform release confirms supported clients have migrated. Bounded dedup of the authenticated embedded payload collapses the migration pair at receivers.
|
||||
|
||||
The relay send queue treats those two events as one protected batch. Capacity pressure removes ephemeral events before regular traffic and never evicts only one private-envelope copy. A queue containing only protected batches rejects a new pair as a whole: user messages surface a failed delivery, while acknowledgements and favorite notifications retain the exact pair in one process-wide 256-entry bounded-backoff retry queue shared by account and short-lived geohash transports. Sustained control-payload overflow evicts the oldest whole pair with an explicit warning rather than growing memory or splitting formats. After either socket write fails, the same pair remains pending and both copies are replayed on the replacement connection. Terminal relay targets are pruned after bounded connection retries; a batch that succeeded elsewhere retires normally, while an all-target failure returns to the transport's failure/retry policy. Receive-side dedup suppresses the replay if one copy had already reached the relay.
|
||||
|
||||
Released iOS legacy envelopes use an empty inner tag list. Current Android legacy envelopes use exactly one inner `p` tag naming the recipient. The kind-1059 decoder accepts only those two shapes after authenticating the outer recipient and sender-signed seal; alternate recipients, duplicate tags, and extra tags are rejected. Kind 1402 remains strict and permits no inner tags.
|
||||
|
||||
### 6.5 Delivery Metrics
|
||||
|
||||
|
||||
+384
-271
@@ -9,24 +9,29 @@ import Security
|
||||
|
||||
/// BitChat's private-envelope protocol transported over Nostr relays.
|
||||
///
|
||||
/// This construction is deliberately BitChat-specific and is **not** NIP-17,
|
||||
/// NIP-44, or NIP-59 compatible, even though it historically reuses those
|
||||
/// NIPs' kind numbers (1059/13/14) and a `v2:` content prefix. It uses Nostr
|
||||
/// events and secp256k1 identities, but the XChaCha20-Poly1305 payload layout
|
||||
/// and key derivation are proprietary and interoperate only with BitChat
|
||||
/// clients.
|
||||
/// This is deliberately BitChat-specific and is not NIP-17, NIP-44, or NIP-59.
|
||||
/// It uses Nostr events and secp256k1 identities, but its XChaCha20-Poly1305
|
||||
/// payload layout is proprietary and interoperates only with BitChat clients.
|
||||
struct NostrProtocol {
|
||||
|
||||
/// Nostr event kinds
|
||||
enum EventKind: Int {
|
||||
case metadata = 0
|
||||
case textNote = 1
|
||||
// BitChat's proprietary private-envelope layers. These reuse the
|
||||
// NIP-17/NIP-59 kind numbers (14/13/1059) for historical reasons, but
|
||||
// the encrypted payloads are BitChat-specific and not NIP-compatible.
|
||||
case dm = 14 // unsigned inner message (inside ciphertext)
|
||||
case seal = 13 // sender-signed seal (inside ciphertext)
|
||||
case giftWrap = 1059 // public outer envelope (one-time key)
|
||||
// Compatibility for BitChat releases that incorrectly emitted the
|
||||
// proprietary payload under standard NIP kinds. Kind 1059 continues
|
||||
// to be published and read until a coordinated cross-platform release
|
||||
// explicitly removes it; all three legacy layers remain readable.
|
||||
case legacyNIP59Seal = 13
|
||||
case legacyNIP17DirectMessage = 14
|
||||
case legacyNIP59GiftWrap = 1059
|
||||
// Provisional BitChat-specific regular event kinds. These are not
|
||||
// formally reserved by the Nostr kind registry. Only
|
||||
// `privateEnvelope` is published; message and seal exist solely
|
||||
// inside ciphertext.
|
||||
case privateEnvelope = 1402
|
||||
case privateSeal = 1403
|
||||
case privateMessage = 1404
|
||||
case ephemeralEvent = 20000
|
||||
case geohashPresence = 20001
|
||||
case deletion = 5 // NIP-09 event deletion request
|
||||
@@ -36,209 +41,290 @@ struct NostrProtocol {
|
||||
case courierDrop = 1401
|
||||
}
|
||||
|
||||
/// Bound work before Base64-decoding either encrypted layer of an inbound
|
||||
/// private envelope, and before parsing each decrypted nested JSON layer.
|
||||
/// Real envelopes are normally a few KiB; 64 KiB leaves ample headroom
|
||||
/// without letting an addressed relay event drive unbounded allocation.
|
||||
/// Prefix for BitChat private-envelope ciphertext. The suffix is
|
||||
/// base64url(nonce24 || ciphertext || poly1305Tag).
|
||||
static let privateEnvelopeContentPrefix = "bitchat-pm-v1:"
|
||||
|
||||
/// Bound work before Base64 decoding either encrypted layer. Current
|
||||
/// private messages are normally only a few KiB; 64 KiB leaves ample
|
||||
/// migration headroom without allowing an addressed relay event to drive
|
||||
/// unbounded allocation.
|
||||
static let maximumPrivateEnvelopeCiphertextBytes = 64 * 1024
|
||||
|
||||
/// Create a BitChat private envelope for relay transport (outer kind 1059).
|
||||
static func createPrivateMessage(
|
||||
/// Bound the inner authenticated message JSON before allocation/parsing.
|
||||
/// This is intentionally an envelope limit, not the generic composer
|
||||
/// limit. Raising it alone would not make larger private-message packets
|
||||
/// compatible with released readers; callers must surface a rejected
|
||||
/// packet or envelope as a failed send.
|
||||
static let maximumPrivateEnvelopePlaintextBytes = 32 * 1024
|
||||
|
||||
/// The outer authenticated seal JSON contains a Base64-encoded encrypted
|
||||
/// copy of the inner JSON, so it needs expansion headroom of its own. Keep
|
||||
/// the layer-specific cap below the public ciphertext ceiling.
|
||||
private static let maximumPrivateEnvelopeSealPlaintextBytes = 48 * 1024
|
||||
|
||||
/// New clients subscribe to the provisional BitChat-specific kind and the
|
||||
/// compatibility legacy kind so both sides of a rolling rollout can
|
||||
/// recover stored messages. Do not remove kind 1059 here until all
|
||||
/// supported iOS and Android releases have migrated.
|
||||
static let acceptedPrivateEnvelopeKinds = [
|
||||
EventKind.privateEnvelope.rawValue,
|
||||
EventKind.legacyNIP59GiftWrap.rawValue
|
||||
]
|
||||
|
||||
private enum PrivateEnvelopeWireFormat {
|
||||
case bitchatV1
|
||||
case legacyMislabelledV2
|
||||
|
||||
init?(outerKind: Int) {
|
||||
switch outerKind {
|
||||
case EventKind.privateEnvelope.rawValue:
|
||||
self = .bitchatV1
|
||||
case EventKind.legacyNIP59GiftWrap.rawValue:
|
||||
self = .legacyMislabelledV2
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
var messageKind: EventKind {
|
||||
switch self {
|
||||
case .bitchatV1: .privateMessage
|
||||
case .legacyMislabelledV2: .legacyNIP17DirectMessage
|
||||
}
|
||||
}
|
||||
|
||||
var sealKind: EventKind {
|
||||
switch self {
|
||||
case .bitchatV1: .privateSeal
|
||||
case .legacyMislabelledV2: .legacyNIP59Seal
|
||||
}
|
||||
}
|
||||
|
||||
var envelopeKind: EventKind {
|
||||
switch self {
|
||||
case .bitchatV1: .privateEnvelope
|
||||
case .legacyMislabelledV2: .legacyNIP59GiftWrap
|
||||
}
|
||||
}
|
||||
|
||||
var contentPrefix: String {
|
||||
switch self {
|
||||
case .bitchatV1: NostrProtocol.privateEnvelopeContentPrefix
|
||||
case .legacyMislabelledV2: "v2:"
|
||||
}
|
||||
}
|
||||
|
||||
var hkdfSalt: Data {
|
||||
switch self {
|
||||
case .bitchatV1: Data("bitchat-private-envelope-v1".utf8)
|
||||
case .legacyMislabelledV2: Data()
|
||||
}
|
||||
}
|
||||
|
||||
var hkdfInfo: Data {
|
||||
switch self {
|
||||
case .bitchatV1: Data()
|
||||
case .legacyMislabelledV2: Data("nip44-v2".utf8)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a BitChat private envelope for relay transport.
|
||||
static func createPrivateEnvelope(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity
|
||||
) throws -> NostrEvent {
|
||||
try createPrivateMessage(
|
||||
try createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderIdentity: senderIdentity,
|
||||
messageTags: []
|
||||
format: .bitchatV1
|
||||
)
|
||||
}
|
||||
|
||||
private static func createPrivateMessage(
|
||||
/// Events to publish for one logical private payload. The primary
|
||||
/// BitChat-specific format is always first and a legacy copy follows for
|
||||
/// clients that still subscribe only to kind 1059. There is deliberately
|
||||
/// no date-based cutoff: removal requires a coordinated iOS/Android
|
||||
/// release after supported old clients have migrated. Both encrypt the
|
||||
/// exact same embedded BitChat payload, so receive-side logical-payload
|
||||
/// dedup collapses the pair.
|
||||
static func createPrivateEnvelopePublicationBatch(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity
|
||||
) throws -> [NostrEvent] {
|
||||
let primary = try createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderIdentity: senderIdentity
|
||||
)
|
||||
let compatibilityCopy = try createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderIdentity: senderIdentity,
|
||||
format: .legacyMislabelledV2
|
||||
)
|
||||
return [primary, compatibilityCopy]
|
||||
}
|
||||
|
||||
private static func createPrivateEnvelope(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity,
|
||||
messageTags: [[String]]
|
||||
format: PrivateEnvelopeWireFormat,
|
||||
messageTags: [[String]] = []
|
||||
) throws -> NostrEvent {
|
||||
// 1. Create the rumor (unsigned inner event)
|
||||
let rumor = NostrEvent(
|
||||
// 1. Create the unsigned inner BitChat message.
|
||||
let message = NostrEvent(
|
||||
pubkey: senderIdentity.publicKeyHex,
|
||||
createdAt: Date(),
|
||||
kind: .dm,
|
||||
kind: format.messageKind,
|
||||
tags: messageTags,
|
||||
content: content
|
||||
)
|
||||
|
||||
// 2. Seal the rumor (encrypt to recipient) and sign it with the SENDER'S
|
||||
// real identity key so the recipient can authenticate who sent the
|
||||
// message; signing with a throwaway key leaves DMs
|
||||
// forgeable/impersonatable.
|
||||
// 2. Encrypt the message to the recipient and sign the private seal
|
||||
// with the sender's stable Nostr identity for sender authentication.
|
||||
let senderKey = try senderIdentity.schnorrSigningKey()
|
||||
let sealedEvent = try createSeal(
|
||||
rumor: rumor,
|
||||
let sealedEvent = try createPrivateSeal(
|
||||
message: message,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderKey: senderKey
|
||||
senderKey: senderKey,
|
||||
format: format
|
||||
)
|
||||
|
||||
// 3. Wrap the sealed event with a throwaway ephemeral key (the wrap
|
||||
// layer hides the sender's identity from relays; createGiftWrap mints
|
||||
// its own ephemeral key internally).
|
||||
let giftWrap = try createGiftWrap(
|
||||
// 3. Encrypt the seal under a one-time key so the public envelope does
|
||||
// not reveal the stable sender identity.
|
||||
return try createPrivateEnvelopeEvent(
|
||||
seal: sealedEvent,
|
||||
recipientPubkey: recipientPubkey
|
||||
recipientPubkey: recipientPubkey,
|
||||
format: format
|
||||
)
|
||||
|
||||
return giftWrap
|
||||
}
|
||||
|
||||
/// Decrypt a received BitChat private envelope.
|
||||
/// Returns the content, sender pubkey, and the actual message timestamp (not the randomized outer timestamp)
|
||||
static func decryptPrivateMessage(
|
||||
giftWrap: NostrEvent,
|
||||
/// Decrypt a BitChat private envelope. Legacy proprietary envelopes that
|
||||
/// older BitChat releases placed under kinds 1059/13/14 are accepted only
|
||||
/// through the format-isolated receive path.
|
||||
static func decryptPrivateEnvelope(
|
||||
envelope: NostrEvent,
|
||||
recipientIdentity: NostrIdentity
|
||||
) throws -> (content: String, senderPubkey: String, timestamp: Int) {
|
||||
|
||||
// 0. Validate the untrusted outer envelope before any decryption work.
|
||||
// Every BitChat client (released iOS and current Android) publishes
|
||||
// exactly one outer recipient `p` tag on a validly signed kind-1059
|
||||
// wrap; anything else is malformed or misbound.
|
||||
guard giftWrap.content.utf8.count <= maximumPrivateEnvelopeCiphertextBytes else {
|
||||
SecureLogger.error("❌ Rejecting DM: oversized outer envelope ciphertext", category: .session)
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
guard giftWrap.kind == EventKind.giftWrap.rawValue,
|
||||
giftWrap.tags == [["p", recipientIdentity.publicKeyHex]],
|
||||
giftWrap.isValidSignature() else {
|
||||
SecureLogger.error("❌ Rejecting DM: malformed or misbound outer envelope", category: .session)
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
// 1. Unwrap the gift wrap
|
||||
let seal: NostrEvent
|
||||
do {
|
||||
seal = try unwrapGiftWrap(
|
||||
giftWrap: giftWrap,
|
||||
recipientKey: recipientIdentity.schnorrSigningKey()
|
||||
let layers = try decodePrivateEnvelopeLayers(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipientIdentity
|
||||
)
|
||||
// Successfully unwrapped gift wrap
|
||||
} catch {
|
||||
SecureLogger.error("❌ Failed to unwrap gift wrap: \(error)", category: .session)
|
||||
throw error
|
||||
}
|
||||
|
||||
// 2. Authenticate the seal. The seal MUST be signed by the sender's real
|
||||
// identity key; without this check a DM is forgeable by anyone who
|
||||
// knows the recipient's npub. Every BitChat sender emits a tagless
|
||||
// kind-13 seal, so bind the decrypted layer to that exact shape.
|
||||
guard seal.kind == EventKind.seal.rawValue,
|
||||
seal.tags.isEmpty,
|
||||
seal.isValidSignature() else {
|
||||
SecureLogger.error("❌ Rejecting DM: seal is malformed or its signature is missing/invalid", category: .session)
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
// 3. Open the seal
|
||||
let rumor: NostrEvent
|
||||
do {
|
||||
rumor = try openSeal(
|
||||
seal: seal,
|
||||
recipientKey: recipientIdentity.schnorrSigningKey()
|
||||
return (
|
||||
content: layers.message.content,
|
||||
senderPubkey: layers.seal.pubkey,
|
||||
timestamp: layers.message.created_at
|
||||
)
|
||||
// Successfully opened seal
|
||||
} catch {
|
||||
SecureLogger.error("❌ Failed to open seal: \(error)", category: .session)
|
||||
throw error
|
||||
}
|
||||
|
||||
// 4. The rumor is intentionally unsigned; sender authentication comes
|
||||
// from the seal. The sender claimed inside the rumor must match the
|
||||
// key that actually signed the seal, otherwise the sender field is
|
||||
// unauthenticated and spoofable. Also bind the inner kind and tag
|
||||
// shape to what BitChat clients actually emit.
|
||||
guard rumor.kind == EventKind.dm.rawValue,
|
||||
validInnerMessageTags(rumor.tags, recipientPubkey: recipientIdentity.publicKeyHex),
|
||||
rumor.sig == nil,
|
||||
seal.pubkey == rumor.pubkey else {
|
||||
SecureLogger.error("❌ Rejecting DM: rumor is malformed or does not match seal signer", category: .session)
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
// Return the seal signer's pubkey as the authenticated sender.
|
||||
return (content: rumor.content, senderPubkey: seal.pubkey, timestamp: rumor.created_at)
|
||||
}
|
||||
|
||||
/// Released iOS envelopes use no inner tags, while current Android
|
||||
/// envelopes place exactly the authenticated recipient's `p` tag on the
|
||||
/// unsigned inner event. Accept only those two historical shapes;
|
||||
/// alternate recipients, duplicate tags, and extra tags are rejected.
|
||||
private static func validInnerMessageTags(
|
||||
_ tags: [[String]],
|
||||
recipientPubkey: String
|
||||
) -> Bool {
|
||||
tags.isEmpty || tags == [["p", recipientPubkey]]
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
static func createPrivateMessageWithInvalidSealSignatureForTesting(
|
||||
static func createPrivateEnvelopeWithInvalidSealSignatureForTesting(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity
|
||||
) throws -> NostrEvent {
|
||||
let rumor = NostrEvent(
|
||||
let format = PrivateEnvelopeWireFormat.bitchatV1
|
||||
let message = NostrEvent(
|
||||
pubkey: senderIdentity.publicKeyHex,
|
||||
createdAt: Date(),
|
||||
kind: .dm,
|
||||
kind: format.messageKind,
|
||||
tags: [],
|
||||
content: content
|
||||
)
|
||||
var seal = try createSeal(
|
||||
rumor: rumor,
|
||||
var seal = try createPrivateSeal(
|
||||
message: message,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderKey: senderIdentity.schnorrSigningKey()
|
||||
senderKey: senderIdentity.schnorrSigningKey(),
|
||||
format: format
|
||||
)
|
||||
seal.sig = String(repeating: "0", count: 128)
|
||||
return try createGiftWrap(seal: seal, recipientPubkey: recipientPubkey)
|
||||
return try createPrivateEnvelopeEvent(
|
||||
seal: seal,
|
||||
recipientPubkey: recipientPubkey,
|
||||
format: format
|
||||
)
|
||||
}
|
||||
|
||||
static func createPrivateMessageWithMismatchedSealRumorPubkeyForTesting(
|
||||
static func createPrivateEnvelopeWithMismatchedSealMessagePubkeyForTesting(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
rumorIdentity: NostrIdentity,
|
||||
messageIdentity: NostrIdentity,
|
||||
sealSignerIdentity: NostrIdentity
|
||||
) throws -> NostrEvent {
|
||||
let rumor = NostrEvent(
|
||||
pubkey: rumorIdentity.publicKeyHex,
|
||||
let format = PrivateEnvelopeWireFormat.bitchatV1
|
||||
let message = NostrEvent(
|
||||
pubkey: messageIdentity.publicKeyHex,
|
||||
createdAt: Date(),
|
||||
kind: .dm,
|
||||
kind: format.messageKind,
|
||||
tags: [],
|
||||
content: content
|
||||
)
|
||||
let seal = try createSeal(
|
||||
rumor: rumor,
|
||||
let seal = try createPrivateSeal(
|
||||
message: message,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderKey: sealSignerIdentity.schnorrSigningKey()
|
||||
senderKey: sealSignerIdentity.schnorrSigningKey(),
|
||||
format: format
|
||||
)
|
||||
return try createPrivateEnvelopeEvent(
|
||||
seal: seal,
|
||||
recipientPubkey: recipientPubkey,
|
||||
format: format
|
||||
)
|
||||
return try createGiftWrap(seal: seal, recipientPubkey: recipientPubkey)
|
||||
}
|
||||
|
||||
/// Reproduces historical wire shapes (current Android places exactly one
|
||||
/// recipient `p` tag on the unsigned inner event) without making the
|
||||
/// production encoder depend on that quirk.
|
||||
static func createPrivateMessageWithInnerTagsForTesting(
|
||||
static func createPrivateEnvelopeWithInnerTagsForTesting(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity,
|
||||
innerMessageTags: [[String]]
|
||||
) throws -> NostrEvent {
|
||||
try createPrivateMessage(
|
||||
try createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderIdentity: senderIdentity,
|
||||
format: .bitchatV1,
|
||||
messageTags: innerMessageTags
|
||||
)
|
||||
}
|
||||
|
||||
static func createLegacyPrivateEnvelopeForTesting(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity,
|
||||
innerMessageTags: [[String]] = []
|
||||
) throws -> NostrEvent {
|
||||
// Current Android legacy envelopes use exactly one recipient `p` tag
|
||||
// on the unsigned inner kind-14 event; released iOS envelopes use no
|
||||
// inner tags. Tests pass the Android shape explicitly so this helper
|
||||
// cannot silently make the production encoder depend on that quirk.
|
||||
try createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderIdentity: senderIdentity,
|
||||
format: .legacyMislabelledV2,
|
||||
messageTags: innerMessageTags
|
||||
)
|
||||
}
|
||||
|
||||
static func decodePrivateEnvelopeLayersForTesting(
|
||||
envelope: NostrEvent,
|
||||
recipientIdentity: NostrIdentity
|
||||
) throws -> (seal: NostrEvent, message: NostrEvent) {
|
||||
try decodePrivateEnvelopeLayers(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipientIdentity
|
||||
)
|
||||
}
|
||||
|
||||
static func decodePrivateEnvelopeEventJSONForTesting(_ json: String) throws -> NostrEvent {
|
||||
try decodePrivateEnvelopeEventJSON(json)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Create a geohash-scoped ephemeral public message (kind 20000)
|
||||
@@ -474,170 +560,211 @@ struct NostrProtocol {
|
||||
|
||||
// MARK: - Private Methods
|
||||
|
||||
private static func createSeal(
|
||||
rumor: NostrEvent,
|
||||
private static func createPrivateSeal(
|
||||
message: NostrEvent,
|
||||
recipientPubkey: String,
|
||||
senderKey: P256K.Schnorr.PrivateKey
|
||||
senderKey: P256K.Schnorr.PrivateKey,
|
||||
format: PrivateEnvelopeWireFormat
|
||||
) throws -> NostrEvent {
|
||||
|
||||
let rumorJSON = try rumor.jsonString()
|
||||
let encrypted = try encrypt(
|
||||
plaintext: rumorJSON,
|
||||
plaintext: message.jsonString(),
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderKey: senderKey
|
||||
senderKey: senderKey,
|
||||
format: format,
|
||||
maximumPlaintextBytes: maximumPrivateEnvelopePlaintextBytes
|
||||
)
|
||||
|
||||
let seal = NostrEvent(
|
||||
pubkey: Data(senderKey.xonly.bytes).hexEncodedString(),
|
||||
createdAt: randomizedTimestamp(),
|
||||
kind: .seal,
|
||||
createdAt: randomizedPastTimestamp(),
|
||||
kind: format.sealKind,
|
||||
tags: [],
|
||||
content: encrypted
|
||||
)
|
||||
|
||||
// Sign the seal with the sender's Schnorr private key
|
||||
return try seal.sign(with: senderKey)
|
||||
}
|
||||
|
||||
private static func createGiftWrap(
|
||||
private static func createPrivateEnvelopeEvent(
|
||||
seal: NostrEvent,
|
||||
recipientPubkey: String
|
||||
recipientPubkey: String,
|
||||
format: PrivateEnvelopeWireFormat
|
||||
) throws -> NostrEvent {
|
||||
|
||||
let sealJSON = try seal.jsonString()
|
||||
|
||||
// Create new ephemeral key for gift wrap
|
||||
let wrapKey = try P256K.Schnorr.PrivateKey()
|
||||
// Creating gift wrap with ephemeral key
|
||||
|
||||
// Encrypt the seal with the new ephemeral key (not the seal's key)
|
||||
// A fresh signing/encryption key for every public envelope keeps the
|
||||
// stable sender identity inside ciphertext.
|
||||
let envelopeKey = try P256K.Schnorr.PrivateKey()
|
||||
let encrypted = try encrypt(
|
||||
plaintext: sealJSON,
|
||||
plaintext: seal.jsonString(),
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderKey: wrapKey // Use the gift wrap ephemeral key
|
||||
senderKey: envelopeKey,
|
||||
format: format,
|
||||
maximumPlaintextBytes: maximumPrivateEnvelopeSealPlaintextBytes
|
||||
)
|
||||
|
||||
let giftWrap = NostrEvent(
|
||||
pubkey: Data(wrapKey.xonly.bytes).hexEncodedString(),
|
||||
createdAt: randomizedTimestamp(),
|
||||
kind: .giftWrap,
|
||||
tags: [["p", recipientPubkey]], // Tag recipient
|
||||
let envelope = NostrEvent(
|
||||
pubkey: Data(envelopeKey.xonly.bytes).hexEncodedString(),
|
||||
createdAt: randomizedPastTimestamp(),
|
||||
kind: format.envelopeKind,
|
||||
tags: [["p", recipientPubkey]],
|
||||
content: encrypted
|
||||
)
|
||||
|
||||
// Sign the gift wrap with the wrap Schnorr private key
|
||||
return try giftWrap.sign(with: wrapKey)
|
||||
return try envelope.sign(with: envelopeKey)
|
||||
}
|
||||
|
||||
private static func unwrapGiftWrap(
|
||||
giftWrap: NostrEvent,
|
||||
recipientKey: P256K.Schnorr.PrivateKey
|
||||
) throws -> NostrEvent {
|
||||
|
||||
// Unwrapping gift wrap
|
||||
|
||||
let decrypted = try decrypt(
|
||||
ciphertext: giftWrap.content,
|
||||
senderPubkey: giftWrap.pubkey,
|
||||
recipientKey: recipientKey
|
||||
)
|
||||
|
||||
// Check UTF-8 size before allocating Data or invoking the general
|
||||
// JSON parser on attacker-influenced plaintext.
|
||||
guard decrypted.utf8.count <= maximumPrivateEnvelopeCiphertextBytes else {
|
||||
private static func decodePrivateEnvelopeLayers(
|
||||
envelope: NostrEvent,
|
||||
recipientIdentity: NostrIdentity
|
||||
) throws -> (seal: NostrEvent, message: NostrEvent) {
|
||||
guard envelope.content.utf8.count <= maximumPrivateEnvelopeCiphertextBytes else {
|
||||
SecureLogger.error("❌ Rejecting DM: oversized outer envelope ciphertext", category: .session)
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
guard let data = decrypted.data(using: .utf8),
|
||||
let sealDict = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
||||
guard let format = PrivateEnvelopeWireFormat(outerKind: envelope.kind),
|
||||
envelope.tags == [["p", recipientIdentity.publicKeyHex]],
|
||||
envelope.isValidSignature() else {
|
||||
SecureLogger.error("❌ Rejecting DM: malformed or misbound outer envelope", category: .session)
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
let seal = try NostrEvent(from: sealDict)
|
||||
// Unwrapped seal
|
||||
|
||||
return seal
|
||||
let recipientKey = try recipientIdentity.schnorrSigningKey()
|
||||
let sealJSON = try decrypt(
|
||||
ciphertext: envelope.content,
|
||||
senderPubkey: envelope.pubkey,
|
||||
recipientKey: recipientKey,
|
||||
format: format,
|
||||
maximumPlaintextBytes: maximumPrivateEnvelopeSealPlaintextBytes
|
||||
)
|
||||
let seal = try decodePrivateEnvelopeEventJSON(
|
||||
sealJSON,
|
||||
maximumBytes: maximumPrivateEnvelopeSealPlaintextBytes
|
||||
)
|
||||
guard seal.kind == format.sealKind.rawValue,
|
||||
seal.tags.isEmpty,
|
||||
seal.isValidSignature() else {
|
||||
SecureLogger.error("❌ Rejecting DM: seal is malformed or its signature is missing/invalid", category: .session)
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
private static func openSeal(
|
||||
seal: NostrEvent,
|
||||
recipientKey: P256K.Schnorr.PrivateKey
|
||||
) throws -> NostrEvent {
|
||||
|
||||
let decrypted = try decrypt(
|
||||
let messageJSON = try decrypt(
|
||||
ciphertext: seal.content,
|
||||
senderPubkey: seal.pubkey,
|
||||
recipientKey: recipientKey
|
||||
recipientKey: recipientKey,
|
||||
format: format,
|
||||
maximumPlaintextBytes: maximumPrivateEnvelopePlaintextBytes
|
||||
)
|
||||
let message = try decodePrivateEnvelopeEventJSON(
|
||||
messageJSON,
|
||||
maximumBytes: maximumPrivateEnvelopePlaintextBytes
|
||||
)
|
||||
|
||||
guard decrypted.utf8.count <= maximumPrivateEnvelopeCiphertextBytes else {
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
guard let data = decrypted.data(using: .utf8),
|
||||
let rumorDict = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
||||
// The inner message is intentionally unsigned; sender authentication
|
||||
// comes from the seal. Bind its claimed sender and custom kind to that
|
||||
// authenticated layer before exposing content.
|
||||
guard message.kind == format.messageKind.rawValue,
|
||||
validInnerMessageTags(
|
||||
message.tags,
|
||||
format: format,
|
||||
recipientPubkey: recipientIdentity.publicKeyHex
|
||||
),
|
||||
message.sig == nil,
|
||||
seal.pubkey == message.pubkey else {
|
||||
SecureLogger.error("❌ Rejecting DM: inner message is malformed or does not match seal signer", category: .session)
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
return try NostrEvent(from: rumorDict)
|
||||
return (seal, message)
|
||||
}
|
||||
|
||||
/// Released iOS legacy envelopes used no inner tags, while current
|
||||
/// Android legacy envelopes use exactly the authenticated recipient tag.
|
||||
/// Accept only those two historical shapes for kind 1059. The new kind
|
||||
/// 1402 format remains strict and rejects every inner tag.
|
||||
private static func validInnerMessageTags(
|
||||
_ tags: [[String]],
|
||||
format: PrivateEnvelopeWireFormat,
|
||||
recipientPubkey: String
|
||||
) -> Bool {
|
||||
switch format {
|
||||
case .bitchatV1:
|
||||
return tags.isEmpty
|
||||
case .legacyMislabelledV2:
|
||||
return tags.isEmpty || tags == [["p", recipientPubkey]]
|
||||
}
|
||||
}
|
||||
|
||||
private static func decodePrivateEnvelopeEventJSON(
|
||||
_ json: String,
|
||||
maximumBytes: Int = maximumPrivateEnvelopePlaintextBytes
|
||||
) throws -> NostrEvent {
|
||||
// Check UTF-8 size before allocating Data or invoking the general JSON
|
||||
// parser. `decrypt` enforces the same cap on authenticated bytes; this
|
||||
// local guard keeps the parser boundary explicit and independently
|
||||
// testable.
|
||||
guard json.utf8.count <= maximumBytes else {
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
guard let data = json.data(using: .utf8),
|
||||
let dictionary = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
return try NostrEvent(from: dictionary)
|
||||
}
|
||||
|
||||
// MARK: - BitChat private-envelope encryption
|
||||
//
|
||||
// Not NIP-44: the `v2:` prefix, base64url(nonce24 || ciphertext || tag)
|
||||
// layout, XChaCha20-Poly1305 cipher, and HKDF parameters are all
|
||||
// BitChat-specific.
|
||||
|
||||
private static func encrypt(
|
||||
plaintext: String,
|
||||
recipientPubkey: String,
|
||||
senderKey: P256K.Schnorr.PrivateKey
|
||||
senderKey: P256K.Schnorr.PrivateKey,
|
||||
format: PrivateEnvelopeWireFormat,
|
||||
maximumPlaintextBytes: Int
|
||||
) throws -> String {
|
||||
|
||||
guard let recipientPubkeyData = Data(hexString: recipientPubkey) else {
|
||||
throw NostrError.invalidPublicKey
|
||||
}
|
||||
|
||||
// Derive shared secret
|
||||
let sharedSecret = try deriveSharedSecret(
|
||||
privateKey: senderKey,
|
||||
publicKey: recipientPubkeyData
|
||||
)
|
||||
// Derive the BitChat private-envelope symmetric key (HKDF-SHA256)
|
||||
let key = try derivePrivateEnvelopeKey(from: sharedSecret)
|
||||
let key = derivePrivateEnvelopeKey(from: sharedSecret, format: format)
|
||||
|
||||
// 24-byte random nonce for XChaCha20-Poly1305
|
||||
var nonce24 = Data(count: 24)
|
||||
let randomStatus = nonce24.withUnsafeMutableBytes { ptr in
|
||||
SecRandomCopyBytes(kSecRandomDefault, 24, ptr.baseAddress!)
|
||||
}
|
||||
// Never encrypt with an unrandomized nonce: nonce reuse under the same
|
||||
// key breaks XChaCha20-Poly1305 confidentiality and authenticity.
|
||||
guard randomStatus == errSecSuccess else {
|
||||
throw NostrError.cryptographicFailure
|
||||
}
|
||||
|
||||
let pt = Data(plaintext.utf8)
|
||||
let sealed = try XChaCha20Poly1305Compat.seal(plaintext: pt, key: key, nonce24: nonce24)
|
||||
let plaintextData = Data(plaintext.utf8)
|
||||
guard plaintextData.count <= maximumPlaintextBytes else {
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
let sealed = try XChaCha20Poly1305Compat.seal(
|
||||
plaintext: plaintextData,
|
||||
key: key,
|
||||
nonce24: nonce24
|
||||
)
|
||||
|
||||
// v2: base64url(nonce24 || ciphertext || tag)
|
||||
var combined = Data()
|
||||
combined.append(nonce24)
|
||||
combined.append(sealed.ciphertext)
|
||||
combined.append(sealed.tag)
|
||||
return "v2:" + Base64URLCoding.encode(combined)
|
||||
return format.contentPrefix + Base64URLCoding.encode(combined)
|
||||
}
|
||||
|
||||
private static func decrypt(
|
||||
ciphertext: String,
|
||||
senderPubkey: String,
|
||||
recipientKey: P256K.Schnorr.PrivateKey
|
||||
recipientKey: P256K.Schnorr.PrivateKey,
|
||||
format: PrivateEnvelopeWireFormat,
|
||||
maximumPlaintextBytes: Int
|
||||
) throws -> String {
|
||||
// Expect BitChat's historical `v2:` private-envelope framing, and
|
||||
// bound work before Base64 decoding attacker-sized input.
|
||||
guard ciphertext.utf8.count <= maximumPrivateEnvelopeCiphertextBytes,
|
||||
ciphertext.hasPrefix("v2:") else {
|
||||
ciphertext.hasPrefix(format.contentPrefix) else {
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
let encoded = String(ciphertext.dropFirst(3))
|
||||
let encoded = String(ciphertext.dropFirst(format.contentPrefix.count))
|
||||
guard let data = Base64URLCoding.decode(encoded),
|
||||
data.count > (24 + 16),
|
||||
let senderPubkeyData = Data(hexString: senderPubkey) else {
|
||||
@@ -647,37 +774,37 @@ struct NostrProtocol {
|
||||
let nonce24 = data.prefix(24)
|
||||
let rest = data.dropFirst(24)
|
||||
let tag = rest.suffix(16)
|
||||
let ct = rest.dropLast(16)
|
||||
let ciphertextBytes = rest.dropLast(16)
|
||||
|
||||
// Try decryption with even-Y then odd-Y when sender pubkey is x-only
|
||||
func attemptDecrypt(using pubKeyData: Data) throws -> Data {
|
||||
let ss = try deriveSharedSecret(privateKey: recipientKey, publicKey: pubKeyData)
|
||||
let key = try derivePrivateEnvelopeKey(from: ss)
|
||||
func attemptDecrypt(using publicKeyData: Data) throws -> Data {
|
||||
let sharedSecret = try deriveSharedSecret(
|
||||
privateKey: recipientKey,
|
||||
publicKey: publicKeyData
|
||||
)
|
||||
let key = derivePrivateEnvelopeKey(from: sharedSecret, format: format)
|
||||
return try XChaCha20Poly1305Compat.open(
|
||||
ciphertext: Data(ct),
|
||||
ciphertext: Data(ciphertextBytes),
|
||||
tag: Data(tag),
|
||||
key: key,
|
||||
nonce24: Data(nonce24)
|
||||
)
|
||||
}
|
||||
|
||||
// If 32 bytes (x-only) try both parities, otherwise single try
|
||||
let plaintext: Data
|
||||
if senderPubkeyData.count == 32 {
|
||||
let even = Data([0x02]) + senderPubkeyData
|
||||
if let pt = try? attemptDecrypt(using: even) {
|
||||
plaintext = pt
|
||||
let evenKey = Data([0x02]) + senderPubkeyData
|
||||
if let opened = try? attemptDecrypt(using: evenKey) {
|
||||
plaintext = opened
|
||||
} else {
|
||||
let odd = Data([0x03]) + senderPubkeyData
|
||||
plaintext = try attemptDecrypt(using: odd)
|
||||
let oddKey = Data([0x03]) + senderPubkeyData
|
||||
plaintext = try attemptDecrypt(using: oddKey)
|
||||
}
|
||||
} else {
|
||||
plaintext = try attemptDecrypt(using: senderPubkeyData)
|
||||
}
|
||||
|
||||
// Authenticated plaintext that is not valid UTF-8 is a malformed
|
||||
// envelope, not an empty message.
|
||||
guard let decoded = String(data: plaintext, encoding: .utf8) else {
|
||||
guard plaintext.count <= maximumPlaintextBytes,
|
||||
let decoded = String(data: plaintext, encoding: .utf8) else {
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
return decoded
|
||||
@@ -740,30 +867,17 @@ struct NostrProtocol {
|
||||
let sharedSecretData = sharedSecret.withUnsafeBytes { Data($0) }
|
||||
// ECDH shared secret derived
|
||||
|
||||
// Return raw ECDH shared secret; HKDF is applied by
|
||||
// derivePrivateEnvelopeKey
|
||||
// Return raw ECDH shared secret; the wire-format-specific HKDF is
|
||||
// applied by derivePrivateEnvelopeKey.
|
||||
return sharedSecretData
|
||||
}
|
||||
|
||||
private static func randomizedTimestamp() -> Date {
|
||||
// Add random offset to current time for privacy
|
||||
// This prevents timing correlation attacks while the actual message timestamp
|
||||
// is preserved in the encrypted rumor
|
||||
let offset = TimeInterval.random(in: -900...900) // +/- 15 minutes
|
||||
let now = Date()
|
||||
let randomized = now.addingTimeInterval(offset)
|
||||
|
||||
// Log with explicit UTC and local time for debugging
|
||||
let formatter = DateFormatter()
|
||||
//
|
||||
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
|
||||
formatter.timeZone = TimeZone(abbreviation: "UTC")
|
||||
|
||||
formatter.timeZone = TimeZone.current
|
||||
|
||||
// Timestamp randomized for privacy
|
||||
|
||||
return randomized
|
||||
private static func randomizedPastTimestamp() -> Date {
|
||||
// Keep public timestamps in the past: future-dated events are rejected
|
||||
// by some relays. The actual message timestamp remains encrypted.
|
||||
Date().addingTimeInterval(
|
||||
-TimeInterval.random(in: 0...TransportConfig.nostrPrivateEnvelopeTimestampFuzzSeconds)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -901,15 +1015,14 @@ enum NostrError: Error {
|
||||
// MARK: - BitChat private-envelope key derivation
|
||||
|
||||
private extension NostrProtocol {
|
||||
/// The HKDF info string retains the historical "nip44-v2" label for wire
|
||||
/// compatibility with deployed clients, but this is not the NIP-44 key
|
||||
/// schedule: NIP-44 derives a conversation key via HKDF-extract with that
|
||||
/// label as the *salt* and uses ChaCha20 with per-message expanded keys.
|
||||
static func derivePrivateEnvelopeKey(from sharedSecretData: Data) throws -> Data {
|
||||
private static func derivePrivateEnvelopeKey(
|
||||
from sharedSecretData: Data,
|
||||
format: PrivateEnvelopeWireFormat
|
||||
) -> Data {
|
||||
let derivedKey = HKDF<CryptoKit.SHA256>.deriveKey(
|
||||
inputKeyMaterial: SymmetricKey(data: sharedSecretData),
|
||||
salt: Data(),
|
||||
info: Data("nip44-v2".utf8),
|
||||
salt: format.hkdfSalt,
|
||||
info: format.hkdfInfo,
|
||||
outputByteCount: 32
|
||||
)
|
||||
return derivedKey.withUnsafeBytes { Data($0) }
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -158,6 +158,16 @@ final class MessageRouter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Wire one typed event sink to every route, including the queue-backed
|
||||
/// Nostr transport. Keeping this at the router boundary prevents a relay
|
||||
/// admission failure from disappearing merely because only the primary
|
||||
/// mesh transport was assigned a UI delegate.
|
||||
func setEventDelegate(_ delegate: TransportEventDelegate?) {
|
||||
for transport in transports {
|
||||
transport.eventDelegate = delegate
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Transport Selection
|
||||
|
||||
private func reachableTransport(for peerID: PeerID) -> Transport? {
|
||||
|
||||
@@ -11,8 +11,12 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
let favoriteStatusForNoiseKey: @MainActor (Data) -> FavoritesPersistenceService.FavoriteRelationship?
|
||||
let favoriteStatusForPeerID: @MainActor (PeerID) -> FavoritesPersistenceService.FavoriteRelationship?
|
||||
let currentIdentity: @MainActor () throws -> NostrIdentity?
|
||||
let registerPendingGiftWrap: @MainActor (String) -> Void
|
||||
let sendEvent: @MainActor (NostrEvent) -> Void
|
||||
let registerPendingPrivateEnvelope: @MainActor (String) -> Void
|
||||
let sendPrivateEnvelopeBatch: @MainActor (
|
||||
[NostrEvent],
|
||||
@escaping @MainActor () -> Void
|
||||
) -> Bool
|
||||
let envelopeRetryQueue: NostrPrivateEnvelopeRetryQueue
|
||||
/// Emits whether a relay that carries private messages is up
|
||||
/// (fail-closed behind Tor). A connected geohash/custom relay alone
|
||||
/// doesn't count: DM sends target the default relay set and would
|
||||
@@ -22,25 +26,35 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
/// serialize behind each other; `live` passes the process-wide one.
|
||||
let ackPacer: AckPacer
|
||||
|
||||
@MainActor
|
||||
init(
|
||||
notificationCenter: NotificationCenter,
|
||||
loadFavorites: @escaping @MainActor () -> [Data: FavoritesPersistenceService.FavoriteRelationship],
|
||||
favoriteStatusForNoiseKey: @escaping @MainActor (Data) -> FavoritesPersistenceService.FavoriteRelationship?,
|
||||
favoriteStatusForPeerID: @escaping @MainActor (PeerID) -> FavoritesPersistenceService.FavoriteRelationship?,
|
||||
currentIdentity: @escaping @MainActor () throws -> NostrIdentity?,
|
||||
registerPendingGiftWrap: @escaping @MainActor (String) -> Void,
|
||||
sendEvent: @escaping @MainActor (NostrEvent) -> Void,
|
||||
registerPendingPrivateEnvelope: @escaping @MainActor (String) -> Void,
|
||||
sendPrivateEnvelopeBatch: @escaping @MainActor (
|
||||
[NostrEvent],
|
||||
@escaping @MainActor () -> Void
|
||||
) -> Bool,
|
||||
scheduleAfter: @escaping @Sendable (TimeInterval, @escaping @Sendable () -> Void) -> Void,
|
||||
relayConnectivity: @escaping @MainActor () -> AnyPublisher<Bool, Never>,
|
||||
ackPacer: AckPacer? = nil
|
||||
ackPacer: AckPacer? = nil,
|
||||
envelopeRetryQueue: NostrPrivateEnvelopeRetryQueue? = nil
|
||||
) {
|
||||
self.notificationCenter = notificationCenter
|
||||
self.loadFavorites = loadFavorites
|
||||
self.favoriteStatusForNoiseKey = favoriteStatusForNoiseKey
|
||||
self.favoriteStatusForPeerID = favoriteStatusForPeerID
|
||||
self.currentIdentity = currentIdentity
|
||||
self.registerPendingGiftWrap = registerPendingGiftWrap
|
||||
self.sendEvent = sendEvent
|
||||
self.registerPendingPrivateEnvelope = registerPendingPrivateEnvelope
|
||||
self.sendPrivateEnvelopeBatch = sendPrivateEnvelopeBatch
|
||||
self.envelopeRetryQueue = envelopeRetryQueue ?? NostrPrivateEnvelopeRetryQueue(
|
||||
sendPrivateEnvelopeBatch: sendPrivateEnvelopeBatch,
|
||||
registerPendingPrivateEnvelope: registerPendingPrivateEnvelope,
|
||||
scheduleAfter: scheduleAfter
|
||||
)
|
||||
self.relayConnectivity = relayConnectivity
|
||||
// Default pacer drives its throttle through the same injected
|
||||
// scheduler, so tests that step scheduleAfter manually keep
|
||||
@@ -56,13 +70,19 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
favoriteStatusForNoiseKey: { FavoritesPersistenceService.shared.getFavoriteStatus(for: $0) },
|
||||
favoriteStatusForPeerID: { FavoritesPersistenceService.shared.getFavoriteStatus(forPeerID: $0) },
|
||||
currentIdentity: { try idBridge.getCurrentNostrIdentity() },
|
||||
registerPendingGiftWrap: { NostrRelayManager.registerPendingGiftWrap(id: $0) },
|
||||
sendEvent: { NostrRelayManager.shared.sendEvent($0) },
|
||||
registerPendingPrivateEnvelope: { NostrRelayManager.registerPendingPrivateEnvelope(id: $0) },
|
||||
sendPrivateEnvelopeBatch: { events, terminalFailure in
|
||||
NostrRelayManager.shared.sendPrivateEnvelopeBatch(
|
||||
events,
|
||||
terminalFailure: terminalFailure
|
||||
)
|
||||
},
|
||||
scheduleAfter: { delay, action in
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: action)
|
||||
},
|
||||
relayConnectivity: { NostrRelayManager.shared.$isDMRelayConnected.eraseToAnyPublisher() },
|
||||
ackPacer: NostrTransport.sharedAckPacer
|
||||
ackPacer: NostrTransport.sharedAckPacer,
|
||||
envelopeRetryQueue: NostrTransport.sharedEnvelopeRetryQueue
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -128,7 +148,37 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
}
|
||||
}
|
||||
static let sharedAckPacer = AckPacer()
|
||||
// Geohash acknowledgements use short-lived NostrTransport instances, so
|
||||
// the retry owner must be process-wide. A per-transport cap would still be
|
||||
// globally unbounded under outage as throwaway instances accumulated.
|
||||
@MainActor
|
||||
private static let sharedEnvelopeRetryQueue = NostrPrivateEnvelopeRetryQueue(
|
||||
sendPrivateEnvelopeBatch: { events, terminalFailure in
|
||||
NostrRelayManager.shared.sendPrivateEnvelopeBatch(
|
||||
events,
|
||||
terminalFailure: terminalFailure
|
||||
)
|
||||
},
|
||||
registerPendingPrivateEnvelope: {
|
||||
NostrRelayManager.registerPendingPrivateEnvelope(id: $0)
|
||||
},
|
||||
scheduleAfter: { delay, action in
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: action)
|
||||
}
|
||||
)
|
||||
|
||||
@MainActor
|
||||
static func resetControlRetriesForPanicWipe() {
|
||||
sharedEnvelopeRetryQueue.removeAll()
|
||||
}
|
||||
|
||||
private enum PrivateEnvelopeFailurePolicy {
|
||||
case userMessage(messageID: String)
|
||||
case retry(retryKey: String)
|
||||
}
|
||||
|
||||
private let dependencies: Dependencies
|
||||
private let envelopeRetryQueue: NostrPrivateEnvelopeRetryQueue
|
||||
private var favoriteStatusObserver: NSObjectProtocol?
|
||||
|
||||
// Reachability Cache (thread-safe)
|
||||
@@ -145,7 +195,9 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
idBridge: NostrIdentityBridge,
|
||||
dependencies: Dependencies? = nil
|
||||
) {
|
||||
self.dependencies = dependencies ?? .live(idBridge: idBridge)
|
||||
let resolvedDependencies = dependencies ?? .live(idBridge: idBridge)
|
||||
self.dependencies = resolvedDependencies
|
||||
self.envelopeRetryQueue = resolvedDependencies.envelopeRetryQueue
|
||||
|
||||
setupObservers()
|
||||
|
||||
@@ -172,6 +224,18 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
@MainActor
|
||||
func debugEnqueueControlRetry(key: String, events: [NostrEvent]) {
|
||||
envelopeRetryQueue.enqueue(key: key, events: events, registerPending: false)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
var debugControlRetryCount: Int {
|
||||
envelopeRetryQueue.debugPendingCount
|
||||
}
|
||||
#endif
|
||||
|
||||
private func setupObservers() {
|
||||
favoriteStatusObserver = dependencies.notificationCenter.addObserver(
|
||||
forName: .favoriteStatusChanged,
|
||||
@@ -253,15 +317,49 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
|
||||
func sendPrivateMessage(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String) {
|
||||
Task { @MainActor in
|
||||
guard let recipientNpub = resolveRecipientNpub(for: peerID),
|
||||
let recipientHex = npubToHex(recipientNpub),
|
||||
let senderIdentity = try? dependencies.currentIdentity() else { return }
|
||||
let failurePolicy = PrivateEnvelopeFailurePolicy.userMessage(
|
||||
messageID: messageID
|
||||
)
|
||||
guard let recipientNpub = resolveRecipientNpub(for: peerID) else {
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: [],
|
||||
registerPending: false,
|
||||
policy: failurePolicy
|
||||
)
|
||||
return
|
||||
}
|
||||
guard let recipientHex = npubToHex(recipientNpub) else {
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: [],
|
||||
registerPending: false,
|
||||
policy: failurePolicy
|
||||
)
|
||||
return
|
||||
}
|
||||
guard let senderIdentity = try? dependencies.currentIdentity() else {
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: [],
|
||||
registerPending: false,
|
||||
policy: failurePolicy
|
||||
)
|
||||
return
|
||||
}
|
||||
SecureLogger.debug("NostrTransport: preparing PM to \(recipientNpub.prefix(16))… id=\(messageID.prefix(8))…", category: .session)
|
||||
guard let embedded = NostrEmbeddedBitChat.encodePMForNostr(content: content, messageID: messageID, recipientPeerID: peerID, senderPeerID: senderPeerID) else {
|
||||
SecureLogger.error("NostrTransport: failed to embed PM packet", category: .session)
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: [],
|
||||
registerPending: false,
|
||||
policy: failurePolicy
|
||||
)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
sendPrivateEnvelope(
|
||||
content: embedded,
|
||||
recipientHex: recipientHex,
|
||||
senderIdentity: senderIdentity,
|
||||
failurePolicy: failurePolicy
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,7 +385,14 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
SecureLogger.error("NostrTransport: failed to embed favorite notification", category: .session)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
sendPrivateEnvelope(
|
||||
content: embedded,
|
||||
recipientHex: recipientHex,
|
||||
senderIdentity: senderIdentity,
|
||||
failurePolicy: .retry(
|
||||
retryKey: privateEnvelopeRetryKey(content: embedded, recipientHex: recipientHex)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -311,16 +416,48 @@ extension NostrTransport {
|
||||
}
|
||||
|
||||
// MARK: Geohash DMs (per-geohash identity)
|
||||
func sendPrivateMessageGeohash(content: String, toRecipientHex recipientHex: String, from identity: NostrIdentity, messageID: String) {
|
||||
Task { @MainActor in
|
||||
guard !recipientHex.isEmpty else { return }
|
||||
/// Returns true only when the complete migration pair entered the relay
|
||||
/// delivery queue. GeoDM callers use this synchronous admission result
|
||||
/// before showing "sent"; deterministic packet/envelope failures must not
|
||||
/// be hidden behind an unobserved MainActor task.
|
||||
@MainActor
|
||||
@discardableResult
|
||||
func sendPrivateMessageGeohash(
|
||||
content: String,
|
||||
toRecipientHex recipientHex: String,
|
||||
from identity: NostrIdentity,
|
||||
messageID: String
|
||||
) -> Bool {
|
||||
let failurePolicy = PrivateEnvelopeFailurePolicy.userMessage(messageID: messageID)
|
||||
guard !recipientHex.isEmpty else {
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: [],
|
||||
registerPending: false,
|
||||
policy: failurePolicy
|
||||
)
|
||||
return false
|
||||
}
|
||||
SecureLogger.debug("GeoDM: send PM mid=\(messageID.prefix(8))…", category: .session)
|
||||
guard let embedded = NostrEmbeddedBitChat.encodePMForNostrNoRecipient(content: content, messageID: messageID, senderPeerID: senderPeerID) else {
|
||||
guard let embedded = NostrEmbeddedBitChat.encodePMForNostrNoRecipient(
|
||||
content: content,
|
||||
messageID: messageID,
|
||||
senderPeerID: senderPeerID
|
||||
) else {
|
||||
SecureLogger.error("NostrTransport: failed to embed geohash PM packet", category: .session)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: [],
|
||||
registerPending: false,
|
||||
policy: failurePolicy
|
||||
)
|
||||
return false
|
||||
}
|
||||
return sendPrivateEnvelope(
|
||||
content: embedded,
|
||||
recipientHex: recipientHex,
|
||||
senderIdentity: identity,
|
||||
registerPending: true,
|
||||
failurePolicy: failurePolicy
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,17 +477,112 @@ extension NostrTransport {
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates and sends a gift-wrapped private message event
|
||||
/// Creates and sends a BitChat private-envelope event over Nostr.
|
||||
@MainActor
|
||||
private func sendWrappedMessage(content: String, recipientHex: String, senderIdentity: NostrIdentity, registerPending: Bool = false) {
|
||||
guard let event = try? NostrProtocol.createPrivateMessage(content: content, recipientPubkey: recipientHex, senderIdentity: senderIdentity) else {
|
||||
SecureLogger.error("NostrTransport: failed to build Nostr event", category: .session)
|
||||
return
|
||||
@discardableResult
|
||||
private func sendPrivateEnvelope(
|
||||
content: String,
|
||||
recipientHex: String,
|
||||
senderIdentity: NostrIdentity,
|
||||
registerPending: Bool = false,
|
||||
failurePolicy: PrivateEnvelopeFailurePolicy
|
||||
) -> Bool {
|
||||
let events: [NostrEvent]
|
||||
do {
|
||||
events = try NostrProtocol.createPrivateEnvelopePublicationBatch(
|
||||
content: content,
|
||||
recipientPubkey: recipientHex,
|
||||
senderIdentity: senderIdentity
|
||||
)
|
||||
} catch {
|
||||
SecureLogger.error(
|
||||
"NostrTransport: failed to build Nostr private-envelope batch: \(error)",
|
||||
category: .session
|
||||
)
|
||||
// Construction failures are deterministic. User-authored messages
|
||||
// must become visibly failed; control payloads have no valid event
|
||||
// pair to retain and retry.
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: [],
|
||||
registerPending: false,
|
||||
policy: failurePolicy
|
||||
)
|
||||
return false
|
||||
}
|
||||
if registerPending {
|
||||
dependencies.registerPendingGiftWrap(event.id)
|
||||
let accepted = dependencies.sendPrivateEnvelopeBatch(events) { [self] in
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: events,
|
||||
registerPending: registerPending,
|
||||
policy: failurePolicy
|
||||
)
|
||||
}
|
||||
guard accepted else {
|
||||
SecureLogger.error(
|
||||
"NostrTransport: private-envelope migration pair was not accepted for relay delivery",
|
||||
category: .session
|
||||
)
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: events,
|
||||
registerPending: registerPending,
|
||||
policy: failurePolicy
|
||||
)
|
||||
return false
|
||||
}
|
||||
registerPendingPrivateEnvelopesIfNeeded(events, registerPending: registerPending)
|
||||
return true
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func handlePrivateEnvelopeFailure(
|
||||
events: [NostrEvent],
|
||||
registerPending: Bool,
|
||||
policy: PrivateEnvelopeFailurePolicy
|
||||
) {
|
||||
switch policy {
|
||||
case .userMessage(let messageID):
|
||||
deliverTransportEvent(.messageDeliveryStatusUpdated(
|
||||
messageID: messageID,
|
||||
status: .failed(reason: String(
|
||||
localized: "content.delivery.reason.not_delivered",
|
||||
comment: "Failure reason shown when a private message could not enter the relay delivery queue"
|
||||
))
|
||||
))
|
||||
case .retry(let retryKey):
|
||||
// A deterministic packet/envelope construction failure has no
|
||||
// events to retry. Only relay admission/delivery failures reach
|
||||
// this branch with the complete atomic pair.
|
||||
guard !events.isEmpty else { return }
|
||||
envelopeRetryQueue.enqueue(
|
||||
key: retryKey,
|
||||
events: events,
|
||||
registerPending: registerPending
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func registerPendingPrivateEnvelopesIfNeeded(
|
||||
_ events: [NostrEvent],
|
||||
registerPending: Bool
|
||||
) {
|
||||
guard registerPending else { return }
|
||||
for event in events {
|
||||
dependencies.registerPendingPrivateEnvelope(event.id)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func privateEnvelopeRetryKey(content: String, recipientHex: String) -> String {
|
||||
"\(recipientHex.lowercased()):\(Data(content.utf8).sha256Fingerprint())"
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func deliverTransportEvent(_ event: TransportEvent) {
|
||||
if let eventDelegate {
|
||||
eventDelegate.didReceiveTransportEvent(event)
|
||||
} else {
|
||||
delegate?.receiveTransportEvent(event)
|
||||
}
|
||||
dependencies.sendEvent(event)
|
||||
}
|
||||
|
||||
|
||||
@@ -367,7 +599,14 @@ extension NostrTransport {
|
||||
SecureLogger.error("NostrTransport: failed to embed READ ack", category: .session)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: ack, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
sendPrivateEnvelope(
|
||||
content: ack,
|
||||
recipientHex: recipientHex,
|
||||
senderIdentity: senderIdentity,
|
||||
failurePolicy: .retry(
|
||||
retryKey: privateEnvelopeRetryKey(content: ack, recipientHex: recipientHex)
|
||||
)
|
||||
)
|
||||
|
||||
case .deliveredDirect(let messageID, let peerID):
|
||||
guard let recipientNpub = resolveRecipientNpub(for: peerID),
|
||||
@@ -378,17 +617,40 @@ extension NostrTransport {
|
||||
SecureLogger.error("NostrTransport: failed to embed DELIVERED ack", category: .session)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: ack, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
sendPrivateEnvelope(
|
||||
content: ack,
|
||||
recipientHex: recipientHex,
|
||||
senderIdentity: senderIdentity,
|
||||
failurePolicy: .retry(
|
||||
retryKey: privateEnvelopeRetryKey(content: ack, recipientHex: recipientHex)
|
||||
)
|
||||
)
|
||||
|
||||
case .deliveredGeohash(let messageID, let recipientHex, let identity):
|
||||
SecureLogger.debug("GeoDM: send DELIVERED mid=\(messageID.prefix(8))…", category: .session)
|
||||
guard let embedded = NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(type: .delivered, messageID: messageID, senderPeerID: senderPeerID) else { return }
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
|
||||
sendPrivateEnvelope(
|
||||
content: embedded,
|
||||
recipientHex: recipientHex,
|
||||
senderIdentity: identity,
|
||||
registerPending: true,
|
||||
failurePolicy: .retry(
|
||||
retryKey: privateEnvelopeRetryKey(content: embedded, recipientHex: recipientHex)
|
||||
)
|
||||
)
|
||||
|
||||
case .readGeohash(let messageID, let recipientHex, let identity):
|
||||
SecureLogger.debug("GeoDM: send READ mid=\(messageID.prefix(8))…", category: .session)
|
||||
guard let embedded = NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(type: .readReceipt, messageID: messageID, senderPeerID: senderPeerID) else { return }
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
|
||||
sendPrivateEnvelope(
|
||||
content: embedded,
|
||||
recipientHex: recipientHex,
|
||||
senderIdentity: identity,
|
||||
registerPending: true,
|
||||
failurePolicy: .retry(
|
||||
retryKey: privateEnvelopeRetryKey(content: embedded, recipientHex: recipientHex)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -408,3 +670,122 @@ extension NostrTransport {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Bounded retry owner for non-user private control payloads. It is separate
|
||||
/// from `NostrTransport` so a scheduled retry from a short-lived geohash
|
||||
/// transport remains valid after that transport deinitializes. Scheduler
|
||||
/// callbacks retain this queue, never the transport; an evicted key simply
|
||||
/// becomes a harmless no-op when its already-scheduled callback fires.
|
||||
@MainActor
|
||||
final class NostrPrivateEnvelopeRetryQueue {
|
||||
private struct PendingRetry {
|
||||
let events: [NostrEvent]
|
||||
let registerPending: Bool
|
||||
var attempt: Int
|
||||
var isScheduled: Bool
|
||||
}
|
||||
|
||||
private let sendPrivateEnvelopeBatch: @MainActor (
|
||||
[NostrEvent],
|
||||
@escaping @MainActor () -> Void
|
||||
) -> Bool
|
||||
private let registerPendingPrivateEnvelope: @MainActor (String) -> Void
|
||||
private let scheduleAfter: @Sendable (
|
||||
TimeInterval,
|
||||
@escaping @Sendable () -> Void
|
||||
) -> Void
|
||||
private var pending: [String: PendingRetry] = [:]
|
||||
private var insertionOrder: [String] = []
|
||||
|
||||
init(
|
||||
sendPrivateEnvelopeBatch: @escaping @MainActor (
|
||||
[NostrEvent],
|
||||
@escaping @MainActor () -> Void
|
||||
) -> Bool,
|
||||
registerPendingPrivateEnvelope: @escaping @MainActor (String) -> Void,
|
||||
scheduleAfter: @escaping @Sendable (
|
||||
TimeInterval,
|
||||
@escaping @Sendable () -> Void
|
||||
) -> Void
|
||||
) {
|
||||
self.sendPrivateEnvelopeBatch = sendPrivateEnvelopeBatch
|
||||
self.registerPendingPrivateEnvelope = registerPendingPrivateEnvelope
|
||||
self.scheduleAfter = scheduleAfter
|
||||
}
|
||||
|
||||
func enqueue(key: String, events: [NostrEvent], registerPending: Bool) {
|
||||
guard pending[key] == nil else { return }
|
||||
if pending.count >= TransportConfig.nostrPrivateEnvelopeRetryQueueCap,
|
||||
let evictedKey = insertionOrder.first {
|
||||
insertionOrder.removeFirst()
|
||||
pending.removeValue(forKey: evictedKey)
|
||||
// These are control payloads, never user-authored messages. Keep
|
||||
// the bounded-loss decision explicit rather than silently growing
|
||||
// memory during a prolonged outage.
|
||||
SecureLogger.warning(
|
||||
"📮 Private control retry queue full — evicted oldest whole migration pair",
|
||||
category: .session
|
||||
)
|
||||
}
|
||||
pending[key] = PendingRetry(
|
||||
events: events,
|
||||
registerPending: registerPending,
|
||||
attempt: 0,
|
||||
isScheduled: false
|
||||
)
|
||||
insertionOrder.append(key)
|
||||
schedule(key: key)
|
||||
}
|
||||
|
||||
private func schedule(key: String) {
|
||||
guard var item = pending[key], !item.isScheduled else { return }
|
||||
item.isScheduled = true
|
||||
pending[key] = item
|
||||
let exponent = min(item.attempt, 5)
|
||||
let delay = min(2.0 * pow(2.0, Double(exponent)), 60.0)
|
||||
scheduleAfter(delay) { [self] in
|
||||
Task { @MainActor [self] in
|
||||
self.retry(key: key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func retry(key: String) {
|
||||
guard var item = pending[key] else { return }
|
||||
item.isScheduled = false
|
||||
pending[key] = item
|
||||
|
||||
let accepted = sendPrivateEnvelopeBatch(item.events) { [self] in
|
||||
self.enqueue(
|
||||
key: key,
|
||||
events: item.events,
|
||||
registerPending: item.registerPending
|
||||
)
|
||||
}
|
||||
if accepted {
|
||||
remove(key: key)
|
||||
if item.registerPending {
|
||||
for event in item.events {
|
||||
registerPendingPrivateEnvelope(event.id)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
item.attempt += 1
|
||||
pending[key] = item
|
||||
schedule(key: key)
|
||||
}
|
||||
}
|
||||
|
||||
private func remove(key: String) {
|
||||
pending.removeValue(forKey: key)
|
||||
insertionOrder.removeAll { $0 == key }
|
||||
}
|
||||
|
||||
func removeAll() {
|
||||
pending.removeAll()
|
||||
insertionOrder.removeAll()
|
||||
}
|
||||
|
||||
var debugPendingCount: Int { pending.count }
|
||||
func debugContains(key: String) -> Bool { pending[key] != nil }
|
||||
}
|
||||
|
||||
@@ -215,7 +215,22 @@ enum TransportConfig {
|
||||
static let nostrGeoRelayCount: Int = 5
|
||||
static let nostrGeohashSampleLookbackSeconds: TimeInterval = 300
|
||||
static let nostrGeohashSampleLimit: Int = 100
|
||||
static let nostrDMSubscribeLookbackSeconds: TimeInterval = 86400
|
||||
/// New iOS public-envelope timestamps are deliberately shifted into the
|
||||
/// past for privacy and relay compatibility.
|
||||
static let nostrPrivateEnvelopeTimestampFuzzSeconds: TimeInterval = 15 * 60
|
||||
/// Deployed Android clients can shift legacy kind-1059 timestamps by the
|
||||
/// full preceding 48 hours.
|
||||
static let nostrLegacyAndroidTimestampFuzzSeconds: TimeInterval = 48 * 60 * 60
|
||||
/// Private mail remains eligible for delivery for the same 24-hour window
|
||||
/// as the persistent sender outbox. The relay query must add timestamp
|
||||
/// randomization to that window rather than replacing it: an Android event
|
||||
/// sent at t0 can legitimately be stamped t0-48h and fetched at t0+24h.
|
||||
static let nostrPrivateEnvelopeDeliveryWindowSeconds: TimeInterval = 24 * 60 * 60
|
||||
static let nostrDMSubscribeClockSkewSeconds: TimeInterval = 15 * 60
|
||||
static let nostrDMSubscribeLookbackSeconds: TimeInterval =
|
||||
nostrPrivateEnvelopeDeliveryWindowSeconds
|
||||
+ nostrLegacyAndroidTimestampFuzzSeconds
|
||||
+ nostrDMSubscribeClockSkewSeconds
|
||||
// A sampled chat message this recent means "a conversation is happening
|
||||
// there" for the empty-timeline nearby-activity hint.
|
||||
static let uiGeohashChatActivityWindowSeconds: TimeInterval = 900
|
||||
@@ -243,11 +258,20 @@ enum TransportConfig {
|
||||
// Reconnect delays get ±20% random jitter so relays that dropped together
|
||||
// (e.g. a network blip) don't thundering-herd the same reconnect instant.
|
||||
static let nostrRelayBackoffJitterRatio: Double = 0.2
|
||||
static let nostrRelayDefaultFetchLimit: Int = 100
|
||||
/// Migration recovery uses one independent relay filter per wire kind so
|
||||
/// primary traffic cannot consume the legacy result budget (or vice
|
||||
/// versa). Five hundred per kind bounds startup work while preserving a
|
||||
/// materially deeper offline mailbox than the generic feed default.
|
||||
static let nostrPrivateEnvelopeFetchLimitPerKind: Int = 500
|
||||
// How many consecutive Tor-readiness waits (each bounded by TorManager's
|
||||
// bootstrap deadline) to attempt before unblocking pending EOSE callers.
|
||||
static let nostrTorReadyMaxWaitAttempts: Int = 3
|
||||
static let nostrPendingSendQueueCap: Int = 200
|
||||
/// Control-payload pairs (delivery/read acknowledgements and favorite
|
||||
/// notifications) that could not enter the relay queue. User messages do
|
||||
/// not use this queue: they fail visibly, while direct messages also
|
||||
/// remain in the router outbox.
|
||||
static let nostrPrivateEnvelopeRetryQueueCap: Int = 256
|
||||
// Sample interval for the send-queue overflow warning (first + every Nth
|
||||
// dropped event). Drops are ephemeral presence/geo traffic — log-only.
|
||||
static let nostrPendingSendDropLogInterval: Int = 10
|
||||
|
||||
@@ -86,7 +86,13 @@ protocol ChatPrivateConversationContext: AnyObject {
|
||||
@discardableResult
|
||||
func routeReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) -> Bool
|
||||
func sendMeshReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID)
|
||||
func sendGeohashPrivateMessage(_ content: String, toRecipientHex recipientHex: String, from identity: NostrIdentity, messageID: String)
|
||||
@discardableResult
|
||||
func sendGeohashPrivateMessage(
|
||||
_ content: String,
|
||||
toRecipientHex recipientHex: String,
|
||||
from identity: NostrIdentity,
|
||||
messageID: String
|
||||
) -> Bool
|
||||
func sendGeohashDeliveryAck(for messageID: String, toRecipientHex recipientHex: String, from identity: NostrIdentity)
|
||||
func sendGeohashReadReceipt(_ messageID: String, toRecipientHex recipientHex: String, from identity: NostrIdentity)
|
||||
|
||||
@@ -174,7 +180,13 @@ extension ChatViewModel: ChatPrivateConversationContext {
|
||||
meshService.sendReadReceipt(receipt, to: peerID)
|
||||
}
|
||||
|
||||
func sendGeohashPrivateMessage(_ content: String, toRecipientHex recipientHex: String, from identity: NostrIdentity, messageID: String) {
|
||||
@discardableResult
|
||||
func sendGeohashPrivateMessage(
|
||||
_ content: String,
|
||||
toRecipientHex recipientHex: String,
|
||||
from identity: NostrIdentity,
|
||||
messageID: String
|
||||
) -> Bool {
|
||||
makeGeohashNostrTransport().sendPrivateMessageGeohash(
|
||||
content: content,
|
||||
toRecipientHex: recipientHex,
|
||||
@@ -216,9 +228,16 @@ extension ChatViewModel: ChatPrivateConversationContext {
|
||||
NotificationService.shared.sendPrivateMessageNotification(from: senderName, message: message, peerID: peerID)
|
||||
}
|
||||
|
||||
private func makeGeohashNostrTransport() -> NostrTransport {
|
||||
let transport = NostrTransport(keychain: keychain, idBridge: idBridge)
|
||||
func makeGeohashNostrTransport(
|
||||
dependencies: NostrTransport.Dependencies? = nil
|
||||
) -> NostrTransport {
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: dependencies
|
||||
)
|
||||
transport.senderPeerID = meshService.myPeerID
|
||||
transport.eventDelegate = self
|
||||
return transport
|
||||
}
|
||||
}
|
||||
@@ -227,7 +246,7 @@ extension ChatViewModel: ChatPrivateConversationContext {
|
||||
final class ChatPrivateConversationCoordinator {
|
||||
private unowned let context: any ChatPrivateConversationContext
|
||||
|
||||
// Outbox retries re-wrap the same message in fresh gift-wrap events, so
|
||||
// Outbox retries re-envelope the same message in fresh private events, so
|
||||
// relay-level event-ID dedup can't catch them; track inbound GeoDM
|
||||
// message IDs so each copy past the first costs one (already-deduped)
|
||||
// ack check and nothing else.
|
||||
@@ -399,13 +418,21 @@ final class ChatPrivateConversationCoordinator {
|
||||
"GeoDM: local send mid=\(messageID.prefix(8))… to=\(recipientHex.prefix(8))… conv=\(peerID)",
|
||||
category: .session
|
||||
)
|
||||
context.sendGeohashPrivateMessage(
|
||||
let accepted = context.sendGeohashPrivateMessage(
|
||||
content,
|
||||
toRecipientHex: recipientHex,
|
||||
from: identity,
|
||||
messageID: messageID
|
||||
)
|
||||
context.setPrivateDeliveryStatus(.sent, forMessageID: messageID, peerID: peerID)
|
||||
let status: DeliveryStatus = accepted
|
||||
? .sent
|
||||
: .failed(
|
||||
reason: String(
|
||||
localized: "content.delivery.reason.not_delivered",
|
||||
comment: "Failure reason shown when a private message could not enter the relay delivery queue"
|
||||
)
|
||||
)
|
||||
context.setPrivateDeliveryStatus(status, forMessageID: messageID, peerID: peerID)
|
||||
} catch {
|
||||
context.setPrivateDeliveryStatus(
|
||||
.failed(
|
||||
|
||||
@@ -1677,6 +1677,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
// Drop relay subscriptions, handlers, pending sends, and replay state.
|
||||
// Geohash DM handlers can capture pre-wipe Nostr identities, so a plain
|
||||
// disconnect is not enough here.
|
||||
NostrTransport.resetControlRetriesForPanicWipe()
|
||||
NostrRelayManager.shared.resetForPanicWipe()
|
||||
// Clearing relay handlers stops NEW events, but a detached gift-wrap
|
||||
// decrypt spawned just before the wipe still holds a pre-wipe key and
|
||||
|
||||
@@ -41,10 +41,11 @@ struct ChatViewModelServiceBundle {
|
||||
self.privateChatManager = privateChatManager
|
||||
self.unifiedPeerService = unifiedPeerService
|
||||
self.autocompleteService = AutocompleteService()
|
||||
// Persist processed gift-wrap event IDs: NIP-59 randomizes their
|
||||
// timestamps, so the 24h-lookback DM subscriptions redeliver the same
|
||||
// events on every launch and only a cross-launch record stops the
|
||||
// reprocessing (re-sent DELIVERED bursts, phantom-ack noise).
|
||||
// Persist processed private-envelope event IDs: legacy Android can
|
||||
// randomize timestamps across the full 72h15m mailbox lookback, so DM
|
||||
// subscriptions redeliver the same events on every launch and only a
|
||||
// cross-launch record stops the reprocessing (re-sent DELIVERED
|
||||
// bursts, phantom-ack noise).
|
||||
self.deduplicationService = MessageDeduplicationService(nostrEventStore: NostrProcessedEventStore())
|
||||
self.publicMessagePipeline = PublicMessagePipeline()
|
||||
}
|
||||
@@ -176,7 +177,7 @@ private extension ChatViewModelBootstrapper {
|
||||
|
||||
func configureTransport() {
|
||||
viewModel.meshService.delegate = viewModel
|
||||
viewModel.meshService.eventDelegate = viewModel
|
||||
viewModel.messageRouter.setEventDelegate(viewModel)
|
||||
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + TransportConfig.uiStartupInitialDelaySeconds) { [weak viewModel] in
|
||||
guard let viewModel else { return }
|
||||
@@ -558,7 +559,7 @@ private extension ChatViewModelBootstrapper {
|
||||
// Default (DM) relays: drops need the standing global relay set,
|
||||
// not geo relays — sender and recipient share no cell.
|
||||
// This confirmed path never falls back to the volatile relay
|
||||
// queue; bridge dedup is committed only after NIP-20 OK.
|
||||
// queue; bridge dedup is committed only after NIP-01 `OK`.
|
||||
NostrRelayManager.shared.sendEventImmediately(event, completion: completion)
|
||||
}
|
||||
courier.openSubscription = { tagsHex in
|
||||
|
||||
@@ -21,8 +21,8 @@ extension ChatViewModel {
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func subscribeGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) {
|
||||
nostrCoordinator.inbound.subscribeGiftWrap(giftWrap, id: id)
|
||||
func subscribePrivateEnvelope(_ envelope: NostrEvent, id: NostrIdentity) {
|
||||
nostrCoordinator.inbound.subscribePrivateEnvelope(envelope, id: id)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@@ -36,8 +36,8 @@ extension ChatViewModel {
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func handleGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) {
|
||||
nostrCoordinator.inbound.handleGiftWrap(giftWrap, id: id)
|
||||
func handlePrivateEnvelope(_ envelope: NostrEvent, id: NostrIdentity) {
|
||||
nostrCoordinator.inbound.handlePrivateEnvelope(envelope, id: id)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
|
||||
@@ -108,7 +108,7 @@ extension ChatViewModel: GeohashSubscriptionContext {
|
||||
}
|
||||
|
||||
/// Owns subscription IDs and relay lifecycle for geohash channels, geohash
|
||||
/// DMs, the account gift-wrap mailbox, and background geohash sampling. The
|
||||
/// DMs, the account private-envelope mailbox, and background geohash sampling. The
|
||||
/// only component that talks to `NostrRelayManager`; inbound events are
|
||||
/// forwarded to `NostrInboundPipeline` / `GeoPresenceTracker`.
|
||||
final class GeohashSubscriptionManager {
|
||||
@@ -162,13 +162,13 @@ final class GeohashSubscriptionManager {
|
||||
if let identity = try? context.deriveNostrIdentity(forGeohash: channel.geohash) {
|
||||
let dmSub = "geo-dm-\(channel.geohash)"
|
||||
context.setGeoDmSubscriptionID(dmSub)
|
||||
let dmFilter = NostrFilter.giftWrapsFor(
|
||||
let dmFilters = NostrFilter.privateEnvelopeFiltersFor(
|
||||
pubkey: identity.publicKeyHex,
|
||||
since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds)
|
||||
)
|
||||
NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub) { [weak self] giftWrap in
|
||||
NostrRelayManager.shared.subscribe(filters: dmFilters, id: dmSub) { [weak self] envelope in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.inbound.subscribeGiftWrap(giftWrap, id: identity)
|
||||
self?.inbound.subscribePrivateEnvelope(envelope, id: identity)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,13 +260,13 @@ final class GeohashSubscriptionManager {
|
||||
if TorManager.shared.isReady {
|
||||
SecureLogger.debug("GeoDM: subscribing DMs pub=\(identity.publicKeyHex.prefix(8))… sub=\(dmSub)", category: .session)
|
||||
}
|
||||
let dmFilter = NostrFilter.giftWrapsFor(
|
||||
let dmFilters = NostrFilter.privateEnvelopeFiltersFor(
|
||||
pubkey: identity.publicKeyHex,
|
||||
since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds)
|
||||
)
|
||||
NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub) { [weak self] giftWrap in
|
||||
NostrRelayManager.shared.subscribe(filters: dmFilters, id: dmSub) { [weak self] envelope in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.inbound.handleGiftWrap(giftWrap, id: identity)
|
||||
self?.inbound.handlePrivateEnvelope(envelope, id: identity)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -388,14 +388,14 @@ final class GeohashSubscriptionManager {
|
||||
category: .session
|
||||
)
|
||||
|
||||
let filter = NostrFilter.giftWrapsFor(
|
||||
let filters = NostrFilter.privateEnvelopeFiltersFor(
|
||||
pubkey: currentIdentity.publicKeyHex,
|
||||
since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds)
|
||||
)
|
||||
|
||||
context.nostrRelayManager?.subscribe(filter: filter, id: "chat-messages") { [weak self] event in
|
||||
context.nostrRelayManager?.subscribe(filters: filters, id: "chat-messages") { [weak self] event in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.inbound.handleNostrMessage(event)
|
||||
self?.inbound.handleAccountPrivateEnvelope(event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,13 +86,21 @@ extension ChatViewModel: NostrInboundPipelineContext {
|
||||
/// pipeline (which records events into its own dedup cache only AFTER
|
||||
/// verification, so forged copies can't suppress genuine events). This
|
||||
/// pipeline therefore never re-verifies; it keeps its own event-ID dedup
|
||||
/// (cheap main-actor lookups) and moves NIP-17 gift-wrap decryption — two
|
||||
/// (cheap main-actor lookups) and moves private-envelope decryption — two
|
||||
/// ECDH+ChaCha layers — off the main actor with an atomic main-actor
|
||||
/// check-and-record.
|
||||
final class NostrInboundPipeline {
|
||||
private weak var context: (any NostrInboundPipelineContext)?
|
||||
private let presence: GeoPresenceTracker
|
||||
private var geoEventLogCount = 0
|
||||
// During the coordinated wire-format migration, one logical private
|
||||
// payload is published under both primary and compatibility formats. Outer
|
||||
// event IDs differ, so collapse the authenticated embedded payload before
|
||||
// invoking message/ack side effects. Keep this bounded like the outer-ID
|
||||
// caches; the recipient and authenticated sender are part of the key.
|
||||
private var recentPrivatePayloadFormats: [String: UInt8] = [:]
|
||||
private var recentPrivatePayloadKeyOrder: [String] = []
|
||||
private static let privatePayloadDedupCapacity = 2_048
|
||||
|
||||
/// Monotonic panic-wipe generation for this pipeline. A panic wipe clears
|
||||
/// relay handlers so no NEW events flow, but a detached decrypt task
|
||||
@@ -286,13 +294,13 @@ final class NostrInboundPipeline {
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func subscribeGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) {
|
||||
func subscribePrivateEnvelope(_ envelope: NostrEvent, id: NostrIdentity) {
|
||||
guard let context else { return }
|
||||
// Cheap dedup pre-check only; processGeohashGiftWrap does the
|
||||
// Cheap dedup pre-check only; processGeohashPrivateEnvelope does the
|
||||
// authoritative main-actor check-and-record before the off-main
|
||||
// NIP-17 unwrap. The outer signature was already verified (exactly
|
||||
// once, off the main actor) by NostrRelayManager.
|
||||
guard !context.hasProcessedNostrEvent(giftWrap.id) else { return }
|
||||
// private-envelope unwrap. The outer signature was already verified
|
||||
// (exactly once, off the main actor) by NostrRelayManager.
|
||||
guard !context.hasProcessedNostrEvent(envelope.id) else { return }
|
||||
|
||||
// Capture the wipe generation at spawn, alongside the per-geohash
|
||||
// identity (private key) the detached task strongly captures. A panic
|
||||
@@ -300,29 +308,29 @@ final class NostrInboundPipeline {
|
||||
// drops its result instead of delivering plaintext post-wipe.
|
||||
let wipeGeneration = self.wipeGeneration
|
||||
Task.detached(priority: .userInitiated) { [weak self] in
|
||||
await self?.processGeohashGiftWrap(giftWrap, id: id, verbose: false, wipeGeneration: wipeGeneration)
|
||||
await self?.processGeohashPrivateEnvelope(envelope, id: id, verbose: false, wipeGeneration: wipeGeneration)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func handleGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) {
|
||||
func handlePrivateEnvelope(_ envelope: NostrEvent, id: NostrIdentity) {
|
||||
guard let context else { return }
|
||||
// Cheap dedup pre-check only; see subscribeGiftWrap.
|
||||
if context.hasProcessedNostrEvent(giftWrap.id) {
|
||||
// Cheap dedup pre-check only; see subscribePrivateEnvelope.
|
||||
if context.hasProcessedNostrEvent(envelope.id) {
|
||||
return
|
||||
}
|
||||
|
||||
// Spawn-time wipe-generation capture; see subscribeGiftWrap.
|
||||
// Spawn-time wipe-generation capture; see subscribePrivateEnvelope.
|
||||
let wipeGeneration = self.wipeGeneration
|
||||
Task.detached(priority: .userInitiated) { [weak self] in
|
||||
await self?.processGeohashGiftWrap(giftWrap, id: id, verbose: true, wipeGeneration: wipeGeneration)
|
||||
await self?.processGeohashPrivateEnvelope(envelope, id: id, verbose: true, wipeGeneration: wipeGeneration)
|
||||
}
|
||||
}
|
||||
|
||||
/// Geohash-DM gift wrap ingest. The NIP-17 unwrap (two ECDH+ChaCha
|
||||
/// layers) runs off the main actor; results hop back for state updates.
|
||||
/// `verbose` keeps `handleGiftWrap`'s decrypt logging without adding it
|
||||
/// to the sampling path.
|
||||
/// Geohash-DM private-envelope ingest. The envelope unwrap (two
|
||||
/// ECDH+ChaCha layers) runs off the main actor; results hop back for
|
||||
/// state updates. `verbose` keeps `handlePrivateEnvelope`'s decrypt
|
||||
/// logging without adding it to the sampling path.
|
||||
///
|
||||
/// `wipeGeneration` is this pipeline's generation captured at spawn (the
|
||||
/// moment the pre-wipe `id` was captured); a mismatch at either main-actor
|
||||
@@ -330,8 +338,8 @@ final class NostrInboundPipeline {
|
||||
/// decrypting (first hop) or without delivering the plaintext (second
|
||||
/// hop) — the captured identity and any decrypted material are simply
|
||||
/// dropped with the task.
|
||||
private func processGeohashGiftWrap(
|
||||
_ giftWrap: NostrEvent,
|
||||
private func processGeohashPrivateEnvelope(
|
||||
_ envelope: NostrEvent,
|
||||
id: NostrIdentity,
|
||||
verbose: Bool,
|
||||
wipeGeneration: UInt64
|
||||
@@ -341,25 +349,25 @@ final class NostrInboundPipeline {
|
||||
// concurrent detached tasks can't both process the same event.
|
||||
let alreadyProcessed: Bool = await MainActor.run {
|
||||
guard self.wipeGeneration == wipeGeneration else { return true }
|
||||
if context.hasProcessedNostrEvent(giftWrap.id) { return true }
|
||||
context.recordProcessedNostrEvent(giftWrap.id)
|
||||
if context.hasProcessedNostrEvent(envelope.id) { return true }
|
||||
context.recordProcessedNostrEvent(envelope.id)
|
||||
return false
|
||||
}
|
||||
if alreadyProcessed { return }
|
||||
|
||||
guard let (content, senderPubkey, rumorTs) = try? NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
guard let (content, senderPubkey, messageTs) = try? NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: id
|
||||
) else {
|
||||
if verbose {
|
||||
SecureLogger.warning("GeoDM: failed decrypt giftWrap id=\(giftWrap.id.prefix(8))…", category: .session)
|
||||
SecureLogger.warning("GeoDM: failed decrypt private envelope id=\(envelope.id.prefix(8))…", category: .session)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if verbose {
|
||||
SecureLogger.debug(
|
||||
"GeoDM: decrypted gift-wrap id=\(giftWrap.id.prefix(16))... from=\(senderPubkey.prefix(8))...",
|
||||
"GeoDM: decrypted private envelope id=\(envelope.id.prefix(16))... from=\(senderPubkey.prefix(8))...",
|
||||
category: .session
|
||||
)
|
||||
}
|
||||
@@ -375,13 +383,19 @@ final class NostrInboundPipeline {
|
||||
else {
|
||||
return
|
||||
}
|
||||
guard self.shouldProcessPrivatePayload(
|
||||
payload,
|
||||
senderPubkey: senderPubkey,
|
||||
recipientPubkey: id.publicKeyHex,
|
||||
envelopeKind: envelope.kind
|
||||
) else { return }
|
||||
|
||||
let convKey = PeerID(nostr_: senderPubkey)
|
||||
context.registerNostrKeyMapping(senderPubkey, for: convKey)
|
||||
|
||||
switch payload.type {
|
||||
case .privateMessage:
|
||||
let messageTimestamp = Date(timeIntervalSince1970: TimeInterval(rumorTs))
|
||||
let messageTimestamp = Date(timeIntervalSince1970: TimeInterval(messageTs))
|
||||
context.handlePrivateMessage(
|
||||
payload,
|
||||
senderPubkey: senderPubkey,
|
||||
@@ -404,44 +418,44 @@ final class NostrInboundPipeline {
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func handleNostrMessage(_ giftWrap: NostrEvent) {
|
||||
func handleAccountPrivateEnvelope(_ envelope: NostrEvent) {
|
||||
guard let context else { return }
|
||||
// Cheap dedup pre-check only; processNostrMessage does the
|
||||
// authoritative check-and-record before the off-main NIP-17 unwrap.
|
||||
// The outer signature was already verified (exactly once, off the
|
||||
// main actor) by NostrRelayManager, and only verified events are
|
||||
// Cheap dedup pre-check only; processAccountPrivateEnvelope does the
|
||||
// authoritative check-and-record before the off-main private-envelope
|
||||
// unwrap. The outer signature was already verified (exactly once, off
|
||||
// the main actor) by NostrRelayManager, and only verified events are
|
||||
// recorded, so a forged-signature copy can never poison the dedup
|
||||
// set and suppress the genuine event.
|
||||
if context.hasProcessedNostrEvent(giftWrap.id) { return }
|
||||
if context.hasProcessedNostrEvent(envelope.id) { return }
|
||||
|
||||
Task.detached(priority: .userInitiated) { [weak self] in
|
||||
await self?.processNostrMessage(giftWrap)
|
||||
await self?.processAccountPrivateEnvelope(envelope)
|
||||
}
|
||||
}
|
||||
|
||||
func processNostrMessage(_ giftWrap: NostrEvent) async {
|
||||
func processAccountPrivateEnvelope(_ envelope: NostrEvent) async {
|
||||
guard let context else { return }
|
||||
// Authoritative check-and-record, atomic on the main actor so two
|
||||
// concurrent detached tasks can't both process the same event.
|
||||
let alreadyProcessed: Bool = await MainActor.run {
|
||||
if context.hasProcessedNostrEvent(giftWrap.id) { return true }
|
||||
context.recordProcessedNostrEvent(giftWrap.id)
|
||||
if context.hasProcessedNostrEvent(envelope.id) { return true }
|
||||
context.recordProcessedNostrEvent(envelope.id)
|
||||
return false
|
||||
}
|
||||
if alreadyProcessed { return }
|
||||
// Fetch the identity and the wipe generation in ONE main-actor hop:
|
||||
// the generation then vouches for exactly this identity. A wipe after
|
||||
// this point bumps the generation and the delivery hop below drops
|
||||
// the decrypted result (same guard as processGeohashGiftWrap; this
|
||||
// account-mailbox path had the identical hazard).
|
||||
// the decrypted result (same guard as processGeohashPrivateEnvelope;
|
||||
// this account-mailbox path had the identical hazard).
|
||||
let (currentIdentity, wipeGeneration): (NostrIdentity?, UInt64) = await MainActor.run {
|
||||
(context.currentNostrIdentity(), self.wipeGeneration)
|
||||
}
|
||||
guard let currentIdentity else { return }
|
||||
|
||||
do {
|
||||
let (content, senderPubkey, rumorTimestamp) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
let (content, senderPubkey, messageTimestampSeconds) = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: currentIdentity
|
||||
)
|
||||
|
||||
@@ -465,11 +479,17 @@ final class NostrInboundPipeline {
|
||||
|
||||
if packet.type == MessageType.noiseEncrypted.rawValue,
|
||||
let payload = NoisePayload.decode(packet.payload) {
|
||||
let messageTimestamp = Date(timeIntervalSince1970: TimeInterval(rumorTimestamp))
|
||||
let messageTimestamp = Date(timeIntervalSince1970: TimeInterval(messageTimestampSeconds))
|
||||
await MainActor.run {
|
||||
// Drop pre-wipe plaintext if a panic wipe landed
|
||||
// during the off-main decrypt (see above).
|
||||
guard self.wipeGeneration == wipeGeneration else { return }
|
||||
guard self.shouldProcessPrivatePayload(
|
||||
payload,
|
||||
senderPubkey: senderPubkey,
|
||||
recipientPubkey: currentIdentity.publicKeyHex,
|
||||
envelopeKind: envelope.kind
|
||||
) else { return }
|
||||
context.registerNostrKeyMapping(senderPubkey, for: targetPeerID)
|
||||
|
||||
switch payload.type {
|
||||
@@ -543,6 +563,47 @@ final class NostrInboundPipeline {
|
||||
}
|
||||
|
||||
private extension NostrInboundPipeline {
|
||||
@MainActor
|
||||
func shouldProcessPrivatePayload(
|
||||
_ payload: NoisePayload,
|
||||
senderPubkey: String,
|
||||
recipientPubkey: String,
|
||||
envelopeKind: Int
|
||||
) -> Bool {
|
||||
let digest = payload.encode().sha256Fingerprint()
|
||||
let key = "\(recipientPubkey.lowercased()):\(senderPubkey.lowercased()):\(digest)"
|
||||
let formatBit: UInt8
|
||||
switch envelopeKind {
|
||||
case NostrProtocol.EventKind.privateEnvelope.rawValue:
|
||||
formatBit = 1 << 0
|
||||
case NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue:
|
||||
formatBit = 1 << 1
|
||||
default:
|
||||
return true
|
||||
}
|
||||
|
||||
if let observedFormats = recentPrivatePayloadFormats[key] {
|
||||
if observedFormats & formatBit != 0 {
|
||||
// A same-format re-envelope is a delivery retry. Let it reach
|
||||
// the coordinator so a lost DELIVERED acknowledgement can be
|
||||
// sent again; downstream message-ID dedup prevents rerendering.
|
||||
return true
|
||||
}
|
||||
// The same authenticated payload under the other migration format
|
||||
// is the compatibility twin, not a new message or acknowledgement.
|
||||
recentPrivatePayloadFormats[key] = observedFormats | formatBit
|
||||
return false
|
||||
}
|
||||
|
||||
recentPrivatePayloadFormats[key] = formatBit
|
||||
recentPrivatePayloadKeyOrder.append(key)
|
||||
if recentPrivatePayloadKeyOrder.count > Self.privatePayloadDedupCapacity {
|
||||
let evicted = recentPrivatePayloadKeyOrder.removeFirst()
|
||||
recentPrivatePayloadFormats.removeValue(forKey: evicted)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@MainActor
|
||||
static func decodeEmbeddedBitChatPacket(from content: String) -> BitchatPacket? {
|
||||
guard content.hasPrefix("bitchat1:") else { return nil }
|
||||
|
||||
@@ -243,7 +243,7 @@ private func drainMainQueue() async {
|
||||
|
||||
/// Exercises `ChatNostrCoordinator` against `MockChatNostrContext` with no
|
||||
/// `ChatViewModel`. Scoped to the inbound event pipeline (dedup, presence,
|
||||
/// public-message ingest), gift-wrap DM ingest, key mapping, channel-switch
|
||||
/// public-message ingest), private-envelope ingest, key mapping, channel-switch
|
||||
/// teardown, embedded ack flows, and — now that favorites and notifications
|
||||
/// are injected through the context — the favorite-notification ingest and
|
||||
/// the sampled-geohash notification cooldown. Flows that hit live singletons
|
||||
@@ -335,7 +335,7 @@ struct ChatNostrCoordinatorContextTests {
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func handleGiftWrap_routesEmbeddedPrivateMessageAndDeduplicates() async throws {
|
||||
func handlePrivateEnvelope_routesEmbeddedPrivateMessageAndDeduplicates() async throws {
|
||||
let context = MockChatNostrContext()
|
||||
let coordinator = ChatNostrCoordinator(context: context)
|
||||
|
||||
@@ -346,20 +346,30 @@ struct ChatNostrCoordinatorContextTests {
|
||||
messageID: "gm-1",
|
||||
senderPeerID: PeerID(str: "aabbccddeeff0011")
|
||||
))
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelopes = try NostrProtocol.createPrivateEnvelopePublicationBatch(
|
||||
content: embedded,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
coordinator.inbound.handleGiftWrap(giftWrap, id: recipient)
|
||||
for envelope in envelopes {
|
||||
coordinator.inbound.handlePrivateEnvelope(envelope, id: recipient)
|
||||
}
|
||||
|
||||
// The NIP-17 unwrap runs off the main actor; wait for the hop back.
|
||||
// The envelope unwrap runs off the main actor; wait for the hop back.
|
||||
let convKey = PeerID(nostr_: sender.publicKeyHex)
|
||||
let routed = await TestHelpers.waitUntil({ context.handledPrivateMessages.count == 1 })
|
||||
let routed = await TestHelpers.waitUntil({
|
||||
context.handledPrivateMessages.count >= 1
|
||||
&& context.recordedNostrEventIDs.count == envelopes.count
|
||||
})
|
||||
#expect(routed)
|
||||
#expect(context.recordedNostrEventIDs == [giftWrap.id])
|
||||
#expect(Set(context.recordedNostrEventIDs) == Set(envelopes.map(\.id)))
|
||||
#expect(context.nostrKeyMapping[convKey] == sender.publicKeyHex)
|
||||
// The primary and compatibility envelopes carry the same authenticated
|
||||
// embedded payload and must invoke message side effects only once.
|
||||
try? await Task.sleep(nanoseconds: 200_000_000)
|
||||
await drainMainQueue()
|
||||
#expect(context.handledPrivateMessages.count == 1)
|
||||
#expect(context.handledPrivateMessages.first?.senderPubkey == sender.publicKeyHex)
|
||||
#expect(context.handledPrivateMessages.first?.convKey == convKey)
|
||||
|
||||
@@ -370,15 +380,78 @@ struct ChatNostrCoordinatorContextTests {
|
||||
#expect(pm.messageID == "gm-1")
|
||||
#expect(pm.content == "psst")
|
||||
|
||||
// The same gift wrap is dropped on replay.
|
||||
coordinator.inbound.handleGiftWrap(giftWrap, id: recipient)
|
||||
// The same private envelope is dropped on replay.
|
||||
coordinator.inbound.handlePrivateEnvelope(envelopes[0], id: recipient)
|
||||
await drainMainQueue()
|
||||
#expect(context.recordedNostrEventIDs == [giftWrap.id])
|
||||
#expect(Set(context.recordedNostrEventIDs) == Set(envelopes.map(\.id)))
|
||||
#expect(context.handledPrivateMessages.count == 1)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func handleGiftWrap_panicWipeAfterSpawnDropsDecryptedResult() async throws {
|
||||
func migrationEnvelopePairs_processEachMessageAndAckOnlyOnce() async throws {
|
||||
let context = MockChatNostrContext()
|
||||
let coordinator = ChatNostrCoordinator(context: context)
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let sender = try NostrIdentity.generate()
|
||||
let messageContent = try #require(NostrEmbeddedBitChat.encodePMForNostrNoRecipient(
|
||||
content: "migration message",
|
||||
messageID: "migration-message-id",
|
||||
senderPeerID: PeerID(str: "aabbccddeeff0011")
|
||||
))
|
||||
let deliveredContent = try #require(NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(
|
||||
type: .delivered,
|
||||
messageID: "migration-ack-id",
|
||||
senderPeerID: PeerID(str: "aabbccddeeff0011")
|
||||
))
|
||||
let readContent = try #require(NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(
|
||||
type: .readReceipt,
|
||||
messageID: "migration-ack-id",
|
||||
senderPeerID: PeerID(str: "aabbccddeeff0011")
|
||||
))
|
||||
|
||||
var publishedIDs: [String] = []
|
||||
for content in [messageContent, deliveredContent, readContent] {
|
||||
let envelopes = try NostrProtocol.createPrivateEnvelopePublicationBatch(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
#expect(envelopes.count == 2)
|
||||
publishedIDs.append(contentsOf: envelopes.map(\.id))
|
||||
for envelope in envelopes {
|
||||
coordinator.inbound.handlePrivateEnvelope(envelope, id: recipient)
|
||||
}
|
||||
}
|
||||
|
||||
// Envelope unwrap runs off the main actor; wait until every published
|
||||
// event has been recorded, then let any (incorrect) twin deliveries
|
||||
// land before asserting exact side-effect counts.
|
||||
let processed = await TestHelpers.waitUntil({
|
||||
context.recordedNostrEventIDs.count == publishedIDs.count
|
||||
})
|
||||
#expect(processed)
|
||||
try? await Task.sleep(nanoseconds: 200_000_000)
|
||||
await drainMainQueue()
|
||||
|
||||
#expect(context.handledPrivateMessages.count == 1)
|
||||
#expect(context.handledDelivered.count == 1)
|
||||
#expect(context.handledReadReceipts.count == 1)
|
||||
|
||||
// A later same-format re-envelope is a delivery retry, not the
|
||||
// migration twin, so it must still reach downstream message-ID dedup
|
||||
// and acknowledgement resend logic.
|
||||
let primaryRetry = try NostrProtocol.createPrivateEnvelope(
|
||||
content: messageContent,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
coordinator.inbound.handlePrivateEnvelope(primaryRetry, id: recipient)
|
||||
let retried = await TestHelpers.waitUntil({ context.handledPrivateMessages.count == 2 })
|
||||
#expect(retried)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func handlePrivateEnvelope_panicWipeAfterSpawnDropsDecryptedResult() async throws {
|
||||
let context = MockChatNostrContext()
|
||||
let coordinator = ChatNostrCoordinator(context: context)
|
||||
|
||||
@@ -389,7 +462,7 @@ struct ChatNostrCoordinatorContextTests {
|
||||
messageID: "gm-wipe-1",
|
||||
senderPeerID: PeerID(str: "aabbccddeeff0011")
|
||||
))
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: embedded,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
@@ -398,7 +471,7 @@ struct ChatNostrCoordinatorContextTests {
|
||||
// Spawn the detached decrypt (it strongly captures the pre-wipe
|
||||
// identity), then panic-wipe in the SAME main-actor turn — guaranteed
|
||||
// to land before the task's first main-actor hop.
|
||||
coordinator.inbound.handleGiftWrap(giftWrap, id: recipient)
|
||||
coordinator.inbound.handlePrivateEnvelope(envelope, id: recipient)
|
||||
coordinator.inbound.invalidateInFlightDecrypts()
|
||||
|
||||
// Give the detached task ample time to have delivered if the wipe
|
||||
@@ -409,9 +482,9 @@ struct ChatNostrCoordinatorContextTests {
|
||||
#expect(context.handledPrivateMessages.isEmpty)
|
||||
#expect(context.recordedNostrEventIDs.isEmpty)
|
||||
|
||||
// The pipeline itself stays usable: a gift wrap spawned AFTER the
|
||||
// The pipeline itself stays usable: an envelope spawned AFTER the
|
||||
// wipe (new generation) still decrypts and delivers.
|
||||
coordinator.inbound.handleGiftWrap(giftWrap, id: recipient)
|
||||
coordinator.inbound.handlePrivateEnvelope(envelope, id: recipient)
|
||||
let delivered = await TestHelpers.waitUntil({ context.handledPrivateMessages.count == 1 })
|
||||
#expect(delivered)
|
||||
}
|
||||
@@ -424,26 +497,26 @@ struct ChatNostrCoordinatorContextTests {
|
||||
// The inbound pipeline only ever sees verified events.
|
||||
|
||||
@Test @MainActor
|
||||
func processNostrMessage_duplicateDeliveryProcessesOnce() async throws {
|
||||
func processAccountPrivateEnvelope_duplicateDeliveryProcessesOnce() async throws {
|
||||
let context = MockChatNostrContext()
|
||||
let coordinator = ChatNostrCoordinator(context: context)
|
||||
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let sender = try NostrIdentity.generate()
|
||||
context.nostrIdentity = recipient
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: "verify:noop",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
// Fan-in of the same (already verified) gift wrap from several relays
|
||||
// Fan-in of the same (already verified) envelope from several relays
|
||||
// records and processes exactly once.
|
||||
await coordinator.inbound.processNostrMessage(giftWrap)
|
||||
#expect(context.recordedNostrEventIDs == [giftWrap.id])
|
||||
await coordinator.inbound.processAccountPrivateEnvelope(envelope)
|
||||
#expect(context.recordedNostrEventIDs == [envelope.id])
|
||||
|
||||
await coordinator.inbound.processNostrMessage(giftWrap)
|
||||
#expect(context.recordedNostrEventIDs == [giftWrap.id])
|
||||
await coordinator.inbound.processAccountPrivateEnvelope(envelope)
|
||||
#expect(context.recordedNostrEventIDs == [envelope.id])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
|
||||
@@ -176,6 +176,7 @@ private final class MockChatPrivateConversationContext: ChatPrivateConversationC
|
||||
private(set) var geoPrivateMessages: [(content: String, recipientHex: String, messageID: String)] = []
|
||||
private(set) var geoDeliveryAcks: [(messageID: String, recipientHex: String)] = []
|
||||
private(set) var geoReadReceipts: [(messageID: String, recipientHex: String)] = []
|
||||
var geohashPrivateMessageAccepted = true
|
||||
|
||||
func routePrivateMessage(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String) {
|
||||
routedPrivateMessages.append((content, peerID, messageID))
|
||||
@@ -191,8 +192,14 @@ private final class MockChatPrivateConversationContext: ChatPrivateConversationC
|
||||
meshReadReceipts.append((receipt.originalMessageID, peerID))
|
||||
}
|
||||
|
||||
func sendGeohashPrivateMessage(_ content: String, toRecipientHex recipientHex: String, from identity: NostrIdentity, messageID: String) {
|
||||
func sendGeohashPrivateMessage(
|
||||
_ content: String,
|
||||
toRecipientHex recipientHex: String,
|
||||
from identity: NostrIdentity,
|
||||
messageID: String
|
||||
) -> Bool {
|
||||
geoPrivateMessages.append((content, recipientHex, messageID))
|
||||
return geohashPrivateMessageAccepted
|
||||
}
|
||||
|
||||
func sendGeohashDeliveryAck(for messageID: String, toRecipientHex recipientHex: String, from identity: NostrIdentity) {
|
||||
@@ -279,6 +286,11 @@ private func isRead(_ status: DeliveryStatus?, by expected: String) -> Bool {
|
||||
return false
|
||||
}
|
||||
|
||||
private func isFailed(_ status: DeliveryStatus?) -> Bool {
|
||||
if case .failed = status { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
private func makeFavoriteRelationship(
|
||||
noiseKey: Data,
|
||||
nostrPublicKey: String? = nil,
|
||||
@@ -412,6 +424,25 @@ struct ChatPrivateConversationCoordinatorContextTests {
|
||||
#expect(context.privateChats[convKey]?.count == 1)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func sendGeohashDM_rejectedAdmissionNeverBecomesSent() async {
|
||||
let context = MockChatPrivateConversationContext()
|
||||
let coordinator = ChatPrivateConversationCoordinator(context: context)
|
||||
let recipientHex = String(repeating: "33", count: 32)
|
||||
let peerID = PeerID(nostr_: recipientHex)
|
||||
context.activeChannel = .location(
|
||||
GeohashChannel(level: .city, geohash: "u4pruy")
|
||||
)
|
||||
context.nostrKeyMapping[peerID] = recipientHex
|
||||
context.geohashPrivateMessageAccepted = false
|
||||
|
||||
coordinator.sendGeohashDM("rejected", to: peerID)
|
||||
|
||||
#expect(context.geoPrivateMessages.map(\.content) == ["rejected"])
|
||||
#expect(context.privateChats[peerID]?.count == 1)
|
||||
#expect(isFailed(context.privateChats[peerID]?.first?.deliveryStatus))
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func handleViewingThisChat_clearsUnreadAndSendsRoutedReadReceiptOnce() async {
|
||||
let context = MockChatPrivateConversationContext()
|
||||
|
||||
@@ -373,20 +373,25 @@ struct ChatViewModelNostrExtensionTests {
|
||||
// `test_receiveGiftWrap_tamperedSignatureIsDroppedAndDoesNotPoisonDedup`.
|
||||
|
||||
@Test @MainActor
|
||||
func subscribeGiftWrap_rejectsOversizedEmbeddedPacket() async throws {
|
||||
func privateEnvelope_rejectsOversizedEmbeddedPacketBeforePublication() async throws {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
|
||||
let oversized = Data(repeating: 0x41, count: FileTransferLimits.maxFramedFileBytes + 1)
|
||||
let content = "bitchat1:" + base64URLEncode(oversized)
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
do {
|
||||
_ = try NostrProtocol.createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
viewModel.subscribeGiftWrap(giftWrap, id: recipient)
|
||||
Issue.record("Expected oversized private-envelope plaintext to be rejected")
|
||||
} catch NostrError.invalidCiphertext {
|
||||
// Rejected before encryption/publication, as intended.
|
||||
} catch {
|
||||
Issue.record("Expected NostrError.invalidCiphertext, got \(error)")
|
||||
}
|
||||
|
||||
try? await Task.sleep(nanoseconds: 100_000_000)
|
||||
#expect(viewModel.privateChats.isEmpty)
|
||||
@@ -431,7 +436,7 @@ struct ChatViewModelNostrExtensionTests {
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func subscribeGiftWrap_deliveredAckUpdatesExistingMessage() async throws {
|
||||
func subscribePrivateEnvelope_deliveredAckUpdatesExistingMessage() async throws {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
@@ -453,13 +458,13 @@ struct ChatViewModelNostrExtensionTests {
|
||||
], for: convKey)
|
||||
|
||||
let content = try ackContent(type: .delivered, messageID: messageID, senderPeerID: PeerID(str: "0123456789abcdef"))
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
viewModel.subscribeGiftWrap(giftWrap, id: recipient)
|
||||
viewModel.subscribePrivateEnvelope(envelope, id: recipient)
|
||||
|
||||
let didUpdate = await TestHelpers.waitUntil(
|
||||
{ isDelivered(status: deliveryStatus(in: viewModel, peerID: convKey, messageID: messageID)) },
|
||||
@@ -469,7 +474,7 @@ struct ChatViewModelNostrExtensionTests {
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func subscribeGiftWrap_readAckUpdatesExistingMessage() async throws {
|
||||
func subscribePrivateEnvelope_readAckUpdatesExistingMessage() async throws {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
@@ -491,13 +496,13 @@ struct ChatViewModelNostrExtensionTests {
|
||||
], for: convKey)
|
||||
|
||||
let content = try ackContent(type: .readReceipt, messageID: messageID, senderPeerID: PeerID(str: "0123456789abcdef"))
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
viewModel.subscribeGiftWrap(giftWrap, id: recipient)
|
||||
viewModel.subscribePrivateEnvelope(envelope, id: recipient)
|
||||
|
||||
let didUpdate = await TestHelpers.waitUntil(
|
||||
{ isRead(status: deliveryStatus(in: viewModel, peerID: convKey, messageID: messageID)) },
|
||||
@@ -507,28 +512,28 @@ struct ChatViewModelNostrExtensionTests {
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func handleGiftWrap_privateMessageStoresConversationAndMapping() async throws {
|
||||
func handlePrivateEnvelope_privateMessageStoresConversationAndMapping() async throws {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let messageID = "gift-private"
|
||||
let messageID = "envelope-private"
|
||||
let convKey = PeerID(nostr_: sender.publicKeyHex)
|
||||
|
||||
let content = try privateMessageContent(
|
||||
text: "Hello from gift wrap",
|
||||
text: "Hello from private envelope",
|
||||
messageID: messageID,
|
||||
senderPeerID: PeerID(str: "0123456789abcdef")
|
||||
)
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
viewModel.handleGiftWrap(giftWrap, id: recipient)
|
||||
viewModel.handlePrivateEnvelope(envelope, id: recipient)
|
||||
|
||||
let didStore = await TestHelpers.waitUntil(
|
||||
{ viewModel.privateChats[convKey]?.first?.content == "Hello from gift wrap" },
|
||||
{ viewModel.privateChats[convKey]?.first?.content == "Hello from private envelope" },
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(didStore)
|
||||
@@ -537,11 +542,11 @@ struct ChatViewModelNostrExtensionTests {
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func handleGiftWrap_blockedSenderSkipsMessageStorage() async throws {
|
||||
func handlePrivateEnvelope_blockedSenderSkipsMessageStorage() async throws {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let messageID = "gift-blocked"
|
||||
let messageID = "envelope-blocked"
|
||||
let convKey = PeerID(nostr_: sender.publicKeyHex)
|
||||
|
||||
viewModel.identityManager.setNostrBlocked(sender.publicKeyHex, isBlocked: true)
|
||||
@@ -551,13 +556,13 @@ struct ChatViewModelNostrExtensionTests {
|
||||
messageID: messageID,
|
||||
senderPeerID: PeerID(str: "0123456789abcdef")
|
||||
)
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
viewModel.handleGiftWrap(giftWrap, id: recipient)
|
||||
viewModel.handlePrivateEnvelope(envelope, id: recipient)
|
||||
|
||||
// Gift-wrap decryption runs off the main actor; wait for the ack
|
||||
// (sent even for blocked senders) to know processing finished.
|
||||
@@ -570,12 +575,12 @@ struct ChatViewModelNostrExtensionTests {
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func handleGiftWrap_deliveredAckUpdatesExistingMessage() async throws {
|
||||
func handlePrivateEnvelope_deliveredAckUpdatesExistingMessage() async throws {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let convKey = PeerID(nostr_: sender.publicKeyHex)
|
||||
let messageID = "gift-delivered"
|
||||
let messageID = "envelope-delivered"
|
||||
|
||||
viewModel.seedPrivateChat([
|
||||
BitchatMessage(
|
||||
@@ -592,13 +597,13 @@ struct ChatViewModelNostrExtensionTests {
|
||||
], for: convKey)
|
||||
|
||||
let content = try ackContent(type: .delivered, messageID: messageID, senderPeerID: PeerID(str: "0123456789abcdef"))
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
viewModel.handleGiftWrap(giftWrap, id: recipient)
|
||||
viewModel.handlePrivateEnvelope(envelope, id: recipient)
|
||||
|
||||
let didUpdate = await TestHelpers.waitUntil(
|
||||
{ isDelivered(status: deliveryStatus(in: viewModel, peerID: convKey, messageID: messageID)) },
|
||||
@@ -766,6 +771,63 @@ struct ChatViewModelGeoDMTests {
|
||||
#expect(isFailed(status: viewModel.privateChats[convKey]?.last?.deliveryStatus))
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func geohashTerminalRelayFailure_transitionsSentMessageToFailed() async throws {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let messageID = "geo-terminal-failure"
|
||||
let convKey = PeerID(nostr_: recipient.publicKeyHex)
|
||||
let message = BitchatMessage(
|
||||
id: messageID,
|
||||
sender: viewModel.nickname,
|
||||
content: "queued geohash message",
|
||||
timestamp: Date(),
|
||||
isRelay: false,
|
||||
isPrivate: true,
|
||||
recipientNickname: "recipient",
|
||||
senderPeerID: viewModel.myPeerID,
|
||||
deliveryStatus: .sent
|
||||
)
|
||||
viewModel.seedPrivateChat([message], for: convKey)
|
||||
|
||||
var terminalFailure: (@MainActor () -> Void)?
|
||||
let dependencies = NostrTransport.Dependencies(
|
||||
notificationCenter: NotificationCenter(),
|
||||
loadFavorites: { [:] },
|
||||
favoriteStatusForNoiseKey: { _ in nil },
|
||||
favoriteStatusForPeerID: { _ in nil },
|
||||
currentIdentity: { sender },
|
||||
registerPendingPrivateEnvelope: { _ in },
|
||||
sendPrivateEnvelopeBatch: { _, failure in
|
||||
terminalFailure = failure
|
||||
return true
|
||||
},
|
||||
scheduleAfter: { _, _ in },
|
||||
relayConnectivity: {
|
||||
Just(false).eraseToAnyPublisher()
|
||||
}
|
||||
)
|
||||
let transport = viewModel.makeGeohashNostrTransport(
|
||||
dependencies: dependencies
|
||||
)
|
||||
|
||||
let accepted = transport.sendPrivateMessageGeohash(
|
||||
content: message.content,
|
||||
toRecipientHex: recipient.publicKeyHex,
|
||||
from: sender,
|
||||
messageID: messageID
|
||||
)
|
||||
|
||||
#expect(accepted)
|
||||
#expect(viewModel.privateChats[convKey]?.first?.deliveryStatus == .sent)
|
||||
let fail = try #require(terminalFailure)
|
||||
fail()
|
||||
#expect(isFailed(
|
||||
status: viewModel.privateChats[convKey]?.first?.deliveryStatus
|
||||
))
|
||||
}
|
||||
|
||||
/// The blocked notice belongs in the DM thread the person is typing in,
|
||||
/// not on the active location-channel timeline.
|
||||
@Test @MainActor
|
||||
|
||||
@@ -12,7 +12,7 @@ import BitFoundation
|
||||
|
||||
struct NostrProtocolTests {
|
||||
|
||||
@Test func nip17MessageRoundTrip() throws {
|
||||
@Test func privateEnvelopeRoundTrip() throws {
|
||||
// Create sender and recipient identities
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
@@ -21,21 +21,19 @@ struct NostrProtocolTests {
|
||||
print("Recipient pubkey: \(recipient.publicKeyHex)")
|
||||
|
||||
// Create a test message
|
||||
let originalContent = "Hello from NIP-17 test!"
|
||||
let originalContent = "Hello from BitChat private-envelope test!"
|
||||
|
||||
// Create encrypted gift wrap
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: originalContent,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
print("Gift wrap created with ID: \(giftWrap.id)")
|
||||
print("Gift wrap pubkey: \(giftWrap.pubkey)")
|
||||
print("Private envelope created with ID: \(envelope.id)")
|
||||
print("Private envelope pubkey: \(envelope.pubkey)")
|
||||
|
||||
// Decrypt the gift wrap
|
||||
let (decryptedContent, senderPubkey, timestamp) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
let (decryptedContent, senderPubkey, timestamp) = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
|
||||
@@ -51,37 +49,37 @@ struct NostrProtocolTests {
|
||||
print("✅ Successfully decrypted message: '\(decryptedContent)' from \(senderPubkey) at \(messageDate)")
|
||||
}
|
||||
|
||||
@Test func giftWrapUsesUniqueEphemeralKeys() throws {
|
||||
@Test func privateEnvelopesUseUniqueEphemeralKeys() throws {
|
||||
// Create identities
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
|
||||
// Create two messages
|
||||
let message1 = try NostrProtocol.createPrivateMessage(
|
||||
let message1 = try NostrProtocol.createPrivateEnvelope(
|
||||
content: "Message 1",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
let message2 = try NostrProtocol.createPrivateMessage(
|
||||
let message2 = try NostrProtocol.createPrivateEnvelope(
|
||||
content: "Message 2",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
// Gift wrap pubkeys should be different (unique ephemeral keys)
|
||||
// Public envelope keys must be one-time use.
|
||||
#expect(message1.pubkey != message2.pubkey)
|
||||
|
||||
print("Message 1 gift wrap pubkey: \(message1.pubkey)")
|
||||
print("Message 2 gift wrap pubkey: \(message2.pubkey)")
|
||||
print("Message 1 envelope pubkey: \(message1.pubkey)")
|
||||
print("Message 2 envelope pubkey: \(message2.pubkey)")
|
||||
|
||||
// Both should decrypt successfully
|
||||
let (content1, _, _) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: message1,
|
||||
let (content1, _, _) = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: message1,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
let (content2, _, _) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: message2,
|
||||
let (content2, _, _) = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: message2,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
|
||||
@@ -89,79 +87,92 @@ struct NostrProtocolTests {
|
||||
#expect(content2 == "Message 2")
|
||||
}
|
||||
|
||||
@Test func decryptionFailsWithWrongRecipient() throws {
|
||||
@Test func privateEnvelopeUsesBitChatWireFormatAtEveryLayer() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let wrongRecipient = try NostrIdentity.generate()
|
||||
|
||||
// Create message for recipient
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
content: "Secret message",
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: "bitchat-specific",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
// Try to decrypt with wrong recipient. The outer envelope is bound to
|
||||
// the addressed recipient's `p` tag, so this now fails validation
|
||||
// before any decryption is attempted.
|
||||
expectInvalidEvent {
|
||||
_ = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
recipientIdentity: wrongRecipient
|
||||
#expect(envelope.kind == NostrProtocol.EventKind.privateEnvelope.rawValue)
|
||||
#expect(envelope.kind != NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue)
|
||||
#expect(envelope.content.hasPrefix(NostrProtocol.privateEnvelopeContentPrefix))
|
||||
#expect(!envelope.content.hasPrefix("v2:"))
|
||||
#expect(envelope.tags == [["p", recipient.publicKeyHex]])
|
||||
#expect(envelope.created_at <= Int(Date().timeIntervalSince1970))
|
||||
|
||||
let layers = try NostrProtocol.decodePrivateEnvelopeLayersForTesting(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
#expect(layers.seal.kind == NostrProtocol.EventKind.privateSeal.rawValue)
|
||||
#expect(layers.seal.content.hasPrefix(NostrProtocol.privateEnvelopeContentPrefix))
|
||||
#expect(layers.seal.tags.isEmpty)
|
||||
#expect(layers.message.kind == NostrProtocol.EventKind.privateMessage.rawValue)
|
||||
#expect(layers.message.tags.isEmpty)
|
||||
#expect(layers.message.sig == nil)
|
||||
}
|
||||
|
||||
@Test func decryptAcceptsCurrentAndroidInnerRecipientTag() throws {
|
||||
@Test func decryptAcceptsReceiveOnlyLegacyBitChatEnvelope() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let envelope = try NostrProtocol.createLegacyPrivateEnvelopeForTesting(
|
||||
content: "legacy in-flight message",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
#expect(envelope.kind == NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue)
|
||||
#expect(envelope.content.hasPrefix("v2:"))
|
||||
|
||||
let result = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(result.content == "legacy in-flight message")
|
||||
#expect(result.senderPubkey == sender.publicKeyHex)
|
||||
|
||||
let layers = try NostrProtocol.decodePrivateEnvelopeLayersForTesting(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(layers.seal.kind == NostrProtocol.EventKind.legacyNIP59Seal.rawValue)
|
||||
#expect(layers.message.kind == NostrProtocol.EventKind.legacyNIP17DirectMessage.rawValue)
|
||||
#expect(layers.message.tags.isEmpty)
|
||||
}
|
||||
|
||||
@Test func decryptAcceptsCurrentAndroidLegacyInnerRecipientTag() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
|
||||
// Current Android's `createPrivateMessage` emits an unsigned kind-14
|
||||
// inner event with exactly [["p", recipient]], while released iOS
|
||||
// uses no inner tags. This isolated generator reproduces the Android
|
||||
// wire shape without making the production encoder depend on it.
|
||||
let giftWrap = try NostrProtocol.createPrivateMessageWithInnerTagsForTesting(
|
||||
// inner event with exactly [["p", recipient]], while its outer/seal
|
||||
// layers use the deployed BitChat legacy v2 crypto. This isolated
|
||||
// generator reproduces that cross-platform wire shape without making
|
||||
// the production encoder depend on Android's historical tag choice.
|
||||
let envelope = try NostrProtocol.createLegacyPrivateEnvelopeForTesting(
|
||||
content: "legacy message from Android",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender,
|
||||
innerMessageTags: [["p", recipient.publicKeyHex]]
|
||||
)
|
||||
|
||||
let result = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
let layers = try NostrProtocol.decodePrivateEnvelopeLayersForTesting(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(layers.message.tags == [["p", recipient.publicKeyHex]])
|
||||
|
||||
let result = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(result.content == "legacy message from Android")
|
||||
#expect(result.senderPubkey == sender.publicKeyHex)
|
||||
}
|
||||
|
||||
@Test func decryptRejectsAlternateInnerTagShapes() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let otherRecipient = try NostrIdentity.generate()
|
||||
let invalidTagShapes = [
|
||||
[["p", otherRecipient.publicKeyHex]],
|
||||
[["p", recipient.publicKeyHex], ["p", recipient.publicKeyHex]],
|
||||
[["p", recipient.publicKeyHex, "unexpected"]],
|
||||
[["x", recipient.publicKeyHex]]
|
||||
]
|
||||
|
||||
for tags in invalidTagShapes {
|
||||
let giftWrap = try NostrProtocol.createPrivateMessageWithInnerTagsForTesting(
|
||||
content: "invalid inner tag shape",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender,
|
||||
innerMessageTags: tags
|
||||
)
|
||||
expectInvalidEvent {
|
||||
_ = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test func decryptsFrozenLegacyEnvelopeProducedByAndroidB7f0b33d() throws {
|
||||
let eventData = try Data(contentsOf: fixtureURL(
|
||||
name: "AndroidLegacyPrivateEnvelopeB7f0b33d"
|
||||
@@ -190,19 +201,68 @@ struct NostrProtocolTests {
|
||||
#expect(generatorPatch.contains("fun emitCrossPlatformFixtures()"))
|
||||
#expect(generatorPatch.contains(metadata.recipientPrivateKey))
|
||||
#expect(envelope.isValidSignature())
|
||||
#expect(envelope.kind == NostrProtocol.EventKind.giftWrap.rawValue)
|
||||
#expect(envelope.kind == NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue)
|
||||
#expect(envelope.tags == [["p", recipient.publicKeyHex]])
|
||||
|
||||
// The Android inner event carries exactly the recipient `p` tag, so a
|
||||
// successful decrypt also proves the Android inner-tag acceptance.
|
||||
let result = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: envelope,
|
||||
let layers = try NostrProtocol.decodePrivateEnvelopeLayersForTesting(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(layers.message.tags == [["p", recipient.publicKeyHex]])
|
||||
|
||||
let result = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(result.content == "legacy fixture from Android b7f0b33d")
|
||||
#expect(result.senderPubkey == metadata.senderPublicKey)
|
||||
}
|
||||
|
||||
@Test func decryptRejectsAlternateLegacyInnerTags() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let otherRecipient = try NostrIdentity.generate()
|
||||
let invalidTagShapes = [
|
||||
[["p", otherRecipient.publicKeyHex]],
|
||||
[["p", recipient.publicKeyHex], ["p", recipient.publicKeyHex]],
|
||||
[["p", recipient.publicKeyHex, "unexpected"]],
|
||||
[["x", recipient.publicKeyHex]]
|
||||
]
|
||||
|
||||
for tags in invalidTagShapes {
|
||||
let envelope = try NostrProtocol.createLegacyPrivateEnvelopeForTesting(
|
||||
content: "invalid Android-shaped tags",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender,
|
||||
innerMessageTags: tags
|
||||
)
|
||||
expectInvalidEvent {
|
||||
_ = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test func newPrivateEnvelopeRejectsInnerRecipientTag() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let envelope = try NostrProtocol.createPrivateEnvelopeWithInnerTagsForTesting(
|
||||
content: "new format stays strict",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender,
|
||||
innerMessageTags: [["p", recipient.publicKeyHex]]
|
||||
)
|
||||
|
||||
expectInvalidEvent {
|
||||
_ = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func decryptsFrozenLegacyEnvelopeProducedByRelease733098bb() throws {
|
||||
let eventData = try Data(contentsOf: fixtureURL(
|
||||
name: "LegacyPrivateEnvelope733098bb"
|
||||
@@ -216,18 +276,121 @@ struct NostrProtocolTests {
|
||||
let recipient = try NostrIdentity(privateKeyData: recipientKey)
|
||||
|
||||
#expect(envelope.isValidSignature())
|
||||
let result = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: envelope,
|
||||
let result = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(result.content == "legacy fixture from 733098bb")
|
||||
#expect(result.senderPubkey == "2e3d79df7047204f02b726c574e256f8de1dd80510f7dcb8b0d12df13acb87e6")
|
||||
}
|
||||
|
||||
@Test func decryptRejectsOversizedCiphertextBeforeDecoding() throws {
|
||||
@Test func decryptRejectsWrongOuterKind() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: "wrong outer kind",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
// Re-mint the ciphertext under a kind that is not an accepted
|
||||
// private-envelope kind; format resolution must reject it before any
|
||||
// decryption work.
|
||||
let reminted = NostrEvent(
|
||||
pubkey: envelope.pubkey,
|
||||
createdAt: Date(timeIntervalSince1970: TimeInterval(envelope.created_at)),
|
||||
kind: .textNote,
|
||||
tags: envelope.tags,
|
||||
content: envelope.content
|
||||
)
|
||||
|
||||
expectInvalidEvent {
|
||||
_ = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: reminted,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func publicationBatchAlwaysDualPublishesForCoordinatedMigration() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
|
||||
let migrationBatch = try NostrProtocol.createPrivateEnvelopePublicationBatch(
|
||||
content: "mixed-version",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
#expect(migrationBatch.map(\.kind) == [
|
||||
NostrProtocol.EventKind.privateEnvelope.rawValue,
|
||||
NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue
|
||||
])
|
||||
for envelope in migrationBatch {
|
||||
let result = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(result.content == "mixed-version")
|
||||
}
|
||||
|
||||
// The compatibility copy retains the exact released-iOS legacy shape,
|
||||
// which current Android also accepts: kinds 1059/13/14, v2 prefix, and
|
||||
// no inner tags. There is no wall-clock branch that can silently stop
|
||||
// old-client delivery.
|
||||
let compatibilityLayers = try NostrProtocol.decodePrivateEnvelopeLayersForTesting(
|
||||
envelope: migrationBatch[1],
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(migrationBatch[1].content.hasPrefix("v2:"))
|
||||
#expect(compatibilityLayers.seal.kind == NostrProtocol.EventKind.legacyNIP59Seal.rawValue)
|
||||
#expect(compatibilityLayers.message.kind == NostrProtocol.EventKind.legacyNIP17DirectMessage.rawValue)
|
||||
#expect(compatibilityLayers.message.tags.isEmpty)
|
||||
}
|
||||
|
||||
@Test func mailboxLookbackCoversDeliveryWindowAndroidFuzzAndClockSkew() {
|
||||
let sentAt = Date(timeIntervalSince1970: 1_800_000_000)
|
||||
let earliestAndroidTimestamp = sentAt.addingTimeInterval(
|
||||
-TransportConfig.nostrLegacyAndroidTimestampFuzzSeconds
|
||||
)
|
||||
let subscribeAtDeliveryBoundary = sentAt.addingTimeInterval(
|
||||
TransportConfig.nostrPrivateEnvelopeDeliveryWindowSeconds
|
||||
)
|
||||
let filterSince = subscribeAtDeliveryBoundary.addingTimeInterval(
|
||||
-TransportConfig.nostrDMSubscribeLookbackSeconds
|
||||
)
|
||||
|
||||
#expect(TransportConfig.nostrPrivateEnvelopeDeliveryWindowSeconds == 24 * 60 * 60)
|
||||
#expect(TransportConfig.nostrLegacyAndroidTimestampFuzzSeconds == 48 * 60 * 60)
|
||||
#expect(TransportConfig.nostrDMSubscribeClockSkewSeconds == 15 * 60)
|
||||
let expectedLookback: TimeInterval = 72 * 60 * 60 + 15 * 60
|
||||
#expect(TransportConfig.nostrDMSubscribeLookbackSeconds == expectedLookback)
|
||||
#expect(filterSince == earliestAndroidTimestamp.addingTimeInterval(-(15 * 60)))
|
||||
}
|
||||
|
||||
@Test func largePrivateEnvelopeFitsLayerSpecificExpansionLimits() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
// Large enough that the nested Base64 seal exceeds the inner 32 KiB
|
||||
// cap, while the inner message JSON itself remains below that cap.
|
||||
let content = String(repeating: "A", count: 30 * 1024)
|
||||
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
let decrypted = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
|
||||
#expect(decrypted.content == content)
|
||||
#expect(envelope.content.utf8.count <= NostrProtocol.maximumPrivateEnvelopeCiphertextBytes)
|
||||
}
|
||||
|
||||
@Test func privateEnvelopeRejectsOversizedCiphertextBeforeDecoding() throws {
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let wrapper = try NostrIdentity.generate()
|
||||
let oversizedContent = "v2:"
|
||||
let oversizedContent = NostrProtocol.privateEnvelopeContentPrefix
|
||||
+ String(
|
||||
repeating: "A",
|
||||
count: NostrProtocol.maximumPrivateEnvelopeCiphertextBytes
|
||||
@@ -235,21 +398,69 @@ struct NostrProtocolTests {
|
||||
let event = NostrEvent(
|
||||
pubkey: wrapper.publicKeyHex,
|
||||
createdAt: Date(),
|
||||
kind: .giftWrap,
|
||||
kind: .privateEnvelope,
|
||||
tags: [["p", recipient.publicKeyHex]],
|
||||
content: oversizedContent
|
||||
)
|
||||
let signed = try event.sign(with: wrapper.schnorrSigningKey())
|
||||
|
||||
expectInvalidCiphertext {
|
||||
_ = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: signed,
|
||||
_ = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: signed,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func decryptDoesNotMisinterpretStandardNIP44Payload() throws {
|
||||
@Test func privateEnvelopeRejectsOversizedPlaintextBeforeEncryption() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let oversizedPlaintext = String(
|
||||
repeating: "x",
|
||||
count: NostrProtocol.maximumPrivateEnvelopePlaintextBytes + 1
|
||||
)
|
||||
|
||||
expectInvalidCiphertext {
|
||||
_ = try NostrProtocol.createPrivateEnvelope(
|
||||
content: oversizedPlaintext,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func privateEnvelopePublicationBatchRejectsMaximumComposerPayload() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let composerMaximum = String(
|
||||
repeating: "x",
|
||||
count: InputValidator.Limits.maxMessageLength
|
||||
)
|
||||
|
||||
#expect(
|
||||
composerMaximum.utf8.count
|
||||
> NostrProtocol.maximumPrivateEnvelopePlaintextBytes
|
||||
)
|
||||
expectInvalidCiphertext {
|
||||
_ = try NostrProtocol.createPrivateEnvelopePublicationBatch(
|
||||
content: composerMaximum,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func privateEnvelopeRejectsOversizedNestedJSONBeforeParsing() {
|
||||
let oversizedJSON = String(
|
||||
repeating: "{",
|
||||
count: NostrProtocol.maximumPrivateEnvelopePlaintextBytes + 1
|
||||
)
|
||||
expectInvalidCiphertext {
|
||||
_ = try NostrProtocol.decodePrivateEnvelopeEventJSONForTesting(oversizedJSON)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func decryptDoesNotMisinterpretStandardNIP44PayloadAsLegacyBitChat() throws {
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let wrapper = try NostrIdentity.generate()
|
||||
// A valid NIP-44 v2 payload from the official test vectors. Its wire
|
||||
@@ -259,40 +470,36 @@ struct NostrProtocolTests {
|
||||
let event = NostrEvent(
|
||||
pubkey: wrapper.publicKeyHex,
|
||||
createdAt: Date(),
|
||||
kind: .giftWrap,
|
||||
kind: .legacyNIP59GiftWrap,
|
||||
tags: [["p", recipient.publicKeyHex]],
|
||||
content: standardPayload
|
||||
)
|
||||
let signed = try event.sign(with: wrapper.schnorrSigningKey())
|
||||
|
||||
expectInvalidCiphertext {
|
||||
_ = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: signed,
|
||||
_ = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: signed,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func decryptRejectsWrongOuterKind() throws {
|
||||
@Test func decryptionFailsWithWrongRecipient() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
var giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
content: "wrong outer kind",
|
||||
let wrongRecipient = try NostrIdentity.generate()
|
||||
|
||||
// Create message for recipient
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: "Secret message",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
giftWrap = NostrEvent(
|
||||
pubkey: giftWrap.pubkey,
|
||||
createdAt: Date(timeIntervalSince1970: TimeInterval(giftWrap.created_at)),
|
||||
kind: .textNote,
|
||||
tags: giftWrap.tags,
|
||||
content: giftWrap.content
|
||||
)
|
||||
|
||||
expectInvalidEvent {
|
||||
_ = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
recipientIdentity: recipient
|
||||
_ = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: wrongRecipient
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -300,41 +507,41 @@ struct NostrProtocolTests {
|
||||
@Test func decryptRejectsInvalidSealSignature() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let giftWrap = try NostrProtocol.createPrivateMessageWithInvalidSealSignatureForTesting(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelopeWithInvalidSealSignatureForTesting(
|
||||
content: "forged signature",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
expectInvalidEvent {
|
||||
_ = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
_ = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func decryptRejectsSealRumorPubkeyMismatch() throws {
|
||||
@Test func decryptRejectsSealMessagePubkeyMismatch() throws {
|
||||
let claimedSender = try NostrIdentity.generate()
|
||||
let sealSigner = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let giftWrap = try NostrProtocol.createPrivateMessageWithMismatchedSealRumorPubkeyForTesting(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelopeWithMismatchedSealMessagePubkeyForTesting(
|
||||
content: "spoofed sender",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
rumorIdentity: claimedSender,
|
||||
messageIdentity: claimedSender,
|
||||
sealSignerIdentity: sealSigner
|
||||
)
|
||||
|
||||
expectInvalidEvent {
|
||||
_ = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
_ = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func testAckRoundTripNIP44V2_Delivered() throws {
|
||||
func deliveredAckRoundTripsInsidePrivateEnvelope() throws {
|
||||
// Identities
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
@@ -348,19 +555,17 @@ struct NostrProtocolTests {
|
||||
"Failed to embed delivered ack"
|
||||
)
|
||||
|
||||
// Create NIP-17 gift wrap to recipient (uses NIP-44 v2 internally)
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: embedded,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
// Ensure v2 format was used for ciphertext
|
||||
#expect(giftWrap.content.hasPrefix("v2:"))
|
||||
#expect(envelope.content.hasPrefix(NostrProtocol.privateEnvelopeContentPrefix))
|
||||
|
||||
// Decrypt as recipient
|
||||
let (content, senderPubkey, _) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
let (content, senderPubkey, _) = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
|
||||
@@ -385,7 +590,7 @@ struct NostrProtocolTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Test func ackRoundTripNIP44V2_ReadReceipt() throws {
|
||||
@Test func readReceiptRoundTripsInsidePrivateEnvelope() throws {
|
||||
// Identities
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
@@ -397,16 +602,16 @@ struct NostrProtocolTests {
|
||||
"Failed to embed read ack"
|
||||
)
|
||||
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: embedded,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
#expect(giftWrap.content.hasPrefix("v2:"))
|
||||
#expect(envelope.content.hasPrefix(NostrProtocol.privateEnvelopeContentPrefix))
|
||||
|
||||
let (content, senderPubkey, _) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
let (content, senderPubkey, _) = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(senderPubkey == sender.publicKeyHex)
|
||||
@@ -467,7 +672,6 @@ struct NostrProtocolTests {
|
||||
#expect(object["limit"] as? Int == 42)
|
||||
}
|
||||
|
||||
|
||||
@Test func inboundNostrEventRejectsTooManyTags() throws {
|
||||
var eventDict = Self.validInboundEventDict()
|
||||
eventDict["tags"] = Array(
|
||||
@@ -513,6 +717,33 @@ struct NostrProtocolTests {
|
||||
#expect(event.tags.count == 2)
|
||||
}
|
||||
|
||||
@Test func privateEnvelopeFiltersGiveEachMigrationKindAnIndependentRecoveryBudget() throws {
|
||||
let since = Date(timeIntervalSince1970: 1_234_567)
|
||||
let filters = NostrFilter.privateEnvelopeFiltersFor(
|
||||
pubkey: "recipient",
|
||||
since: since
|
||||
)
|
||||
|
||||
#expect(filters.count == 2)
|
||||
let objects = try filters.map { filter in
|
||||
let data = try JSONEncoder().encode(filter)
|
||||
return try #require(
|
||||
try JSONSerialization.jsonObject(with: data) as? [String: Any]
|
||||
)
|
||||
}
|
||||
#expect(objects.compactMap { $0["kinds"] as? [Int] } == [
|
||||
[NostrProtocol.EventKind.privateEnvelope.rawValue],
|
||||
[NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue]
|
||||
])
|
||||
for object in objects {
|
||||
#expect(object["#p"] as? [String] == ["recipient"])
|
||||
#expect(object["since"] as? Int == 1_234_567)
|
||||
#expect(object["limit"] as? Int ==
|
||||
TransportConfig.nostrPrivateEnvelopeFetchLimitPerKind
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
private static func validInboundEventDict() -> [String: Any] {
|
||||
[
|
||||
@@ -557,9 +788,6 @@ struct NostrProtocolTests {
|
||||
}
|
||||
|
||||
private func fixtureURL(name: String, extension fileExtension: String = "json") throws -> URL {
|
||||
// Bundle.module only exists under SwiftPM; the Xcode test targets
|
||||
// resolve resources through the test bundle (same pattern as
|
||||
// NoiseProtocolTests' NoiseTestVectors.json loader).
|
||||
#if SWIFT_PACKAGE
|
||||
let bundle = Bundle.module
|
||||
#else
|
||||
|
||||
@@ -267,6 +267,588 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, TransportConfig.nostrPendingSendQueueCap)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchEvictsEphemeralTrafficAndRemainsAtomic() async throws {
|
||||
let relayURL = "wss://private-batch-priority.example"
|
||||
let context = makeContext(
|
||||
permission: .denied,
|
||||
userTorEnabled: true,
|
||||
torEnforced: true,
|
||||
torIsReady: false
|
||||
)
|
||||
var ephemeralIDs: [String] = []
|
||||
for i in 0..<(TransportConfig.nostrPendingSendQueueCap - 1) {
|
||||
let event = try makeSignedEvent(
|
||||
content: "ephemeral-\(i)",
|
||||
kind: .ephemeralEvent
|
||||
)
|
||||
ephemeralIDs.append(event.id)
|
||||
context.manager.sendEvent(event, to: [relayURL])
|
||||
}
|
||||
let regular = try makeSignedEvent(content: "regular survives")
|
||||
context.manager.sendEvent(regular, to: [relayURL])
|
||||
XCTAssertEqual(
|
||||
context.manager.debugPendingMessageQueueCount,
|
||||
TransportConfig.nostrPendingSendQueueCap
|
||||
)
|
||||
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch([primary, legacy], to: [relayURL]))
|
||||
|
||||
let batches = context.manager.debugPendingMessageQueueEventIDsByBatch
|
||||
let allIDs = Set(batches.flatMap { $0 })
|
||||
XCTAssertEqual(
|
||||
context.manager.debugPendingMessageQueueCount,
|
||||
TransportConfig.nostrPendingSendQueueCap
|
||||
)
|
||||
XCTAssertTrue(batches.contains([primary.id, legacy.id]))
|
||||
XCTAssertTrue(allIDs.contains(regular.id))
|
||||
XCTAssertFalse(allIDs.contains(ephemeralIDs[0]))
|
||||
XCTAssertFalse(allIDs.contains(ephemeralIDs[1]))
|
||||
|
||||
// Later low-priority traffic may evict another ephemeral event, but
|
||||
// never one half (or both halves) of the protected private batch.
|
||||
let lateEphemeral = try makeSignedEvent(content: "late", kind: .geohashPresence)
|
||||
context.manager.sendEvent(lateEphemeral, to: [relayURL])
|
||||
XCTAssertTrue(
|
||||
context.manager.debugPendingMessageQueueEventIDsByBatch
|
||||
.contains([primary.id, legacy.id])
|
||||
)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchDoesNotWriteStaleSocketUntilTorRecovers() async throws {
|
||||
let relayURL = "wss://private-batch-tor-gate.example"
|
||||
let context = makeContext(
|
||||
permission: .denied,
|
||||
userTorEnabled: true,
|
||||
torEnforced: true,
|
||||
torIsReady: true
|
||||
)
|
||||
context.manager.ensureConnections(to: [relayURL])
|
||||
let connected = await waitUntil {
|
||||
context.manager.relays.first(where: { $0.url == relayURL })?.isConnected == true
|
||||
}
|
||||
XCTAssertTrue(connected)
|
||||
let connection = try XCTUnwrap(context.sessionFactory.latestConnection(for: relayURL))
|
||||
|
||||
context.torWaiter.isReady = false
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch([primary, legacy], to: [relayURL]))
|
||||
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertTrue(connection.sentStrings.isEmpty)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
XCTAssertEqual(context.torWaiter.awaitCallCount, 1)
|
||||
|
||||
context.torWaiter.resolve(true)
|
||||
let flushed = await waitUntil {
|
||||
connection.sentStrings.count == 2
|
||||
}
|
||||
XCTAssertTrue(flushed)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
try await emitAcceptedPair([primary, legacy], on: connection)
|
||||
let acknowledged = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(acknowledged)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchPrunesTerminalRelayAfterHealthyDelivery() async throws {
|
||||
let healthyURL = "wss://private-batch-healthy.example"
|
||||
let deadURL = "wss://private-batch-dead.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
context.sessionFactory.pingErrorByURL[deadURL] = NSError(
|
||||
domain: NSURLErrorDomain,
|
||||
code: NSURLErrorCannotFindHost
|
||||
)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
var terminalFailureCount = 0
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(
|
||||
[primary, legacy],
|
||||
to: [healthyURL, deadURL],
|
||||
terminalFailure: { terminalFailureCount += 1 }
|
||||
))
|
||||
|
||||
let healthyConnection = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: healthyURL)
|
||||
)
|
||||
let written = await waitUntil {
|
||||
healthyConnection.sentStrings.count == 2
|
||||
}
|
||||
XCTAssertTrue(written)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
try await emitAcceptedPair([primary, legacy], on: healthyConnection)
|
||||
let initiallyAcknowledged = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(initiallyAcknowledged)
|
||||
XCTAssertEqual(terminalFailureCount, 0)
|
||||
|
||||
// The terminal target is excluded during cooldown. More than one full
|
||||
// protected-capacity worth of subsequent logical sends must continue
|
||||
// to drain through the healthy relay instead of wedging globally.
|
||||
for _ in 0...100 {
|
||||
let sentCountBefore = healthyConnection.sentStrings.count
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(
|
||||
[primary, legacy],
|
||||
to: [healthyURL, deadURL]
|
||||
))
|
||||
let written = await waitUntil {
|
||||
healthyConnection.sentStrings.count == sentCountBefore + 2
|
||||
}
|
||||
XCTAssertTrue(written)
|
||||
try await emitAcceptedPair([primary, legacy], on: healthyConnection)
|
||||
let acknowledged = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(acknowledged)
|
||||
}
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchAllTerminalTargetsReportsWholeBatchFailure() async throws {
|
||||
let deadURL = "wss://private-batch-all-dead.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
context.sessionFactory.pingErrorByURL[deadURL] = NSError(
|
||||
domain: NSURLErrorDomain,
|
||||
code: NSURLErrorCannotFindHost
|
||||
)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
var terminalFailureCount = 0
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(
|
||||
[primary, legacy],
|
||||
to: [deadURL],
|
||||
terminalFailure: { terminalFailureCount += 1 }
|
||||
))
|
||||
|
||||
let failed = await waitUntil {
|
||||
terminalFailureCount == 1 &&
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(failed)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchRejectsBeforeWritingWhenProtectedCapacityIsFull() async throws {
|
||||
let stalledRelayURL = "wss://private-batch-full.example"
|
||||
let connectedRelayURL = "wss://private-batch-connected.example"
|
||||
let context = makeContext(
|
||||
permission: .denied,
|
||||
userTorEnabled: true,
|
||||
torEnforced: true,
|
||||
torIsReady: true,
|
||||
torIsForeground: true
|
||||
)
|
||||
context.manager.ensureConnections(to: [connectedRelayURL])
|
||||
let connected = await waitUntil {
|
||||
context.manager.relays.first(where: { $0.url == connectedRelayURL })?.isConnected == true
|
||||
}
|
||||
XCTAssertTrue(connected)
|
||||
context.torForeground.value = false
|
||||
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
let pair = [primary, legacy]
|
||||
|
||||
for _ in 0..<(TransportConfig.nostrPendingSendQueueCap / pair.count) {
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(pair, to: [stalledRelayURL]))
|
||||
}
|
||||
XCTAssertEqual(
|
||||
context.manager.debugPendingMessageQueueCount,
|
||||
TransportConfig.nostrPendingSendQueueCap
|
||||
)
|
||||
|
||||
let rejectedPrimary = try makeSignedEvent(content: "rejected-primary", kind: .privateEnvelope)
|
||||
let rejectedLegacy = try makeSignedEvent(content: "rejected-legacy", kind: .legacyNIP59GiftWrap)
|
||||
XCTAssertFalse(
|
||||
context.manager.sendPrivateEnvelopeBatch(
|
||||
[rejectedPrimary, rejectedLegacy],
|
||||
to: [connectedRelayURL]
|
||||
)
|
||||
)
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertTrue(
|
||||
context.sessionFactory.latestConnection(for: connectedRelayURL)?.sentStrings.isEmpty == true
|
||||
)
|
||||
let queuedIDs = Set(
|
||||
context.manager.debugPendingMessageQueueEventIDsByBatch.flatMap { $0 }
|
||||
)
|
||||
XCTAssertFalse(queuedIDs.contains(rejectedPrimary.id))
|
||||
XCTAssertFalse(queuedIDs.contains(rejectedLegacy.id))
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchStaysQueuedAndRetriesAfterFirstWriteFails() async throws {
|
||||
try await assertPrivateEnvelopeBatchWriteFailure(
|
||||
failureSequence: [NSError(domain: "send", code: 1)],
|
||||
expectedFirstConnectionWrites: 1
|
||||
)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchStaysQueuedAndRetriesAfterSecondWriteFails() async throws {
|
||||
try await assertPrivateEnvelopeBatchWriteFailure(
|
||||
failureSequence: [nil, NSError(domain: "send", code: 2)],
|
||||
expectedFirstConnectionWrites: 2
|
||||
)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchRemainsPendingUntilBothRelayOKsArrive() async throws {
|
||||
let relayURL = "wss://private-batch-two-write-commit.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch([primary, legacy], to: [relayURL]))
|
||||
let connection = try XCTUnwrap(context.sessionFactory.latestConnection(for: relayURL))
|
||||
connection.deferSendCompletions = true
|
||||
|
||||
let firstWriteStarted = await waitUntil { connection.sentStrings.count == 1 }
|
||||
XCTAssertTrue(firstWriteStarted)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
|
||||
connection.flushDeferredSendCompletions()
|
||||
let secondWriteStarted = await waitUntil { connection.sentStrings.count == 2 }
|
||||
XCTAssertTrue(secondWriteStarted)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
|
||||
connection.flushDeferredSendCompletions()
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
|
||||
try connection.emitOK(eventID: primary.id, success: true, reason: "accepted")
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
|
||||
try connection.emitOK(eventID: legacy.id, success: true, reason: "accepted")
|
||||
let committed = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(committed)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchRejectedHalfReportsWholeBatchFailure() async throws {
|
||||
let relayURL = "wss://private-batch-rejected-half.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
var terminalFailureCount = 0
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(
|
||||
[primary, legacy],
|
||||
to: [relayURL],
|
||||
terminalFailure: { terminalFailureCount += 1 }
|
||||
))
|
||||
let connection = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
let written = await waitUntil { connection.sentStrings.count == 2 }
|
||||
XCTAssertTrue(written)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
|
||||
try connection.emitOK(eventID: primary.id, success: true, reason: "accepted")
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
XCTAssertEqual(terminalFailureCount, 0)
|
||||
|
||||
try connection.emitOK(eventID: legacy.id, success: false, reason: "blocked: policy")
|
||||
let failed = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0 &&
|
||||
terminalFailureCount == 1
|
||||
}
|
||||
XCTAssertTrue(failed)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchDuplicateOKsCountAsDurableAcceptance() async throws {
|
||||
let relayURL = "wss://private-batch-duplicate.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
var terminalFailureCount = 0
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(
|
||||
[primary, legacy],
|
||||
to: [relayURL],
|
||||
terminalFailure: { terminalFailureCount += 1 }
|
||||
))
|
||||
let connection = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
let written = await waitUntil { connection.sentStrings.count == 2 }
|
||||
XCTAssertTrue(written)
|
||||
|
||||
for event in [primary, legacy] {
|
||||
try connection.emitOK(
|
||||
eventID: event.id,
|
||||
success: false,
|
||||
reason: " DuPlIcAtE: already have this event"
|
||||
)
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
let acknowledged = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(acknowledged)
|
||||
XCTAssertEqual(terminalFailureCount, 0)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchAcknowledgementTimeoutReportsWholeBatchFailure() async throws {
|
||||
let relayURL = "wss://private-batch-ok-timeout.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
var terminalFailureCount = 0
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(
|
||||
[primary, legacy],
|
||||
to: [relayURL],
|
||||
terminalFailure: { terminalFailureCount += 1 }
|
||||
))
|
||||
let connection = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
let timeoutScheduled = await waitUntil {
|
||||
connection.sentStrings.count == 2 &&
|
||||
context.scheduler.scheduled.contains {
|
||||
$0.delay == TransportConfig.nostrConfirmedSendAckTimeoutSeconds
|
||||
}
|
||||
}
|
||||
XCTAssertTrue(timeoutScheduled)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
NostrRelayManager.registerPendingPrivateEnvelope(id: primary.id)
|
||||
NostrRelayManager.registerPendingPrivateEnvelope(id: legacy.id)
|
||||
|
||||
context.scheduler.runNext()
|
||||
let failed = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0 &&
|
||||
terminalFailureCount == 1
|
||||
}
|
||||
XCTAssertTrue(failed)
|
||||
|
||||
try connection.emitOK(eventID: primary.id, success: true, reason: "late")
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertEqual(terminalFailureCount, 1)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 0)
|
||||
XCTAssertFalse(NostrRelayManager.pendingPrivateEnvelopeIDs.contains(primary.id))
|
||||
XCTAssertFalse(NostrRelayManager.pendingPrivateEnvelopeIDs.contains(legacy.id))
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchFastPrimaryRejectionStillWritesCompatibilityHalf() async throws {
|
||||
let relayURL = "wss://private-batch-early-reject.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
var terminalFailureCount = 0
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(
|
||||
[primary, legacy],
|
||||
to: [relayURL],
|
||||
terminalFailure: { terminalFailureCount += 1 }
|
||||
))
|
||||
let connection = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
connection.deferSendCompletions = true
|
||||
let firstWriteStarted = await waitUntil { connection.sentStrings.count == 1 }
|
||||
XCTAssertTrue(firstWriteStarted)
|
||||
NostrRelayManager.registerPendingPrivateEnvelope(id: primary.id)
|
||||
NostrRelayManager.registerPendingPrivateEnvelope(id: legacy.id)
|
||||
|
||||
try connection.emitOK(eventID: primary.id, success: false, reason: "invalid: rejected")
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
XCTAssertEqual(terminalFailureCount, 0)
|
||||
XCTAssertEqual(connection.sentStrings.count, 1)
|
||||
|
||||
// Completing the primary write must attempt the legacy 1059 even
|
||||
// though the relay has already rejected the provisional 1402.
|
||||
connection.flushDeferredSendCompletions()
|
||||
let compatibilityWriteStarted = await waitUntil {
|
||||
connection.sentStrings.count == 2
|
||||
}
|
||||
XCTAssertTrue(compatibilityWriteStarted)
|
||||
let compatibilityRequest = try XCTUnwrap(connection.sentStrings.last)
|
||||
let compatibilityJSON = try XCTUnwrap(
|
||||
JSONSerialization.jsonObject(
|
||||
with: Data(compatibilityRequest.utf8)
|
||||
) as? [Any]
|
||||
)
|
||||
let compatibilityEvent = try XCTUnwrap(
|
||||
compatibilityJSON.dropFirst().first as? [String: Any]
|
||||
)
|
||||
XCTAssertEqual(
|
||||
compatibilityEvent["kind"] as? Int,
|
||||
NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue
|
||||
)
|
||||
XCTAssertEqual(compatibilityEvent["id"] as? String, legacy.id)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
XCTAssertEqual(terminalFailureCount, 0)
|
||||
|
||||
connection.flushDeferredSendCompletions()
|
||||
let failed = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0 &&
|
||||
terminalFailureCount == 1
|
||||
}
|
||||
XCTAssertTrue(failed)
|
||||
XCTAssertEqual(connection.cancelCallCount, 0)
|
||||
XCTAssertEqual(
|
||||
context.manager.relays.first(where: { $0.url == relayURL })?.isConnected,
|
||||
true
|
||||
)
|
||||
XCTAssertEqual(terminalFailureCount, 1)
|
||||
XCTAssertFalse(NostrRelayManager.pendingPrivateEnvelopeIDs.contains(primary.id))
|
||||
XCTAssertFalse(NostrRelayManager.pendingPrivateEnvelopeIDs.contains(legacy.id))
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchFastRejectionThenDisconnectReplaysWholePair() async throws {
|
||||
let relayURL = "wss://private-batch-early-reject-replay.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
var terminalFailureCount = 0
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(
|
||||
[primary, legacy],
|
||||
to: [relayURL],
|
||||
terminalFailure: { terminalFailureCount += 1 }
|
||||
))
|
||||
let firstConnection = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
firstConnection.deferSendCompletions = true
|
||||
let firstWriteStarted = await waitUntil {
|
||||
firstConnection.sentStrings.count == 1
|
||||
}
|
||||
XCTAssertTrue(firstWriteStarted)
|
||||
|
||||
try firstConnection.emitOK(
|
||||
eventID: primary.id,
|
||||
success: false,
|
||||
reason: "invalid: rejected"
|
||||
)
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
XCTAssertEqual(terminalFailureCount, 0)
|
||||
|
||||
// Replacing the connection before the sibling write clears the
|
||||
// attempt-scoped rejection. The durable pair must replay in full.
|
||||
context.manager.disconnect()
|
||||
context.manager.connect()
|
||||
let replacementReady = await waitUntil {
|
||||
let connections = context.sessionFactory.connectionsByURL[relayURL] ?? []
|
||||
guard connections.count == 2, let replacement = connections.last else {
|
||||
return false
|
||||
}
|
||||
return replacement.sentStrings.count == 2
|
||||
}
|
||||
XCTAssertTrue(replacementReady)
|
||||
let replacement = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
try await emitAcceptedPair([primary, legacy], on: replacement)
|
||||
let acknowledged = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(acknowledged)
|
||||
XCTAssertEqual(terminalFailureCount, 0)
|
||||
|
||||
// The canceled connection's late completion cannot send its sibling
|
||||
// or mutate the replacement attempt.
|
||||
firstConnection.flushDeferredSendCompletions()
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertEqual(firstConnection.sentStrings.count, 1)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 0)
|
||||
XCTAssertEqual(terminalFailureCount, 0)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchDisconnectDuringWriteReplaysOnReplacementConnection() async throws {
|
||||
let relayURL = "wss://private-batch-background-reconnect.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch([primary, legacy], to: [relayURL]))
|
||||
let firstConnection = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
firstConnection.deferSendCompletions = true
|
||||
let firstWriteStarted = await waitUntil { firstConnection.sentStrings.count == 1 }
|
||||
XCTAssertTrue(firstWriteStarted)
|
||||
|
||||
// Backgrounding cancels the socket while its first write callback is
|
||||
// still outstanding. The pair must remain replayable in the queue.
|
||||
context.manager.disconnect()
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
context.manager.connect()
|
||||
|
||||
let replacementReady = await waitUntil {
|
||||
let connections = context.sessionFactory.connectionsByURL[relayURL] ?? []
|
||||
guard connections.count == 2, let replacement = connections.last else {
|
||||
return false
|
||||
}
|
||||
return replacement.sentStrings.count == 2
|
||||
}
|
||||
XCTAssertTrue(replacementReady)
|
||||
let replacement = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
try await emitAcceptedPair([primary, legacy], on: replacement)
|
||||
let acknowledged = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(acknowledged)
|
||||
|
||||
// A late success callback from the canceled socket must neither send
|
||||
// the legacy half on that stale socket nor disturb the completed pair.
|
||||
firstConnection.flushDeferredSendCompletions()
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertEqual(firstConnection.sentStrings.count, 1)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 0)
|
||||
}
|
||||
|
||||
private func assertPrivateEnvelopeBatchWriteFailure(
|
||||
failureSequence: [Error?],
|
||||
expectedFirstConnectionWrites: Int
|
||||
) async throws {
|
||||
let relayURL = "wss://private-batch-write-failure.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch([primary, legacy], to: [relayURL]))
|
||||
let firstConnection = try XCTUnwrap(context.sessionFactory.latestConnection(for: relayURL))
|
||||
firstConnection.sendErrorSequence = failureSequence
|
||||
|
||||
let stayedQueued = await waitUntil {
|
||||
firstConnection.sentStrings.count == expectedFirstConnectionWrites &&
|
||||
context.manager.debugPendingMessageQueueEventIDsByBatch.contains([primary.id, legacy.id])
|
||||
}
|
||||
XCTAssertTrue(stayedQueued)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
|
||||
// The failed socket is disconnected with bounded backoff. Its queue
|
||||
// item is reused—not re-admitted—and the replacement retries both
|
||||
// copies before the pair is finally removed.
|
||||
XCTAssertFalse(context.scheduler.scheduled.isEmpty)
|
||||
context.scheduler.runNext()
|
||||
let replacementReady = await waitUntil {
|
||||
guard let replacement = context.sessionFactory.latestConnection(for: relayURL),
|
||||
replacement !== firstConnection else { return false }
|
||||
return replacement.sentStrings.count == 2
|
||||
}
|
||||
XCTAssertTrue(replacementReady)
|
||||
let replacement = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
try await emitAcceptedPair([primary, legacy], on: replacement)
|
||||
let acknowledged = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(acknowledged)
|
||||
}
|
||||
|
||||
func test_sendEvent_waitsForTorReadinessBeforeSending() async throws {
|
||||
let relayURL = "wss://tor-ready.example"
|
||||
let context = makeContext(permission: .denied, userTorEnabled: true, torEnforced: true, torIsReady: false)
|
||||
@@ -548,6 +1130,52 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
XCTAssertEqual(context.sessionFactory.latestConnection(for: relayURL)?.sentStrings.count, 1)
|
||||
}
|
||||
|
||||
func test_subscribe_multiplePrivateEnvelopeFiltersEncodesIndependentLimits() async throws {
|
||||
let relayURL = "wss://private-recovery-filters.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let filters = NostrFilter.privateEnvelopeFiltersFor(
|
||||
pubkey: "recipient",
|
||||
since: Date(timeIntervalSince1970: 1_234_567)
|
||||
)
|
||||
|
||||
context.manager.subscribe(
|
||||
filters: filters,
|
||||
id: "private-recovery",
|
||||
relayUrls: [relayURL],
|
||||
handler: { _ in }
|
||||
)
|
||||
|
||||
let sent = await waitUntil {
|
||||
context.sessionFactory.latestConnection(for: relayURL)?.sentStrings.count == 1
|
||||
}
|
||||
XCTAssertTrue(sent)
|
||||
let request = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)?.sentStrings.first
|
||||
)
|
||||
let data = try XCTUnwrap(request.data(using: .utf8))
|
||||
let array = try XCTUnwrap(
|
||||
try JSONSerialization.jsonObject(with: data) as? [Any]
|
||||
)
|
||||
XCTAssertEqual(array.count, 4)
|
||||
XCTAssertEqual(array[0] as? String, "REQ")
|
||||
XCTAssertEqual(array[1] as? String, "private-recovery")
|
||||
let encodedFilters = try [array[2], array[3]].map {
|
||||
try XCTUnwrap($0 as? [String: Any])
|
||||
}
|
||||
XCTAssertEqual(encodedFilters.compactMap { $0["kinds"] as? [Int] }, [
|
||||
[NostrProtocol.EventKind.privateEnvelope.rawValue],
|
||||
[NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue]
|
||||
])
|
||||
for filter in encodedFilters {
|
||||
XCTAssertEqual(
|
||||
filter["limit"] as? Int,
|
||||
TransportConfig.nostrPrivateEnvelopeFetchLimitPerKind
|
||||
)
|
||||
XCTAssertEqual(filter["#p"] as? [String], ["recipient"])
|
||||
XCTAssertEqual(filter["since"] as? Int, 1_234_567)
|
||||
}
|
||||
}
|
||||
|
||||
func test_subscribe_coalescesDuplicateRequestsBeforeTorReadyAndDefersEOSE() async throws {
|
||||
let relayURL = "wss://tor-subscribe-coalesce.example"
|
||||
let context = makeContext(permission: .denied, userTorEnabled: true, torEnforced: true, torIsReady: false)
|
||||
@@ -854,7 +1482,7 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
|
||||
/// The relay boundary is the single signature-verification point for the
|
||||
/// whole inbound path (downstream pipelines no longer re-verify), so a
|
||||
/// tampered gift wrap (kind 1059, the DM/mailbox path) must be dropped
|
||||
/// tampered private envelope (the DM/mailbox path) must be dropped
|
||||
/// here — and must not poison the dedup cache against the genuine copy.
|
||||
func test_receiveGiftWrap_tamperedSignatureIsDroppedAndDoesNotPoisonDedup() async throws {
|
||||
let firstRelayURL = "wss://giftwrap-one.example"
|
||||
@@ -862,7 +1490,7 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
let context = makeContext(permission: .denied)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let giftWrap = try NostrProtocol.createPrivateEnvelope(
|
||||
content: "psst",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
@@ -1039,11 +1667,11 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
XCTAssertTrue(secondDelivered)
|
||||
}
|
||||
|
||||
func test_okMessages_clearPendingGiftWrapIDs() async throws {
|
||||
func test_okMessages_clearPendingPrivateEnvelopeIDs() async throws {
|
||||
let relayURL = "wss://ok.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let successID = "gift-wrap-success"
|
||||
let failureID = "gift-wrap-failure"
|
||||
let successID = "private-envelope-success"
|
||||
let failureID = "private-envelope-failure"
|
||||
|
||||
context.manager.ensureConnections(to: [relayURL])
|
||||
let connected = await waitUntil {
|
||||
@@ -1052,17 +1680,17 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
}
|
||||
XCTAssertTrue(connected)
|
||||
|
||||
NostrRelayManager.registerPendingGiftWrap(id: successID)
|
||||
NostrRelayManager.registerPendingPrivateEnvelope(id: successID)
|
||||
try context.sessionFactory.latestConnection(for: relayURL)?.emitOK(eventID: successID, success: true, reason: "ok")
|
||||
let successCleared = await waitUntil {
|
||||
!NostrRelayManager.pendingGiftWrapIDs.contains(successID)
|
||||
!NostrRelayManager.pendingPrivateEnvelopeIDs.contains(successID)
|
||||
}
|
||||
XCTAssertTrue(successCleared)
|
||||
|
||||
NostrRelayManager.registerPendingGiftWrap(id: failureID)
|
||||
NostrRelayManager.registerPendingPrivateEnvelope(id: failureID)
|
||||
try context.sessionFactory.latestConnection(for: relayURL)?.emitOK(eventID: failureID, success: false, reason: "rejected")
|
||||
let failureCleared = await waitUntil {
|
||||
!NostrRelayManager.pendingGiftWrapIDs.contains(failureID)
|
||||
!NostrRelayManager.pendingPrivateEnvelopeIDs.contains(failureID)
|
||||
}
|
||||
XCTAssertTrue(failureCleared)
|
||||
}
|
||||
@@ -1792,12 +2420,31 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
return filter
|
||||
}
|
||||
|
||||
private func makeSignedEvent(content: String) throws -> NostrEvent {
|
||||
private func emitAcceptedPair(
|
||||
_ events: [NostrEvent],
|
||||
on connection: MockRelayConnection
|
||||
) async throws {
|
||||
for event in events {
|
||||
try connection.emitOK(
|
||||
eventID: event.id,
|
||||
success: true,
|
||||
reason: "accepted"
|
||||
)
|
||||
// Each inbound frame consumes the mock receive handler. Let the
|
||||
// manager re-arm it before delivering the next relay response.
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
}
|
||||
|
||||
private func makeSignedEvent(
|
||||
content: String,
|
||||
kind: NostrProtocol.EventKind = .textNote
|
||||
) throws -> NostrEvent {
|
||||
let identity = try NostrIdentity.generate()
|
||||
let event = NostrEvent(
|
||||
pubkey: identity.publicKeyHex,
|
||||
createdAt: Date(),
|
||||
kind: .textNote,
|
||||
kind: kind,
|
||||
tags: [],
|
||||
content: content
|
||||
)
|
||||
@@ -1937,6 +2584,7 @@ private final class MockRelaySessionFactory: NostrRelaySessionProtocol {
|
||||
private final class MockRelayConnection: NostrRelayConnectionProtocol {
|
||||
private let pingError: Error?
|
||||
var sendError: Error?
|
||||
var sendErrorSequence: [Error?] = []
|
||||
private var receiveHandler: ((Result<URLSessionWebSocketTask.Message, Error>) -> Void)?
|
||||
private(set) var resumeCallCount = 0
|
||||
private(set) var cancelCallCount = 0
|
||||
@@ -1966,14 +2614,15 @@ private final class MockRelayConnection: NostrRelayConnectionProtocol {
|
||||
}
|
||||
|
||||
var deferSendCompletions = false
|
||||
private var deferredSendCompletions: [(Error?) -> Void] = []
|
||||
private var deferredSendCompletions: [(error: Error?, completion: (Error?) -> Void)] = []
|
||||
|
||||
func send(_ message: URLSessionWebSocketTask.Message, completionHandler: @escaping (Error?) -> Void) {
|
||||
sentMessages.append(message)
|
||||
let error = sendErrorSequence.isEmpty ? sendError : sendErrorSequence.removeFirst()
|
||||
if deferSendCompletions {
|
||||
deferredSendCompletions.append(completionHandler)
|
||||
deferredSendCompletions.append((error, completionHandler))
|
||||
} else {
|
||||
completionHandler(sendError)
|
||||
completionHandler(error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1981,7 +2630,7 @@ private final class MockRelayConnection: NostrRelayConnectionProtocol {
|
||||
let pending = deferredSendCompletions
|
||||
deferredSendCompletions = []
|
||||
pending.forEach {
|
||||
$0(sendError)
|
||||
$0.completion($0.error)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -131,7 +131,7 @@ struct NostrTransportTests {
|
||||
#expect(undeliverable)
|
||||
}
|
||||
|
||||
@Test("Private message resolves short peer ID and emits decryptable packet")
|
||||
@Test("Private message resolves short peer ID and emits both migration formats")
|
||||
@MainActor
|
||||
func sendPrivateMessageResolvesShortPeerID() async throws {
|
||||
let keychain = MockKeychain()
|
||||
@@ -153,8 +153,8 @@ struct NostrTransportTests {
|
||||
favoriteStatusForNoiseKey: { _ in nil },
|
||||
favoriteStatusForPeerID: { $0 == shortPeerID ? relationship : nil },
|
||||
currentIdentity: { sender },
|
||||
registerPendingGiftWrap: probe.recordPendingGiftWrap(id:),
|
||||
sendEvent: probe.record(event:),
|
||||
registerPendingPrivateEnvelope: probe.recordPendingPrivateEnvelope(id:),
|
||||
sendPrivateEnvelopeBatch: { events, _ in probe.record(batch: events) },
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
@@ -164,8 +164,12 @@ 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 == 2 }, timeout: 5.0)
|
||||
#expect(didSend)
|
||||
#expect(probe.sentEvents.map(\.kind) == [
|
||||
NostrProtocol.EventKind.privateEnvelope.rawValue,
|
||||
NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue
|
||||
])
|
||||
let result = try decodeEmbeddedPayload(from: probe.sentEvents[0], recipient: recipient)
|
||||
let privateMessage = try decodePrivateMessage(from: result.payload)
|
||||
|
||||
@@ -173,7 +177,583 @@ struct NostrTransportTests {
|
||||
#expect(privateMessage.messageID == "pm-1")
|
||||
#expect(privateMessage.content == "hello over nostr")
|
||||
#expect(result.packet.recipientID == shortPeerID.routingData)
|
||||
#expect(probe.pendingGiftWrapIDs.isEmpty)
|
||||
#expect(probe.pendingPrivateEnvelopeIDs.isEmpty)
|
||||
}
|
||||
|
||||
@Test("Coordinated migration always publishes primary and compatibility envelopes")
|
||||
@MainActor
|
||||
func migrationAlwaysDualPublishes() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let noiseKey = Data((192..<224).map(UInt8.init))
|
||||
let peerID = PeerID(hexData: noiseKey)
|
||||
let relationship = makeRelationship(
|
||||
peerNoisePublicKey: noiseKey,
|
||||
peerNostrPublicKey: recipient.npub,
|
||||
peerNickname: "Migration peer"
|
||||
)
|
||||
|
||||
let migrationProbe = NostrTransportProbe()
|
||||
let migrationTransport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
favoriteStatusForNoiseKey: { $0 == noiseKey ? relationship : nil },
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { events, _ in migrationProbe.record(batch: events) }
|
||||
)
|
||||
)
|
||||
migrationTransport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
migrationTransport.sendPrivateMessage(
|
||||
"migration payload",
|
||||
to: peerID,
|
||||
recipientNickname: "Migration peer",
|
||||
messageID: "migration-pm"
|
||||
)
|
||||
|
||||
let sentPair = await TestHelpers.waitUntil(
|
||||
{ migrationProbe.sentEvents.count == 2 },
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(sentPair)
|
||||
#expect(migrationProbe.sentEvents.map(\.kind) == [
|
||||
NostrProtocol.EventKind.privateEnvelope.rawValue,
|
||||
NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue
|
||||
])
|
||||
for event in migrationProbe.sentEvents {
|
||||
let result = try decodeEmbeddedPayload(from: event, recipient: recipient)
|
||||
let message = try decodePrivateMessage(from: result.payload)
|
||||
#expect(message.messageID == "migration-pm")
|
||||
#expect(message.content == "migration payload")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Rejected migration batch does not register half-delivery state")
|
||||
@MainActor
|
||||
func rejectedMigrationBatchRegistersNothing() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let probe = NostrTransportProbe()
|
||||
var rejectedKinds: [Int] = []
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
currentIdentity: { sender },
|
||||
registerPendingPrivateEnvelope: probe.recordPendingPrivateEnvelope(id:),
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
rejectedKinds = events.map(\.kind)
|
||||
return false
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
|
||||
transport.sendPrivateMessageGeohash(
|
||||
content: "must stay atomic",
|
||||
toRecipientHex: recipient.publicKeyHex,
|
||||
from: sender,
|
||||
messageID: "atomic-reject"
|
||||
)
|
||||
|
||||
let attempted = await TestHelpers.waitUntil({ rejectedKinds.count == 2 }, timeout: 5.0)
|
||||
#expect(attempted)
|
||||
#expect(rejectedKinds == [
|
||||
NostrProtocol.EventKind.privateEnvelope.rawValue,
|
||||
NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue
|
||||
])
|
||||
#expect(probe.pendingPrivateEnvelopeIDs.isEmpty)
|
||||
}
|
||||
|
||||
@Test("Rejected user message emits a visible failed-delivery event")
|
||||
@MainActor
|
||||
func rejectedUserMessageEmitsFailureEvent() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let eventProbe = NostrTransportEventProbe()
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { _, _ in false }
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
transport.eventDelegate = eventProbe
|
||||
|
||||
transport.sendPrivateMessageGeohash(
|
||||
content: "must fail visibly",
|
||||
toRecipientHex: recipient.publicKeyHex,
|
||||
from: sender,
|
||||
messageID: "visible-reject"
|
||||
)
|
||||
|
||||
let reported = await TestHelpers.waitUntil(
|
||||
{ eventProbe.failedMessageIDs == ["visible-reject"] },
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(reported)
|
||||
}
|
||||
|
||||
@Test("Envelope construction failure rejects visibly without publishing")
|
||||
@MainActor
|
||||
func envelopeConstructionFailureRejectsVisibly() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let eventProbe = NostrTransportEventProbe()
|
||||
let publicationProbe = NostrTransportProbe()
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
publicationProbe.record(batch: events)
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
transport.eventDelegate = eventProbe
|
||||
|
||||
// Non-empty but invalid hex reaches envelope construction after the
|
||||
// embedded BitChat packet succeeds, reproducing the throwing batch
|
||||
// builder path without allocating an oversized test fixture.
|
||||
let accepted = transport.sendPrivateMessageGeohash(
|
||||
content: "must fail before sent",
|
||||
toRecipientHex: "not-a-hex-public-key",
|
||||
from: sender,
|
||||
messageID: "build-reject"
|
||||
)
|
||||
|
||||
#expect(!accepted)
|
||||
#expect(publicationProbe.sentEvents.isEmpty)
|
||||
#expect(eventProbe.failedMessageIDs == ["build-reject"])
|
||||
}
|
||||
|
||||
@Test("Unencodable user message rejects visibly without publishing")
|
||||
@MainActor
|
||||
func unencodableUserMessageRejectsVisibly() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let eventProbe = NostrTransportEventProbe()
|
||||
let publicationProbe = NostrTransportProbe()
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
publicationProbe.record(batch: events)
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
transport.eventDelegate = eventProbe
|
||||
|
||||
// PrivateMessagePacket uses the deployed UInt8 content length. Do not
|
||||
// create a larger wire shape that released clients cannot decode.
|
||||
let accepted = transport.sendPrivateMessageGeohash(
|
||||
content: String(repeating: "x", count: 256),
|
||||
toRecipientHex: recipient.publicKeyHex,
|
||||
from: sender,
|
||||
messageID: "packet-reject"
|
||||
)
|
||||
|
||||
#expect(!accepted)
|
||||
#expect(publicationProbe.sentEvents.isEmpty)
|
||||
#expect(eventProbe.failedMessageIDs == ["packet-reject"])
|
||||
}
|
||||
|
||||
@Test("Unencodable direct message emits a visible failure")
|
||||
@MainActor
|
||||
func unencodableDirectMessageEmitsVisibleFailure() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let noiseKey = Data((224..<256).map(UInt8.init))
|
||||
let peerID = PeerID(hexData: noiseKey)
|
||||
let relationship = makeRelationship(
|
||||
peerNoisePublicKey: noiseKey,
|
||||
peerNostrPublicKey: recipient.npub,
|
||||
peerNickname: "Oversized peer"
|
||||
)
|
||||
let eventProbe = NostrTransportEventProbe()
|
||||
let publicationProbe = NostrTransportProbe()
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
favoriteStatusForNoiseKey: {
|
||||
$0 == noiseKey ? relationship : nil
|
||||
},
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
publicationProbe.record(batch: events)
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
transport.eventDelegate = eventProbe
|
||||
|
||||
transport.sendPrivateMessage(
|
||||
String(repeating: "x", count: 256),
|
||||
to: peerID,
|
||||
recipientNickname: "Oversized peer",
|
||||
messageID: "direct-packet-reject"
|
||||
)
|
||||
|
||||
let failed = await TestHelpers.waitUntil(
|
||||
{
|
||||
eventProbe.failedMessageIDs
|
||||
== ["direct-packet-reject"]
|
||||
},
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(failed)
|
||||
#expect(publicationProbe.sentEvents.isEmpty)
|
||||
}
|
||||
|
||||
@Test("Direct message with an invalid npub emits a visible failure")
|
||||
@MainActor
|
||||
func invalidDirectRecipientNpubEmitsVisibleFailure() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let noiseKey = Data(repeating: 0xA5, count: 32)
|
||||
let peerID = PeerID(hexData: noiseKey)
|
||||
let relationship = makeRelationship(
|
||||
peerNoisePublicKey: noiseKey,
|
||||
peerNostrPublicKey: "not-a-valid-npub",
|
||||
peerNickname: "Invalid npub peer"
|
||||
)
|
||||
let eventProbe = NostrTransportEventProbe()
|
||||
let publicationProbe = NostrTransportProbe()
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
favoriteStatusForNoiseKey: {
|
||||
$0 == noiseKey ? relationship : nil
|
||||
},
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
publicationProbe.record(batch: events)
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
transport.eventDelegate = eventProbe
|
||||
|
||||
transport.sendPrivateMessage(
|
||||
"must fail before publication",
|
||||
to: peerID,
|
||||
recipientNickname: "Invalid npub peer",
|
||||
messageID: "invalid-npub"
|
||||
)
|
||||
|
||||
let failed = await TestHelpers.waitUntil(
|
||||
{ eventProbe.failedMessageIDs == ["invalid-npub"] },
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(failed)
|
||||
#expect(publicationProbe.sentEvents.isEmpty)
|
||||
}
|
||||
|
||||
@Test("Direct message without a resolvable recipient emits a visible failure")
|
||||
@MainActor
|
||||
func missingDirectRecipientEmitsVisibleFailure() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let peerID = PeerID(hexData: Data(repeating: 0xC3, count: 32))
|
||||
let eventProbe = NostrTransportEventProbe()
|
||||
let publicationProbe = NostrTransportProbe()
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
publicationProbe.record(batch: events)
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
transport.eventDelegate = eventProbe
|
||||
|
||||
transport.sendPrivateMessage(
|
||||
"must fail without recipient",
|
||||
to: peerID,
|
||||
recipientNickname: "Unknown peer",
|
||||
messageID: "missing-recipient"
|
||||
)
|
||||
|
||||
let failed = await TestHelpers.waitUntil(
|
||||
{ eventProbe.failedMessageIDs == ["missing-recipient"] },
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(failed)
|
||||
#expect(publicationProbe.sentEvents.isEmpty)
|
||||
}
|
||||
|
||||
@Test("Direct message without a current identity emits a visible failure")
|
||||
@MainActor
|
||||
func missingDirectSenderIdentityEmitsVisibleFailure() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let noiseKey = Data(repeating: 0x5A, count: 32)
|
||||
let peerID = PeerID(hexData: noiseKey)
|
||||
let relationship = makeRelationship(
|
||||
peerNoisePublicKey: noiseKey,
|
||||
peerNostrPublicKey: recipient.npub,
|
||||
peerNickname: "Missing identity peer"
|
||||
)
|
||||
let eventProbe = NostrTransportEventProbe()
|
||||
let publicationProbe = NostrTransportProbe()
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
favoriteStatusForNoiseKey: {
|
||||
$0 == noiseKey ? relationship : nil
|
||||
},
|
||||
currentIdentity: { nil },
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
publicationProbe.record(batch: events)
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
transport.eventDelegate = eventProbe
|
||||
|
||||
transport.sendPrivateMessage(
|
||||
"must fail without identity",
|
||||
to: peerID,
|
||||
recipientNickname: "Missing identity peer",
|
||||
messageID: "missing-identity"
|
||||
)
|
||||
|
||||
let failed = await TestHelpers.waitUntil(
|
||||
{ eventProbe.failedMessageIDs == ["missing-identity"] },
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(failed)
|
||||
#expect(publicationProbe.sentEvents.isEmpty)
|
||||
}
|
||||
|
||||
@Test("Rejected favorite notification retains and retries the exact pair")
|
||||
@MainActor
|
||||
func rejectedFavoriteNotificationRetriesExactPair() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let noiseKey = Data((96..<128).map(UInt8.init))
|
||||
let fullPeerID = PeerID(hexData: noiseKey)
|
||||
let relationship = makeRelationship(
|
||||
peerNoisePublicKey: noiseKey,
|
||||
peerNostrPublicKey: recipient.npub,
|
||||
peerNickname: "Retry favorite"
|
||||
)
|
||||
let probe = NostrTransportProbe()
|
||||
var attempts: [[String]] = []
|
||||
weak var releasedTransport: NostrTransport?
|
||||
do {
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
favoriteStatusForNoiseKey: { $0 == noiseKey ? relationship : nil },
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
attempts.append(events.map(\.id))
|
||||
return attempts.count > 1
|
||||
},
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
releasedTransport = transport
|
||||
|
||||
transport.sendFavoriteNotification(to: fullPeerID, isFavorite: true)
|
||||
let retryScheduled = await TestHelpers.waitUntil(
|
||||
{ attempts.count == 1 && probe.scheduledActionCount == 1 },
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(retryScheduled)
|
||||
}
|
||||
#expect(releasedTransport == nil)
|
||||
#expect(probe.runNextScheduledAction())
|
||||
|
||||
let retried = await TestHelpers.waitUntil({ attempts.count == 2 }, timeout: 5.0)
|
||||
#expect(retried)
|
||||
#expect(attempts[0] == attempts[1])
|
||||
}
|
||||
|
||||
@Test("Rejected delivery acknowledgement remains queued for retry")
|
||||
@MainActor
|
||||
func rejectedDeliveryAckRetries() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let noiseKey = Data((128..<160).map(UInt8.init))
|
||||
let fullPeerID = PeerID(hexData: noiseKey)
|
||||
let relationship = makeRelationship(
|
||||
peerNoisePublicKey: noiseKey,
|
||||
peerNostrPublicKey: recipient.npub,
|
||||
peerNickname: "Retry ack"
|
||||
)
|
||||
let probe = NostrTransportProbe()
|
||||
var attempts: [[String]] = []
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
favoriteStatusForNoiseKey: { $0 == noiseKey ? relationship : nil },
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
attempts.append(events.map(\.id))
|
||||
return attempts.count > 1
|
||||
},
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
|
||||
transport.sendDeliveryAck(for: "retry-ack", to: fullPeerID)
|
||||
let firstAttempt = await TestHelpers.waitUntil(
|
||||
{ attempts.count == 1 && probe.scheduledActionCount >= 1 },
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(firstAttempt)
|
||||
|
||||
for _ in 0..<3 where attempts.count < 2 {
|
||||
_ = probe.runNextScheduledAction()
|
||||
_ = await TestHelpers.waitUntil(
|
||||
{ attempts.count == 2 || probe.scheduledActionCount > 0 },
|
||||
timeout: 1.0
|
||||
)
|
||||
}
|
||||
#expect(attempts.count == 2)
|
||||
#expect(attempts[0] == attempts[1])
|
||||
}
|
||||
|
||||
@Test("Control retry queue is bounded and evicted callbacks are harmless")
|
||||
@MainActor
|
||||
func controlRetryQueueIsBounded() async throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let events = try NostrProtocol.createPrivateEnvelopePublicationBatch(
|
||||
content: "bounded retry fixture",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
let probe = NostrTransportProbe()
|
||||
var retryAttempts = 0
|
||||
let queue = NostrPrivateEnvelopeRetryQueue(
|
||||
sendPrivateEnvelopeBatch: { _, _ in
|
||||
retryAttempts += 1
|
||||
return false
|
||||
},
|
||||
registerPendingPrivateEnvelope: { _ in },
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
)
|
||||
|
||||
for index in 0...TransportConfig.nostrPrivateEnvelopeRetryQueueCap {
|
||||
queue.enqueue(
|
||||
key: "control-\(index)",
|
||||
events: events,
|
||||
registerPending: false
|
||||
)
|
||||
}
|
||||
|
||||
#expect(queue.debugPendingCount == TransportConfig.nostrPrivateEnvelopeRetryQueueCap)
|
||||
#expect(!queue.debugContains(key: "control-0"))
|
||||
#expect(queue.debugContains(key: "control-1"))
|
||||
|
||||
// The oldest callback was scheduled before eviction. Running it must
|
||||
// observe the missing key and return without touching dependencies.
|
||||
#expect(probe.runNextScheduledAction())
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
#expect(retryAttempts == 0)
|
||||
|
||||
queue.removeAll()
|
||||
#expect(queue.debugPendingCount == 0)
|
||||
#expect(probe.runNextScheduledAction())
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
#expect(retryAttempts == 0)
|
||||
}
|
||||
|
||||
@Test("Multiple transports share one globally bounded control retry owner")
|
||||
@MainActor
|
||||
func multipleTransportsShareControlRetryQueue() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let events = try NostrProtocol.createPrivateEnvelopePublicationBatch(
|
||||
content: "shared retry fixture",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
let probe = NostrTransportProbe()
|
||||
var retryAttempts = 0
|
||||
let sharedQueue = NostrPrivateEnvelopeRetryQueue(
|
||||
sendPrivateEnvelopeBatch: { _, _ in
|
||||
retryAttempts += 1
|
||||
return false
|
||||
},
|
||||
registerPendingPrivateEnvelope: { _ in },
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
)
|
||||
let first = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(envelopeRetryQueue: sharedQueue)
|
||||
)
|
||||
let second = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(envelopeRetryQueue: sharedQueue)
|
||||
)
|
||||
|
||||
first.debugEnqueueControlRetry(key: "shared", events: events)
|
||||
second.debugEnqueueControlRetry(key: "shared", events: events)
|
||||
#expect(first.debugControlRetryCount == 1)
|
||||
#expect(second.debugControlRetryCount == 1)
|
||||
|
||||
for index in 0...TransportConfig.nostrPrivateEnvelopeRetryQueueCap {
|
||||
let transport = index.isMultiple(of: 2) ? first : second
|
||||
transport.debugEnqueueControlRetry(key: "global-\(index)", events: events)
|
||||
}
|
||||
#expect(first.debugControlRetryCount == TransportConfig.nostrPrivateEnvelopeRetryQueueCap)
|
||||
#expect(second.debugControlRetryCount == TransportConfig.nostrPrivateEnvelopeRetryQueueCap)
|
||||
|
||||
// The first scheduled callback belongs to the now-evicted shared key.
|
||||
#expect(probe.runNextScheduledAction())
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
#expect(retryAttempts == 0)
|
||||
}
|
||||
|
||||
@Test("Favorite notification embeds current npub")
|
||||
@@ -198,8 +778,8 @@ struct NostrTransportTests {
|
||||
favoriteStatusForNoiseKey: { $0 == noiseKey ? relationship : nil },
|
||||
favoriteStatusForPeerID: { _ in nil },
|
||||
currentIdentity: { sender },
|
||||
registerPendingGiftWrap: probe.recordPendingGiftWrap(id:),
|
||||
sendEvent: probe.record(event:),
|
||||
registerPendingPrivateEnvelope: probe.recordPendingPrivateEnvelope(id:),
|
||||
sendPrivateEnvelopeBatch: { events, _ in probe.record(batch: events) },
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
@@ -209,7 +789,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 == 2 }, timeout: 5.0)
|
||||
#expect(didSend)
|
||||
let result = try decodeEmbeddedPayload(from: probe.sentEvents[0], recipient: recipient)
|
||||
let privateMessage = try decodePrivateMessage(from: result.payload)
|
||||
@@ -239,8 +819,8 @@ struct NostrTransportTests {
|
||||
favoriteStatusForNoiseKey: { $0 == noiseKey ? relationship : nil },
|
||||
favoriteStatusForPeerID: { _ in nil },
|
||||
currentIdentity: { sender },
|
||||
registerPendingGiftWrap: probe.recordPendingGiftWrap(id:),
|
||||
sendEvent: probe.record(event:),
|
||||
registerPendingPrivateEnvelope: probe.recordPendingPrivateEnvelope(id:),
|
||||
sendPrivateEnvelopeBatch: { events, _ in probe.record(batch: events) },
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
@@ -250,7 +830,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 == 2 }, timeout: 5.0)
|
||||
#expect(didSend)
|
||||
let result = try decodeEmbeddedPayload(from: probe.sentEvents[0], recipient: recipient)
|
||||
|
||||
@@ -259,9 +839,9 @@ struct NostrTransportTests {
|
||||
#expect(result.packet.recipientID == fullPeerID.toShort().routingData)
|
||||
}
|
||||
|
||||
@Test("Geohash private message registers pending gift wrap")
|
||||
@Test("Geohash private message registers pending private envelope")
|
||||
@MainActor
|
||||
func sendPrivateMessageGeohashRegistersPendingGiftWrap() async throws {
|
||||
func sendPrivateMessageGeohashRegistersPendingPrivateEnvelope() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
@@ -272,8 +852,8 @@ struct NostrTransportTests {
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
currentIdentity: { sender },
|
||||
registerPendingGiftWrap: probe.recordPendingGiftWrap(id:),
|
||||
sendEvent: probe.record(event:),
|
||||
registerPendingPrivateEnvelope: probe.recordPendingPrivateEnvelope(id:),
|
||||
sendPrivateEnvelopeBatch: { events, _ in probe.record(batch: events) },
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
@@ -288,7 +868,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 == 2 }, timeout: 5.0)
|
||||
#expect(didSend)
|
||||
let event = probe.sentEvents[0]
|
||||
let result = try decodeEmbeddedPayload(from: event, recipient: recipient)
|
||||
@@ -297,7 +877,7 @@ struct NostrTransportTests {
|
||||
#expect(privateMessage.messageID == "geo-1")
|
||||
#expect(privateMessage.content == "geo hello")
|
||||
#expect(result.packet.recipientID == nil)
|
||||
#expect(probe.pendingGiftWrapIDs == [event.id])
|
||||
#expect(probe.pendingPrivateEnvelopeIDs == probe.sentEvents.map(\.id))
|
||||
}
|
||||
|
||||
@Test("Read receipt queue sends in order and waits for scheduler")
|
||||
@@ -322,8 +902,8 @@ struct NostrTransportTests {
|
||||
favoriteStatusForNoiseKey: { $0 == noiseKey ? relationship : nil },
|
||||
favoriteStatusForPeerID: { _ in nil },
|
||||
currentIdentity: { sender },
|
||||
registerPendingGiftWrap: probe.recordPendingGiftWrap(id:),
|
||||
sendEvent: probe.record(event:),
|
||||
registerPendingPrivateEnvelope: probe.recordPendingPrivateEnvelope(id:),
|
||||
sendPrivateEnvelopeBatch: { events, _ in probe.record(batch: events) },
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
@@ -338,20 +918,20 @@ struct NostrTransportTests {
|
||||
transport.sendReadReceipt(second, to: fullPeerID)
|
||||
|
||||
let readReceiptTimeout: TimeInterval = 5.0
|
||||
let sentFirst = await TestHelpers.waitUntil({ probe.sentEvents.count >= 1 }, timeout: readReceiptTimeout)
|
||||
try #require(sentFirst, "Expected first queued read receipt event")
|
||||
let sentFirst = await TestHelpers.waitUntil({ probe.sentEvents.count == 2 }, timeout: readReceiptTimeout)
|
||||
try #require(sentFirst, "Expected first queued read receipt pair")
|
||||
let scheduledThrottle = await TestHelpers.waitUntil({ probe.scheduledActionCount == 1 }, timeout: readReceiptTimeout)
|
||||
try #require(scheduledThrottle, "Expected queued throttle action after first read receipt")
|
||||
let firstEvent = try #require(probe.sentEvents.first, "Expected first queued read receipt event")
|
||||
let firstEvent = try #require(probe.sentEvents.first, "Expected first queued read receipt pair")
|
||||
let firstPayload = try decodeEmbeddedPayload(from: firstEvent, recipient: recipient).payload
|
||||
#expect(firstPayload.type == .readReceipt)
|
||||
#expect(String(data: firstPayload.data, encoding: .utf8) == "read-1")
|
||||
|
||||
try #require(probe.runNextScheduledAction(), "Expected queued throttle action after first read receipt")
|
||||
|
||||
let sentSecond = await TestHelpers.waitUntil({ probe.sentEvents.count >= 2 }, timeout: readReceiptTimeout)
|
||||
try #require(sentSecond, "Expected second read receipt after running throttle action")
|
||||
let secondEvent = try #require(probe.sentEvents.last, "Expected second queued read receipt event")
|
||||
let sentSecond = await TestHelpers.waitUntil({ probe.sentEvents.count == 4 }, timeout: readReceiptTimeout)
|
||||
try #require(sentSecond, "Expected second read receipt pair after running throttle action")
|
||||
let secondEvent = probe.sentEvents[2]
|
||||
let secondPayload = try decodeEmbeddedPayload(from: secondEvent, recipient: recipient).payload
|
||||
#expect(secondPayload.type == .readReceipt)
|
||||
#expect(String(data: secondPayload.data, encoding: .utf8) == "read-2")
|
||||
@@ -419,10 +999,14 @@ struct NostrTransportTests {
|
||||
favoriteStatusForNoiseKey: @escaping @MainActor (Data) -> FavoriteRelationship? = { _ in nil },
|
||||
favoriteStatusForPeerID: @escaping @MainActor (PeerID) -> FavoriteRelationship? = { _ in nil },
|
||||
currentIdentity: @escaping @MainActor () throws -> NostrIdentity? = { nil },
|
||||
registerPendingGiftWrap: @escaping @MainActor (String) -> Void = { _ in },
|
||||
sendEvent: @escaping @MainActor (NostrEvent) -> Void = { _ in },
|
||||
registerPendingPrivateEnvelope: @escaping @MainActor (String) -> Void = { _ in },
|
||||
sendPrivateEnvelopeBatch: @escaping @MainActor (
|
||||
[NostrEvent],
|
||||
@escaping @MainActor () -> Void
|
||||
) -> Bool = { _, _ in true },
|
||||
scheduleAfter: @escaping @Sendable (TimeInterval, @escaping @Sendable () -> Void) -> Void = { _, _ in },
|
||||
relayConnectivity: @escaping @MainActor () -> AnyPublisher<Bool, Never> = { Just(false).eraseToAnyPublisher() }
|
||||
relayConnectivity: @escaping @MainActor () -> AnyPublisher<Bool, Never> = { Just(false).eraseToAnyPublisher() },
|
||||
envelopeRetryQueue: NostrPrivateEnvelopeRetryQueue? = nil
|
||||
) -> NostrTransport.Dependencies {
|
||||
NostrTransport.Dependencies(
|
||||
notificationCenter: notificationCenter,
|
||||
@@ -430,10 +1014,11 @@ struct NostrTransportTests {
|
||||
favoriteStatusForNoiseKey: favoriteStatusForNoiseKey,
|
||||
favoriteStatusForPeerID: favoriteStatusForPeerID,
|
||||
currentIdentity: currentIdentity,
|
||||
registerPendingGiftWrap: registerPendingGiftWrap,
|
||||
sendEvent: sendEvent,
|
||||
registerPendingPrivateEnvelope: registerPendingPrivateEnvelope,
|
||||
sendPrivateEnvelopeBatch: sendPrivateEnvelopeBatch,
|
||||
scheduleAfter: scheduleAfter,
|
||||
relayConnectivity: relayConnectivity
|
||||
relayConnectivity: relayConnectivity,
|
||||
envelopeRetryQueue: envelopeRetryQueue
|
||||
)
|
||||
}
|
||||
|
||||
@@ -457,8 +1042,8 @@ struct NostrTransportTests {
|
||||
from event: NostrEvent,
|
||||
recipient: NostrIdentity
|
||||
) throws -> (packet: BitchatPacket, payload: NoisePayload, senderPubkey: String) {
|
||||
let (content, senderPubkey, _) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: event,
|
||||
let (content, senderPubkey, _) = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: event,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
guard content.hasPrefix("bitchat1:") else {
|
||||
@@ -488,6 +1073,17 @@ private enum NostrTransportTestError: Error {
|
||||
case invalidPrivateMessage
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private final class NostrTransportEventProbe: TransportEventDelegate {
|
||||
private(set) var failedMessageIDs: [String] = []
|
||||
|
||||
func didReceiveTransportEvent(_ event: TransportEvent) {
|
||||
guard case .messageDeliveryStatusUpdated(let messageID, let status) = event,
|
||||
case .failed = status else { return }
|
||||
failedMessageIDs.append(messageID)
|
||||
}
|
||||
}
|
||||
|
||||
private func base64URLDecode(_ string: String) -> Data? {
|
||||
var candidate = string
|
||||
let padding = (4 - (candidate.count % 4)) % 4
|
||||
@@ -503,7 +1099,7 @@ private func base64URLDecode(_ string: String) -> Data? {
|
||||
private final class NostrTransportProbe: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var sentEventsStorage: [NostrEvent] = []
|
||||
private var pendingGiftWrapIDsStorage: [String] = []
|
||||
private var pendingPrivateEnvelopeIDsStorage: [String] = []
|
||||
private var scheduledActionsStorage: [(@Sendable () -> Void)] = []
|
||||
|
||||
var sentEvents: [NostrEvent] {
|
||||
@@ -512,10 +1108,10 @@ private final class NostrTransportProbe: @unchecked Sendable {
|
||||
return sentEventsStorage
|
||||
}
|
||||
|
||||
var pendingGiftWrapIDs: [String] {
|
||||
var pendingPrivateEnvelopeIDs: [String] {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return pendingGiftWrapIDsStorage
|
||||
return pendingPrivateEnvelopeIDsStorage
|
||||
}
|
||||
|
||||
var scheduledActionCount: Int {
|
||||
@@ -524,15 +1120,16 @@ private final class NostrTransportProbe: @unchecked Sendable {
|
||||
return scheduledActionsStorage.count
|
||||
}
|
||||
|
||||
func record(event: NostrEvent) {
|
||||
func record(batch: [NostrEvent]) -> Bool {
|
||||
lock.lock()
|
||||
sentEventsStorage.append(event)
|
||||
sentEventsStorage.append(contentsOf: batch)
|
||||
lock.unlock()
|
||||
return true
|
||||
}
|
||||
|
||||
func recordPendingGiftWrap(id: String) {
|
||||
func recordPendingPrivateEnvelope(id: String) {
|
||||
lock.lock()
|
||||
pendingGiftWrapIDsStorage.append(id)
|
||||
pendingPrivateEnvelopeIDsStorage.append(id)
|
||||
lock.unlock()
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user