Remove unnecessary documentation files - keep only README.md

This commit is contained in:
jack
2025-07-04 16:50:35 +02:00
parent 7c95595d5b
commit 25de7df10e
3 changed files with 0 additions and 449 deletions
-94
View File
@@ -1,94 +0,0 @@
# BitChat Scaling Optimizations
## Overview
Implemented practical scaling optimizations to improve BitChat's capacity from ~20-30 users to potentially 50-100 users while maintaining privacy and simplicity.
## Optimizations Implemented
### 1. **Probabilistic Flooding**
- Messages are relayed with probability based on network density
- Reduces redundant transmissions in dense networks
- Adaptive relay probability:
- ≤5 users: 100% relay (ensure delivery)
- ≤15 users: 80% relay
- ≤30 users: 60% relay
- ≤50 users: 40% relay
- >50 users: 30% relay (minimum)
- Random delay (50-500ms) prevents collision storms
### 2. **Bloom Filter for Duplicate Detection**
- 4096-bit bloom filter (512 bytes) for fast duplicate checking
- 3 hash functions for optimal false positive rate
- Resets every 5 minutes to prevent saturation
- Combined with exact set for accuracy
- O(1) lookup time vs O(n) for set membership
### 3. **Connection Pooling & Exponential Backoff**
- Reuses existing peripheral connections
- Tracks connection attempts per peripheral
- Exponential backoff: 1s × 2^attempts after failures
- Maximum 3 connection attempts
- Reduces connection churn and battery usage
### 4. **Adaptive TTL**
- TTL adjusts based on network size:
- ≤10 users: TTL=5 (maximum reach)
- ≤30 users: TTL=4
- ≤50 users: TTL=3
- >50 users: TTL=2 (limit propagation)
- Prevents message storms in large networks
### 5. **Message Aggregation (Framework)**
- 100ms aggregation window
- Groups messages by destination
- Sends with 20ms spacing to prevent collisions
- Ready for future batching optimizations
### 6. **BLE Advertisement Enhancements**
- Includes network size hint in manufacturer data
- Battery level in advertisements
- Enables network-aware decisions without connections
- Lightweight presence detection
## Performance Impact
### Before Optimizations
- Full mesh: O(n²) connections
- Every node relays every message
- Fixed TTL=5 for all messages
- Connection attempts without backoff
- Linear duplicate detection
### After Optimizations
- Same mesh topology but smarter behavior
- 30-70% relay reduction in dense networks
- Dynamic TTL reduces unnecessary hops
- Connection failures don't cause storms
- Constant-time duplicate detection
## Estimated Capacity
- **Small groups (5-10 users)**: Excellent performance, minimal change
- **Medium groups (20-30 users)**: Good performance, noticeable improvement
- **Large groups (50-100 users)**: Functional but degraded experience
- **Very large (100+ users)**: Not recommended without architectural changes
## Future Improvements
1. **Hierarchical Clustering**: Elect cluster heads for inter-cluster routing
2. **DHT-based Routing**: Distributed hash table for targeted message delivery
3. **True Message Aggregation**: Combine multiple messages into single packets
4. **Adaptive Scanning**: Reduce scan frequency based on network load
5. **Priority Queues**: Prioritize direct messages over broadcasts
## Trade-offs
- **Privacy maintained**: No routing tables or persistent node IDs
- **Complexity limited**: Avoided heavyweight protocols (OLSR/AODV)
- **Battery impact**: Slightly higher CPU usage for bloom filter
- **Reliability**: Probabilistic relay may miss some messages in edge cases
## Configuration
All parameters are adaptive and require no user configuration. The system automatically adjusts based on:
- Network size (peer count)
- Battery level
- Connection quality
This approach balances scalability improvements with BitChat's core values of simplicity and privacy.
-148
View File
@@ -1,148 +0,0 @@
# Bitchat Technical Debt Remediation Plan
## Overview
This document outlines the technical debt in the bitchat project and provides a prioritized plan for addressing it.
## Priority 1: Critical Security & Stability (1-2 weeks)
### 1.1 Thread Safety Issues
**Problem**: Potential race conditions in message processing and peer management
**Solution**:
- Audit all concurrent access to shared state
- Add proper synchronization to message queues
- Use actor pattern for BluetoothMeshService
- Add thread sanitizer to debug builds
### 1.2 Error Handling
**Problem**: Many errors are silently logged without proper recovery
**Solution**:
- Implement proper error propagation
- Add user-visible error states
- Create recovery mechanisms for common failures
- Add crash reporting for TestFlight
### 1.3 Memory Management
**Problem**: Fragment cleanup could leak memory, no proper cleanup on errors
**Solution**:
- Add fragment timeout cleanup
- Implement proper weak references in closures
- Add memory pressure handling
- Profile with Instruments
## Priority 2: Code Quality & Maintainability (2-3 weeks)
### 2.1 Service Refactoring
**Problem**: BluetoothMeshService is 1600+ lines, doing too much
**Solution**:
- Extract message handling into MessageProcessor
- Extract peer management into PeerManager
- Extract fragment handling into FragmentManager
- Create proper dependency injection
### 2.2 Testing Infrastructure
**Problem**: No unit tests, making refactoring risky
**Solution**:
- Add XCTest target
- Create mock implementations for Bluetooth
- Test encryption service thoroughly
- Add integration tests for message flow
- Aim for 70% code coverage
### 2.3 Documentation
**Problem**: Limited code comments, no architecture docs
**Solution**:
- Add comprehensive header comments
- Document protocol specifications
- Create architecture diagrams
- Add inline documentation for complex logic
## Priority 3: Performance & UX (3-4 weeks)
### 3.1 Message Deduplication
**Problem**: Simple Set-based deduplication can grow unbounded
**Solution**:
- Implement LRU cache for message IDs
- Add time-based expiration
- Consider bloom filters for efficiency
### 3.2 Connection Management
**Problem**: No connection pooling or retry logic
**Solution**:
- Implement connection state machine
- Add exponential backoff for retries
- Pool peripheral connections
- Add connection quality metrics
### 3.3 UI Responsiveness
**Problem**: Heavy operations on main thread
**Solution**:
- Move encryption to background queues
- Add loading states for operations
- Implement message pagination
- Add pull-to-refresh
## Priority 4: Feature Enhancements (4-6 weeks)
### 4.1 Message Persistence (Optional)
**Problem**: All messages ephemeral, no history
**Solution**:
- Add encrypted SQLite storage
- Implement configurable retention
- Add search functionality
- Maintain privacy-first approach
### 4.2 Protocol Improvements
**Problem**: No versioning, hard to upgrade
**Solution**:
- Add protocol version negotiation
- Implement capability discovery
- Plan migration strategy
- Add feature flags
### 4.3 Network Visualization
**Problem**: Users don't understand mesh topology
**Solution**:
- Add network graph view
- Show message routing paths
- Display peer connection quality
- Add statistics dashboard
## Implementation Strategy
### Phase 1: Foundation (Weeks 1-2)
1. Set up testing infrastructure
2. Add thread sanitizer and memory profiler
3. Begin service refactoring
4. Fix critical thread safety issues
### Phase 2: Stability (Weeks 3-4)
1. Complete service refactoring
2. Add comprehensive error handling
3. Implement proper memory management
4. Add initial test coverage
### Phase 3: Quality (Weeks 5-6)
1. Add documentation
2. Improve connection management
3. Optimize performance bottlenecks
4. Enhance UI responsiveness
### Phase 4: Enhancement (Weeks 7-10)
1. Add optional persistence
2. Implement protocol versioning
3. Build network visualization
4. Polish for production
## Success Metrics
- Zero crashes in TestFlight
- 70% test coverage
- Sub-100ms message processing
- < 5% battery drain per hour
- Clean architecture with < 300 lines per class
## Risk Mitigation
- Keep all changes backwards compatible initially
- Add feature flags for risky changes
- Extensive TestFlight testing between phases
- Maintain current security properties
- Regular security audits of changes
-207
View File
@@ -1,207 +0,0 @@
# BitChat Security and Encryption Analysis
## Executive Summary
BitChat is a Bluetooth mesh networking app that implements a mix of encrypted and unencrypted communications. While private messages are properly encrypted using Curve25519 and AES-GCM, public broadcast messages are sent in plaintext with optional signatures. The app has several security strengths but also notable vulnerabilities that could compromise user privacy and security.
## 1. Message Encryption
### 1.1 Encrypted Messages
- **Private Messages**: Properly encrypted using Curve25519 key agreement and AES-GCM
- Uses ephemeral key pairs for forward secrecy
- Implements proper authenticated encryption (AEAD)
- Encrypted payload includes the full message content
### 1.2 Unencrypted Messages
- **Public/Broadcast Messages**: Sent in **PLAINTEXT**
- Message content, sender nickname, timestamps are all visible
- Only protected by optional signatures (not encryption)
- Anyone within Bluetooth range can read these messages
- **Announce Messages**: Sent in plaintext containing nicknames
- **Key Exchange Messages**: Public keys sent in plaintext (this is acceptable)
### 1.3 Partially Protected Data
- **Fragments**: Large messages are fragmented but fragments themselves are not encrypted unless the original message was private
- **Metadata**: TTL, timestamps, sender/recipient IDs are always in plaintext
## 2. Key Management
### 2.1 Key Types
The app uses three types of keys per peer:
1. **Ephemeral Encryption Key** (Curve25519 KeyAgreement) - Changes each session
2. **Ephemeral Signing Key** (Curve25519 Signing) - Changes each session
3. **Persistent Identity Key** (Curve25519 Signing) - Stored in UserDefaults
### 2.2 Key Exchange Process
```
1. On connection, peers exchange 96 bytes containing:
- 32 bytes: Ephemeral encryption public key
- 32 bytes: Ephemeral signing public key
- 32 bytes: Persistent identity public key
2. Shared secrets are derived using HKDF with:
- Salt: "bitchat-v1"
- Info: empty
- Output: 32-byte symmetric key for AES-GCM
```
### 2.3 Key Storage Vulnerabilities
- **Persistent identity keys** stored in UserDefaults (not secure storage)
- No key rotation mechanism for persistent keys
- No key expiration or revocation support
- Ephemeral keys provide forward secrecy but are lost on app restart
## 3. Authentication & Signatures
### 3.1 Message Authentication
- Messages can be signed using ephemeral signing keys
- Signatures use Curve25519 (Ed25519) - cryptographically strong
- **CRITICAL ISSUE**: Signatures are optional, not mandatory
- Broadcast messages often sent without signatures
- No enforcement of signature verification
### 3.2 Identity Verification
- No mechanism to verify persistent identity keys
- Peer IDs are random 8-character hex strings (ephemeral per session)
- Nicknames are self-assigned and not authenticated
- **Impersonation Risk**: Anyone can claim any nickname
### 3.3 Anti-Replay Protection
- Basic timestamp validation (5-minute window)
- Message deduplication based on timestamp + sender ID
- **Weakness**: Deduplication cache cleared after 1000 messages
## 4. Privacy Analysis
### 4.1 Metadata Exposure
The following metadata is **always exposed** in plaintext:
- Message type (broadcast, private, announce, etc.)
- Timestamp (exact time of message)
- TTL (time-to-live) value
- Sender ID (8-character ephemeral ID)
- Recipient ID (for private messages)
- Message exists (traffic analysis possible)
### 4.2 User Tracking
- **Session Tracking**: Ephemeral peer IDs change per session (good)
- **Long-term Tracking**: Persistent identity keys enable tracking favorites across sessions
- **Nickname Tracking**: Self-assigned nicknames can be tracked
- **RSSI Tracking**: Signal strength logged, enabling location tracking
### 4.3 Traffic Analysis Vulnerabilities
- Message sizes not padded (reveals content length)
- Timing patterns not obscured
- Relay behavior reveals network topology
- Fragment reassembly reveals large message senders
## 5. Security Vulnerabilities
### 5.1 MITM (Man-in-the-Middle) Attacks
- **Key Exchange Vulnerable**: No authentication during initial key exchange
- Anyone can intercept and replace public keys
- No certificate pinning or trust verification
- **Mitigation**: Only persistent identity keys provide some continuity
### 5.2 Replay Attack Protection
- **Partial Protection**: 5-minute timestamp window
- **Weakness**: Attacker can replay within window
- **Weakness**: Cache-based deduplication can be overwhelmed
### 5.3 Key Compromise Impact
- **Ephemeral Key Compromise**: Only affects current session
- **Identity Key Compromise**: Affects all future favorite communications
- **No Perfect Forward Secrecy** for identity-based communications
### 5.4 Message Integrity
- **Private Messages**: Protected by AES-GCM authentication tag
- **Public Messages**: Only protected if signed (optional)
- **Fragments**: No integrity protection during reassembly
### 5.5 Denial of Service
- No rate limiting on messages
- Fragment reassembly can consume memory
- Message cache can be filled with spam
- TTL-based flooding possible
## 6. Protocol-Specific Vulnerabilities
### 6.1 Binary Protocol Issues
- No protocol version negotiation
- Fixed-size fields can lead to truncation
- No extension mechanism for future security features
### 6.2 Bluetooth-Specific Risks
- BLE advertisements reveal app usage
- Connection attempts logged by OS
- RSSI measurements enable physical tracking
- No protection against Bluetooth protocol attacks
## 7. Implementation Issues
### 7.1 Cryptographic Issues
- Using SHA256 for fingerprints (should use key-specific hashing)
- No constant-time comparisons for signatures
- Error messages may leak timing information
### 7.2 Memory Safety
- Message cache stores decrypted content
- No secure memory wiping after use
- Crash dumps may contain sensitive data
## 8. Recommendations
### 8.1 Critical Fixes
1. **Encrypt all messages** including broadcasts
2. **Mandatory signatures** on all messages
3. **Authenticated key exchange** (e.g., using SMP or custom protocol)
4. **Secure key storage** using Keychain instead of UserDefaults
### 8.2 Privacy Enhancements
1. **Pad message sizes** to fixed buckets
2. **Add decoy traffic** to obscure patterns
3. **Randomize timing** of message relay
4. **Implement onion routing** for multi-hop messages
### 8.3 Security Improvements
1. **Add perfect forward secrecy** for all messages
2. **Implement key rotation** for long-term keys
3. **Add replay protection** with sequence numbers
4. **Rate limiting** to prevent DoS attacks
### 8.4 Protocol Enhancements
1. **Version negotiation** for protocol upgrades
2. **Capability advertisement** for feature discovery
3. **Extension fields** for future features
4. **Formal security audit** of protocol design
## 9. Threat Model Considerations
### 9.1 Local Adversary (Within Bluetooth Range)
- Can read all broadcast messages
- Can perform traffic analysis
- Can attempt MITM during key exchange
- Can track users via RSSI
### 9.2 Network Adversary (Multiple Nodes)
- Can correlate messages across the mesh
- Can map network topology
- Can perform timing correlation attacks
- Can identify high-value targets (favorites)
### 9.3 Persistent Adversary
- Can track users across sessions via identity keys
- Can build social graphs from message patterns
- Can perform long-term traffic analysis
- Can compromise stored keys from UserDefaults
## 10. Conclusion
BitChat implements basic encryption for private messages but has significant security and privacy vulnerabilities. The lack of encryption for broadcast messages, optional signatures, vulnerable key exchange, and metadata exposure make it unsuitable for high-security scenarios. While the app provides some protection against casual eavesdropping, it would not withstand targeted attacks by motivated adversaries.
For activist or high-risk use cases, the current implementation poses serious risks including:
- Message content exposure (broadcasts)
- User tracking and identification
- Social graph analysis
- Physical location tracking via RSSI
Major architectural changes would be needed to provide adequate security for sensitive communications.