Skip to main content

Types & Internals

Types

ForwardInfo

Forwarding attribution attached to forwarded messages. This is a display-level hint, not a cryptographic proof.
interface ForwardInfo {
  original_sender: string;
  original_message_id: string;
  original_timestamp: number;
  forward_count: number;
}

NetworkTopology

interface NetworkTopology {
  timestamp: number;
  local_user_id: string;
  nodes: NetworkNode[];
  links: NetworkLink[];
  stats: NetworkStats;
}

interface NetworkNode {
  user_id: string;
  role: NodeRole;  // 'normal' | 'relay'
  connection_count: number;
  battery_level?: number;
  last_seen: number;
  transports: TransportType[];
}

interface NetworkLink {
  from: string;
  to: string;
  quality: number;  // 0.0 - 1.0
  transport: TransportType;
  rssi?: number;
}

interface NetworkStats {
  total_nodes: number;
  relay_nodes: number;
  total_connections: number;
  avg_link_quality: number;
  network_diameter?: number;
}

MessageDeliveryStats

interface MessageDeliveryStats {
  message_id: string;
  sender: string;
  recipient: string;
  sent_at: number;
  delivered_at?: number;
  hop_count: number;
  transport?: TransportType;
  retry_count: number;
  latency_ms?: number;
}

RouteEntry

interface RouteEntry {
  nextHop: string;
  hopCount: number;
  quality: number;     // 0.0 - 1.0
  lastSeenMs: number;
}

RoutingStats

interface RoutingStats {
  destinationCount: number;
  routeCount: number;
}

GradientRoutingConfig

interface GradientRoutingConfig {
  maxRoutesPerDestination?: number;
  routeTtlSecs?: number;
  maxRoutingTableSize?: number;
}

DedupStats

interface DedupStats {
  totalTracked: number;
  recentTracked: number;
  capacityUsedPercent: number;
  mode: string;  // 'HashMap' or 'BloomFilter'
}

FileProgress

interface FileProgress {
  file_id: string;
  chunks_sent: number;
  total_chunks: number;
  percentage: number;
}

MLS Types

interface MlsKeyPackage {
  packageId: string;
  userId: string;
  keyPackageData: number[];
  createdAt: number;
  isSynced: boolean;
}

interface MlsEncryptedMessage {
  groupId: string;
  messageType: string;  // 'Application', 'Proposal', 'Commit'
  epoch: number;
  ciphertext: number[];
  senderId: string;
  timestampMs: number;
}

interface MlsWelcome {
  groupId: string;
  welcomeData: number[];
  inviterId: string;
  timestampMs: number;
}

interface MlsSessionInfo {
  otherUserId: string;
  groupId: string;
  epoch: number;
  createdAt: number;
}

interface MlsGroupInfo {
  groupId: string;
  groupName: string;
  memberIds: string[];
  epoch: number;
  createdAt: number;
}

ProtocolState

enum ProtocolState {
  Stopped = 0,
  Running = 1,
  Paused = 2,
}

DORS (Dynamic Offline Relay Switch)

DORS automatically selects the optimal transport based on real-time conditions.

Scoring Factors

FactorDescription
Signal StrengthRSSI for BLE/WiFi (-50 to -100 dBm)
ProximityHop count to destination
BandwidthTransport throughput capability
CongestionQueue depth and backlog
EnergyBattery impact of transport
ReliabilityHistorical delivery success rate
LoadCurrent processing capacity

Transport Weights

BLE: Optimized for energy efficiency and mesh scenarios
  • Signal: 30%, Energy: 30%, Congestion: 15%, Proximity: 15%
WiFi Direct: Optimized for high throughput
  • Bandwidth: 35%, Proximity: 20%, Congestion: 20%, Reliability: 15%
Internet: Optimized for server connectivity
  • Bandwidth: 35%, Reliability: 30%, Congestion: 15%, Energy: 10%

Switching Safeguards

SafeguardDefaultDescription
Hysteresis15 pointsMinimum score improvement to switch
Cooldown20 secondsWait time between switches
Stability Window8 secondsTransport must be stable before switching

Mesh Networking

Cluster Architecture

Devices organize into clusters (groups of nearby connected peers). Connections between clusters are handled by bridge connections. Connection Roles:
  • MEMBER - Intra-cluster connection (devices in same neighborhood)
  • BRIDGE - Inter-cluster connection (bridges different neighborhoods)

How It Works

  1. Discovery: Devices broadcast BLE advertisements with mesh metadata (degree, free slots, battery, uptime)
  2. Cluster Detection: Each device computes a cluster signature from connected peer hashes
  3. Connection Decisions: MeshController evaluates candidates - prioritizes bridging different clusters
  4. Rebalancing: Periodically swaps lower-quality peers for better candidates or bridge opportunities
  5. Delivery: Messages sent to connected peers

Connection Budget

  • Default: 4 connections per device
  • Minimum: 1 connection maintained
  • Connections are scored and rebalanced every ~15 seconds
  • Bridge candidates get priority when clusters need unifying

Peer Scoring

FactorWeightDescription
RSSI35%Signal strength to peer
Availability20%Free connection slots
Uptime15%How long peer has been active
Battery15%Peer’s battery level
Stability10%Connection reliability history
Load5%Current processing load
Bridge Favor: Candidates from different clusters get a score bonus (bridgeFavor: 0.1) to encourage network unification.

Message TTL

  • Default: 8 hops
  • Messages are dropped when TTL reaches 0
  • Prevents infinite message circulation

Reliability Layer

Acknowledgments

  • Messages require ACK for delivery confirmation
  • Default timeout: 5 seconds
  • message_delivered event fires on ACK receipt

Retry Queue

  • Failed messages are retried with exponential backoff
  • Initial delay: 1 second
  • Maximum delay: 30 seconds
  • Maximum retries: 5

Deduplication

Prevents duplicate message processing:
  • Bloom Filter Mode: Space-efficient, ~1% false positive rate
  • HashMap Mode: Exact tracking, configurable capacity

Troubleshooting

Messages Not Delivering

  1. Verify both devices have protocol started
  2. Check they’re within BLE range (~10-30m)
  3. Ensure TTL is sufficient for network size
  4. Monitor message_failed events for retry information
  5. Check getEstablishmentState() if encryption is required

No Peers Discovered

  1. Verify Bluetooth is enabled: await protocol.isBluetoothEnabled()
  2. Check permissions are granted
  3. Ensure background modes enabled (iOS)
  4. Verify devices are within range

Secure Session Not Establishing

  1. Ensure encryption is enabled (default: true)
  2. Check getEstablishmentState(peerId) for current state
  3. Verify hasPendingKeyPackage(peerId) returns true
  4. Check for secure_session_failed events
  5. Try resetTofuForPeer(peerId) if key mismatch is suspected

Frequent Disconnections

  1. Check signal strength via neighbor_discovered RSSI
  2. Increase stabilityWindowSecs in DORS config
  3. Reduce rebalanceInterval frequency
  4. Check for BLE interference

High Battery Drain

  1. Reduce connection count (native mesh config)
  2. Verify DORS is selecting BLE over WiFi Direct
  3. Check for excessive retry activity
  4. Use setBatteryLevel() to inform mesh decisions

Transport Not Switching

  1. Verify transport is enabled in config
  2. Check hysteresis threshold isn’t too high
  3. Ensure cooldown period has elapsed
  4. Use forceTransport() to test manually

Linking Error

If you see the linking error message:
  1. Run pod install (iOS)
  2. Rebuild the app after installing
  3. Verify not using Expo Go (native modules required)