Files
bitchat/bitchatTests/NostrProtocolTests.swift
845ffc601b Refactor/robustness (#446)
* Refactor BitChat for improved robustness and performance

Major refactoring to simplify architecture and fix critical issues:

Architecture Improvements:
- Replace complex BluetoothMeshService with simplified SimplifiedBluetoothService
- Consolidate message routing and peer management into unified services
- Remove redundant caching layers and optimize performance

Bug Fixes:
- Fix critical BLE peer mapping corruption in mesh networks
- Fix encrypted message routing failures in multi-peer scenarios
- Fix app freezes and Main Thread Checker warnings
- Fix BLE message delivery in dual-role connections
- Fix favorite toggle UI not updating instantly
- Fix Nostr offline messaging with 24-hour message filtering

Features:
- Add command processor for chat commands
- Add autocomplete service for mentions and commands
- Improve private chat management with dedicated service
- Add unified peer service for consistent state management

Performance:
- Optimize BLE reconnection speed
- Reduce excessive logging throughout codebase
- Improve message deduplication efficiency
- Optimize UI updates and state management

* Improvements refactor robust (#441)

* remove unused code

* remove more

* TLV for announcement

* restore

* restore

* restore?

* messages tlv too (#442)

* Fix Nostr notification and read receipt issues, add TLV encoding, cleanup unused code

## Notification & Read Receipt Fixes
- Fixed toolbar notification icon appearing incorrectly on app restart for already-read messages
- Fixed read receipts being incorrectly deleted on startup when privateChats was empty
- Fixed messages not being marked as read when opening chat for first time
- Fixed senderPeerID not being updated during message consolidation
- Added startup phase logic to block old messages (>30s) while allowing recent ones
- Fixed unread status checking across all storage locations (ephemeral, stable Noise keys, temporary Nostr IDs)

## TLV Encoding Implementation
- Implemented Type-Length-Value encoding for private message payloads
- Added PrivateMessagePacket struct with TLV encode/decode methods
- Enhanced message structure for better extensibility and robustness

## Code Cleanup
- Removed unused PeerStateManager class and related dependencies
- Removed dead protocol types (DeliveryAck, ProtocolAck/Nack, NoiseIdentityAnnouncement)
- Cleaned up BitchatDelegate by removing unused methods
- Removed excessive debug logging throughout ChatViewModel
- Added test-only ProtocolNack helper for integration tests

## Technical Details
- Messages stored under three ID types: ephemeral peer IDs, stable Noise key hexes, temporary Nostr IDs
- Fixed cleanupOldReadReceipts() to skip when privateChats is empty or during startup
- Updated message consolidation to properly update senderPeerID
- Restored NIP-17 timestamp randomization (±15 minutes) for privacy

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2025-08-17 01:51:54 +02:00

115 lines
4.0 KiB
Swift

//
// NostrProtocolTests.swift
// bitchatTests
//
// Tests for NIP-17 gift-wrapped private messages
//
import XCTest
import CryptoKit
@testable import bitchat
final class NostrProtocolTests: XCTestCase {
override func setUp() {
super.setUp()
// SecureLogger is always enabled
}
func testNIP17MessageRoundTrip() throws {
// Create sender and recipient identities
let sender = try NostrIdentity.generate()
let recipient = try NostrIdentity.generate()
print("Sender pubkey: \(sender.publicKeyHex)")
print("Recipient pubkey: \(recipient.publicKeyHex)")
// Create a test message
let originalContent = "Hello from NIP-17 test!"
// Create encrypted gift wrap
let giftWrap = try NostrProtocol.createPrivateMessage(
content: originalContent,
recipientPubkey: recipient.publicKeyHex,
senderIdentity: sender
)
print("Gift wrap created with ID: \(giftWrap.id)")
print("Gift wrap pubkey: \(giftWrap.pubkey)")
// Decrypt the gift wrap
let (decryptedContent, senderPubkey, timestamp) = try NostrProtocol.decryptPrivateMessage(
giftWrap: giftWrap,
recipientIdentity: recipient
)
// Verify
XCTAssertEqual(decryptedContent, originalContent)
XCTAssertEqual(senderPubkey, sender.publicKeyHex)
// Verify timestamp is reasonable (within last minute)
let messageDate = Date(timeIntervalSince1970: TimeInterval(timestamp))
let timeDiff = abs(messageDate.timeIntervalSinceNow)
XCTAssertLessThan(timeDiff, 60, "Message timestamp should be recent")
print("✅ Successfully decrypted message: '\(decryptedContent)' from \(senderPubkey) at \(messageDate)")
}
func testGiftWrapUsesUniqueEphemeralKeys() throws {
// Create identities
let sender = try NostrIdentity.generate()
let recipient = try NostrIdentity.generate()
// Create two messages
let message1 = try NostrProtocol.createPrivateMessage(
content: "Message 1",
recipientPubkey: recipient.publicKeyHex,
senderIdentity: sender
)
let message2 = try NostrProtocol.createPrivateMessage(
content: "Message 2",
recipientPubkey: recipient.publicKeyHex,
senderIdentity: sender
)
// Gift wrap pubkeys should be different (unique ephemeral keys)
XCTAssertNotEqual(message1.pubkey, message2.pubkey)
print("Message 1 gift wrap pubkey: \(message1.pubkey)")
print("Message 2 gift wrap pubkey: \(message2.pubkey)")
// Both should decrypt successfully
let (content1, _, _) = try NostrProtocol.decryptPrivateMessage(
giftWrap: message1,
recipientIdentity: recipient
)
let (content2, _, _) = try NostrProtocol.decryptPrivateMessage(
giftWrap: message2,
recipientIdentity: recipient
)
XCTAssertEqual(content1, "Message 1")
XCTAssertEqual(content2, "Message 2")
}
func testDecryptionFailsWithWrongRecipient() 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",
recipientPubkey: recipient.publicKeyHex,
senderIdentity: sender
)
// Try to decrypt with wrong recipient
XCTAssertThrowsError(try NostrProtocol.decryptPrivateMessage(
giftWrap: giftWrap,
recipientIdentity: wrongRecipient
)) { error in
print("Expected error when decrypting with wrong key: \(error)")
}
}
}