# What Are the Main Modules in the Bitchat Codebase? A Complete Architecture Guide

> Explore the eight main modules of the Bitchat codebase, covering core app, data, logic, UI, networking, sync, share extensions, and utilities. Understand the complete architecture.

- Repository: [permissionlesstech/bitchat](https://github.com/permissionlesstech/bitchat)
- Tags: architecture
- Published: 2026-08-06

---

**Bitchat organizes its Swift-based macOS/iOS application into eight primary modules spanning the core app, data models, business logic, UI, networking, synchronization, share extensions, and local utility packages.**

Bitchat is a permissionless, peer-to-peer messaging platform built for resilient, censorship-resistant communication. Understanding its **main modules in the Bitchat codebase** reveals how the architecture cleanly separates concerns across cryptography, mesh networking, and SwiftUI presentation layers. This guide walks through each module with concrete source references from the `permissionlesstech/bitchat` repository.

## Core App Module: `bitchat/`

The **`bitchat/`** directory serves as the root application bundle, containing the entry point, resource bundles, and top-level configuration. This module bootstraps the dependency graph and initializes the service layer before any UI appears.

Key responsibilities include app lifecycle management, entitlements configuration, and scene delegate setup for both macOS and iOS targets.

## Data Layer: `bitchat/Models`

The **Models module** defines immutable data structures that flow through the entire system. Located in [`bitchat/Models/`](https://github.com/permissionlesstech/bitchat/blob/main/bitchat/Models), these Swift structs represent:

- `BitchatMessage` — core message envelope with content types (text, media, voice)
- `BitchatPeer` — discovered peer identity with cryptographic public keys
- `ReadReceipt` — delivery acknowledgment metadata
- Cryptographic payloads for the Noise protocol handshake

Models remain pure data containers without business logic, enabling easy serialization for the sync engine and transport layer.

## Business Logic: `bitchat/ViewModels`

The **ViewModels module** in [`bitchat/ViewModels/`](https://github.com/permissionlesstech/bitchat/blob/main/bitchat/ViewModels) contains `ObservableObject` classes that bridge UI and services. Notable implementations include:

- **`ChatViewModel`** — primary coordinator implementing `BitchatDelegate`, managing message composition, media attachment, and navigation state
- **`VoiceRecordingViewModel`** — handles audio capture, encoding, and transcription flows
- **`NostrRelayViewModel`** — manages bridge connections to Nostr protocol relays

ViewModels expose `@Published` properties for SwiftUI binding and invoke service methods on background queues.

## Presentation Layer: `bitchat/Views`

The **Views module** ([`bitchat/Views/`](https://github.com/permissionlesstech/bitchat/blob/main/bitchat/Views)) contains platform-adaptive SwiftUI and AppKit implementations:

- Chat bubbles with markdown rendering and link preview
- Media composers with drag-and-drop support
- Verification screens for cryptographic identity confirmation
- Settings panels for mesh and geohash configuration

Views remain thin, delegating all state mutations to their corresponding view-models.

## Runtime Services: `bitchat/Services`

The **Services module** is the largest functional area in [`bitchat/Services/`](https://github.com/permissionlesstech/bitchat/blob/main/bitchat/Services), encapsulating side-effect-heavy operations:

| Service | Responsibility |
|---------|---------------|
| `UnifiedPeerService` | Central hub for peer discovery, transport wiring, and event delegation |
| `Transport` | Abstract interface for mesh and relay packet transmission |
| `NoiseEncryptionService` | End-to-end encryption via the Noise XX handshake pattern |
| `GeohashPresenceService` | Location-based peer discovery using hierarchical geohash encoding |
| `KeychainService` | Secure storage of private keys and session state |
| `NotificationService` | Local and push notification handling with privacy-preserving content |

Services are typically singletons or injected via environment objects, initialized early in the app lifecycle.

### Example: Sending a Ping via UnifiedPeerService

```swift
import Bitchat

final class ExampleViewModel: ObservableObject {
    @Published var status = ""

    private let peerService = UnifiedPeerService.shared

    func sendPing(to peer: BitchatPeer) {
        peerService.sendPing(to: peer) { result in
            switch result {
            case .success:
                self.status = "Ping sent"
            case .failure(let error):
                self.status = "Error: \(error.localizedDescription)"
            }
        }
    }
}

```

### Example: Starting Geohash Presence Tracking

```swift
import Bitchat

let presence = GeohashPresenceService.shared
presence.startTracking { error in
    if let err = error {
        print("Failed to start: \(err)")
    } else {
        print("Geohash presence tracking active")
    }
}

```

## State Replication: `bitchat/Sync`

The **Sync module** ([`bitchat/Sync/`](https://github.com/permissionlesstech/bitchat/blob/main/bitchat/Sync)) implements eventual consistency across distributed peers through two complementary strategies:

- **`RequestSyncManager`** — pull-based synchronization that queries peers for missing conversation history
- **`GossipSyncManager`** — push-based epidemic broadcast for rapid message dissemination

Both managers leverage `MessageDeduplicationService` to prevent replay attacks and redundant processing. The sync layer operates below view-models, ensuring UI remains responsive during reconciliation.

## System Integration: `bitchatShareExtension`

The **Share Extension module** ([`bitchatShareExtension/`](https://github.com/permissionlesstech/bitchat/blob/main/bitchatShareExtension)) enables native macOS/iOS share sheet integration. When users share media from external apps:

1. [`ShareViewController.swift`](https://github.com/permissionlesstech/bitchat/blob/main/ShareViewController.swift) receives the content
2. `SharedContentHandoff` serializes the payload
3. `SharedContentStore` (keychain-backed) persists data for the main app to consume

This architecture respects the extension's memory constraints while maintaining cryptographic continuity with the host app.

## Reusable Utilities: `localPackages/`

Bitchat extracts foundational code into two Swift packages for cross-target reuse:

- **`BitFoundation`** ([`localPackages/BitFoundation/`](https://github.com/permissionlesstech/bitchat/blob/main/localPackages/BitFoundation)) — cryptographic helpers, data sanitization, and base encoding utilities
- **`BitLogger`** ([`localPackages/BitLogger/`](https://github.com/permissionlesstech/bitchat/blob/main/localPackages/BitLogger)) — structured logging with privacy levels and subsystem tagging

These packages compile independently, enabling unit testing without the full application target.

## Documentation and Tooling

Supporting modules include:

- **`docs/`** — architecture decision records, security assessments, and protocol specifications (start with [`docs/ARCHITECTURE_V2.md`](https://github.com/permissionlesstech/bitchat/blob/main/docs/ARCHITECTURE_V2.md))
- **`scripts/`** — CI pipelines, performance benchmarks, and georelay validation tools

## Module Interaction Flow

The **main modules in the Bitchat codebase** communicate through a unidirectional data flow:

1. **UI → ViewModels**: SwiftUI views bind to `@Published` properties and trigger actions
2. **ViewModels → Services**: Business logic delegates to encryption, transport, and presence services
3. **Services ↔ Models**: Data structures serialize for network transmission and persist via sync managers
4. **Sync Layer**: Ensures consistency without blocking the main thread

This layering keeps cryptographic operations isolated from presentation code and enables comprehensive testing at each boundary.

## Summary

- **Eight primary modules** organize Bitchat: core app (`bitchat/`), Models, ViewModels, Views, Services, Sync, Share Extension, and local utility packages
- **Services module** contains the most complex logic: encryption, mesh transport, geohash presence, and keychain management
- **Sync engine** achieves eventual consistency via request-sync pull and gossip push protocols
- **Share extension** uses keychain-backed handoff for secure cross-process media sharing
- **Local packages** (`BitFoundation`, `BitLogger`) promote code reuse across app targets

## Frequently Asked Questions

### Where is the peer-to-peer networking logic implemented?

The networking stack resides in the **Services module**, specifically [`bitchat/Services/UnifiedPeerService.swift`](https://github.com/permissionlesstech/bitchat/blob/main/bitchat/Services/UnifiedPeerService.swift) for peer management and [`bitchat/Services/Transport.swift`](https://github.com/permissionlesstech/bitchat/blob/main/bitchat/Services/Transport.swift) for packet transmission. The `GeohashPresenceService` adds location-based discovery on top of these foundations.

### How does Bitchat handle message synchronization across devices?

The **Sync module** (`bitchat/Sync/`) implements dual strategies: `RequestSyncManager` pulls missing history on demand, while `GossipSyncManager` pushes new messages epidemically. `MessageDeduplicationService` prevents redundant processing.

### What encryption protocol does Bitchat use?

According to the source in [`bitchat/Services/NoiseEncryptionService.swift`](https://github.com/permissionlesstech/bitchat/blob/main/bitchat/Services/NoiseEncryptionService.swift), Bitchat implements the **Noise XX handshake pattern** for end-to-end encryption, providing forward secrecy and mutual authentication without centralized certificate authorities.

### Can developers contribute to the core modules without affecting the UI?

Yes. The **Models** and **Services** modules have no SwiftUI dependencies, enabling isolated testing and contribution. The **localPackages/** utilities compile independently, and comprehensive unit tests validate behavior without launching the full application.