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

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/, 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/ 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/) 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/, 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

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

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/) 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/) enables native macOS/iOS share sheet integration. When users share media from external apps:

  1. 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:

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)
  • 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 for peer management and 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, 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.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →