mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-25 01:05:19 +00:00
* Live push-to-talk voice for DMs: stream while you talk, voice note as fallback Holding the mic in a DM now streams AAC frames live over the Noise session (walkie-talkie style, ~0.5s mouth-to-ear at one hop) while recording the same audio as a normal voice note. On release the note ships through the existing fileTransfer pipeline; receivers that heard the live stream absorb it silently into the same bubble (matched by the burst ID embedded in the file name), so reliability comes for free and nobody sees duplicates. Protocol: - NoisePayloadType.voiceFrame = 0x08 carrying VoiceBurstPacket (burstID + seq + START/data/END/CANCELED, length-prefixed AAC frames) - 210-byte burst-content budget keeps each Noise packet inside the 256-byte padding bucket: one BLE frame, never the fragment scheduler - fire-and-forget: frames are dropped (never queued) without an established session; live is only offered when the peer is mesh-reachable Receive: - ChatLiveVoiceCoordinator assembles bursts (jitter-ordered, 0.5s gap skip, 3s idle end, flood/size caps), persists progressively as ADTS .aac so even a partial burst is a replayable bubble - live autoplay only when the conversation is on screen, app active, and the new app-info "live voice messages" toggle is on (also gates live sending) - one-playback-at-a-time via a shared ExclusivePlayback slot Capture: - PTTCaptureEngine taps AVAudioEngine, dual-encodes: live AAC frames + the finalized .m4a (same 16kHz/mono/16kbps settings as VoiceRecorder) - VoiceRecordingViewModel now drives a pluggable VoiceCaptureSession; the composer HUD shows a pulsing LIVE treatment when streaming Includes the push-to-talk design doc, 6 new localization keys across all 29 locales, and unit tests for framing, packetizer budget, ADTS output, codec round-trip, and the assembly/absorb lifecycle. Public-mesh PTT (MessageType 0x29) lands separately on top of this. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * PTT follow-ups from review + field test: peer-ID normalization, toggle gates inbound, drop-path diagnostics Codex review fixes (#1403): - makeVoiceCaptureSession normalizes the selected peer with toShort() before the reachability/session checks and binds the send target to that same routing ID — a conversation selected under the stable 64-hex Noise key no longer silently falls back to a classic note while the short-ID session is established - the live-voice toggle now gates inbound bursts too: off means classic-notes-only in both directions (no live bubble, partial file, or early notification; the finalized note still arrives), with a test Field-test diagnostics (first device run: DM frames decrypted but no bubble appeared, with no log evidence of which guard dropped them): - coordinator logs undecodable frames (size + hex prefix) and blocked drops - makeAssembly logs directory/file-handle failures instead of returning nil silently - PTTLiveVoiceSession logs capture start and finish (packet/frame/duration counts); PTTCaptureEngine logs engine start success/failure with the input format; BLEService.sendVoiceFrame logs no-session drops Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix iPhone live-capture failure: dead input unit (AURemoteIO -10851, 0 Hz) Field testing showed the phone's live capture failing at mic enable with AURemoteIO -10851 and an input format of 0 Hz / 2 ch — an input unit bound to an earlier (playback-only or settling) audio session. The Mac, which has no session lifecycle, captured fine, which is why public bursts from the Mac worked while phone-side sends degraded from working (first hold) to sporadic to dead across holds. Three layers of defense: - PTTCaptureEngine recreates its AVAudioEngine on every start(), after the session is configured, so the input unit binds to the session that is active now; a dead input (0 Hz or 0 channels) is now a distinct, logged error instead of a silent setup failure - PTTLiveVoiceSession retries the capture start once after a 150 ms route-settle pause - VoiceRecordingViewModel falls back to the classic VoiceRecorder within the same hold if the live engine still cannot start — a route glitch now costs the live stream, never the voice note Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
160 lines
6.3 KiB
Swift
160 lines
6.3 KiB
Swift
//
|
|
// BitchatProtocol.swift
|
|
// bitchat
|
|
//
|
|
// This is free and unencumbered software released into the public domain.
|
|
// For more information, see <https://unlicense.org>
|
|
//
|
|
|
|
///
|
|
/// # BitchatProtocol
|
|
///
|
|
/// Defines the application-layer protocol for BitChat mesh networking, including
|
|
/// message types, packet structures, and encoding/decoding logic.
|
|
///
|
|
/// ## Overview
|
|
/// BitchatProtocol implements a binary protocol optimized for Bluetooth LE's
|
|
/// constrained bandwidth and MTU limitations. It provides:
|
|
/// - Efficient binary message encoding
|
|
/// - Message fragmentation for large payloads
|
|
/// - TTL-based routing for mesh networks
|
|
/// - Privacy features: message padding and randomized relay jitter
|
|
/// - Integration points for end-to-end encryption
|
|
///
|
|
/// ## Protocol Design
|
|
/// The protocol uses a compact binary format to minimize overhead:
|
|
/// - 1-byte message type identifier
|
|
/// - Variable-length fields with length prefixes
|
|
/// - Network byte order (big-endian) for multi-byte values
|
|
/// - PKCS#7-style padding for privacy
|
|
///
|
|
/// ## Message Flow
|
|
/// 1. **Creation**: Messages are created with type, content, and metadata
|
|
/// 2. **Encoding**: Converted to binary format with proper field ordering
|
|
/// 3. **Fragmentation**: Split if larger than BLE MTU (512 bytes)
|
|
/// 4. **Transmission**: Sent via BLEService
|
|
/// 5. **Routing**: Relayed by intermediate nodes (TTL decrements)
|
|
/// 6. **Reassembly**: Fragments collected and reassembled
|
|
/// 7. **Decoding**: Binary data parsed back to message objects
|
|
///
|
|
/// ## Security Considerations
|
|
/// - Message padding (to 256/512/1024/2048-byte blocks) obscures actual content length
|
|
/// - Randomized relay jitter reduces the traffic-analysis signal; there is no
|
|
/// cover traffic or per-message timing obfuscation
|
|
/// - Integration with Noise Protocol for E2E encryption
|
|
/// - No persistent identifiers in protocol headers
|
|
///
|
|
/// ## Message Types
|
|
/// - **Announce/Leave**: Peer presence notifications
|
|
/// - **Message**: Public chat messages
|
|
/// - **Fragment**: Multi-part message handling
|
|
/// - **NoiseHandshake/NoiseEncrypted**: Encrypted channel establishment and
|
|
/// all private payloads (messages, delivery acks, read receipts)
|
|
/// - **CourierEnvelope**: Sealed store-and-forward mail
|
|
/// - **RequestSync/FileTransfer**: Gossip history sync and media transfer
|
|
///
|
|
/// ## Future Extensions
|
|
/// The protocol is designed to be extensible:
|
|
/// - Reserved message type ranges for future use
|
|
/// - Version field for protocol evolution
|
|
/// - Optional fields for new features
|
|
///
|
|
|
|
import Foundation
|
|
import CoreBluetooth
|
|
import BitFoundation
|
|
|
|
// MARK: - Noise Payload Types
|
|
|
|
/// Types of payloads embedded within noiseEncrypted messages.
|
|
/// The first byte of decrypted Noise payload indicates the type.
|
|
/// This provides privacy - observers can't distinguish message types.
|
|
enum NoisePayloadType: UInt8 {
|
|
// Messages and status
|
|
case privateMessage = 0x01 // Private chat message
|
|
case readReceipt = 0x02 // Message was read
|
|
case delivered = 0x03 // Message was delivered
|
|
// Private groups (0x04/0x05 reserved by other features)
|
|
case groupInvite = 0x06 // Creator-signed group state (invite)
|
|
case groupKeyUpdate = 0x07 // Creator-signed group state (key rotation / roster update)
|
|
// Live voice (push-to-talk)
|
|
case voiceFrame = 0x08 // One live voice-burst packet (see VoiceBurstPacket)
|
|
// Verification (QR-based OOB binding)
|
|
case verifyChallenge = 0x10 // Verification challenge
|
|
case verifyResponse = 0x11 // Verification response
|
|
// Transitive verification (web of trust)
|
|
case vouch = 0x12 // Batch of vouch attestations
|
|
|
|
var description: String {
|
|
switch self {
|
|
case .privateMessage: return "privateMessage"
|
|
case .readReceipt: return "readReceipt"
|
|
case .delivered: return "delivered"
|
|
case .groupInvite: return "groupInvite"
|
|
case .groupKeyUpdate: return "groupKeyUpdate"
|
|
case .voiceFrame: return "voiceFrame"
|
|
case .verifyChallenge: return "verifyChallenge"
|
|
case .verifyResponse: return "verifyResponse"
|
|
case .vouch: return "vouch"
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Handshake State
|
|
|
|
// Lazy handshake state tracking
|
|
enum LazyHandshakeState {
|
|
case none // No session, no handshake attempted
|
|
case handshakeQueued // User action requires handshake
|
|
case handshaking // Currently in handshake process
|
|
case established // Session ready for use
|
|
case failed(Error) // Handshake failed
|
|
}
|
|
|
|
// MARK: - Delegate Protocol
|
|
|
|
protocol BitchatDelegate: AnyObject {
|
|
func didReceiveMessage(_ message: BitchatMessage)
|
|
func didConnectToPeer(_ peerID: PeerID)
|
|
func didDisconnectFromPeer(_ peerID: PeerID)
|
|
func didUpdatePeerList(_ peers: [PeerID])
|
|
|
|
// Optional method to check if a fingerprint belongs to a favorite peer
|
|
func isFavorite(fingerprint: String) -> Bool
|
|
|
|
func didUpdateMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus)
|
|
|
|
// Low-level events for better separation of concerns
|
|
func didReceiveNoisePayload(from peerID: PeerID, type: NoisePayloadType, payload: Data, timestamp: Date)
|
|
|
|
// Encrypted group broadcast (opaque envelope; decrypted by the group coordinator)
|
|
func didReceiveGroupMessage(payload: Data, timestamp: Date)
|
|
|
|
// Bluetooth state updates for user notifications
|
|
func didUpdateBluetoothState(_ state: CBManagerState)
|
|
func didReceivePublicMessage(from peerID: PeerID, nickname: String, content: String, timestamp: Date, messageID: String?)
|
|
}
|
|
|
|
// Provide default implementation to make it effectively optional
|
|
extension BitchatDelegate {
|
|
func isFavorite(fingerprint: String) -> Bool {
|
|
return false
|
|
}
|
|
|
|
func didUpdateMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) {
|
|
// Default empty implementation
|
|
}
|
|
|
|
func didReceiveNoisePayload(from peerID: PeerID, type: NoisePayloadType, payload: Data, timestamp: Date) {
|
|
// Default empty implementation
|
|
}
|
|
|
|
func didReceiveGroupMessage(payload: Data, timestamp: Date) {
|
|
// Default empty implementation
|
|
}
|
|
|
|
func didReceivePublicMessage(from peerID: PeerID, nickname: String, content: String, timestamp: Date, messageID: String?) {
|
|
// Default empty implementation
|
|
}
|
|
}
|