This commit is contained in:
callebtc
2025-07-08 20:37:46 +02:00
commit d6a4e122b4
43 changed files with 7037 additions and 0 deletions
@@ -0,0 +1,16 @@
package com.bitchat.android
import android.app.Application
/**
* Main application class for bitchat Android
*/
class BitchatApplication : Application() {
override fun onCreate() {
super.onCreate()
// Initialize any global services or configurations
// For now, keep it simple
}
}
@@ -0,0 +1,97 @@
package com.bitchat.android
import android.Manifest
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import com.bitchat.android.ui.ChatScreen
import com.bitchat.android.ui.ChatViewModel
import com.bitchat.android.ui.theme.BitchatTheme
class MainActivity : ComponentActivity() {
private val chatViewModel: ChatViewModel by viewModels()
private val permissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { permissions ->
val allPermissionsGranted = permissions.values.all { it }
if (allPermissionsGranted) {
// Permissions granted, the mesh service should start automatically
} else {
// Handle permission denial
finish()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Request necessary permissions
requestPermissions()
setContent {
BitchatTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
ChatScreen(viewModel = chatViewModel)
}
}
}
}
private fun requestPermissions() {
val permissions = mutableListOf<String>()
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
permissions.addAll(listOf(
Manifest.permission.BLUETOOTH_ADVERTISE,
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_SCAN
))
} else {
permissions.addAll(listOf(
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN
))
}
permissions.addAll(listOf(
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
))
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
permissions.add(Manifest.permission.POST_NOTIFICATIONS)
}
permissionLauncher.launch(permissions.toTypedArray())
}
override fun onDestroy() {
super.onDestroy()
// FIXED: Ensure Bluetooth resources are cleaned up when the activity is destroyed
// This addresses the issue where stale Bluetooth advertisements interfere with
// restart discovery times. This is more reliable than relying solely on
// ChatViewModel.onCleared() which may not be called when the app is swiped away.
try {
chatViewModel.meshService.stopServices()
} catch (e: Exception) {
// Log error, but don't crash the app on exit
android.util.Log.w("MainActivity", "Error stopping mesh services in onDestroy: ${e.message}")
}
}
}
@@ -0,0 +1,321 @@
package com.bitchat.android.crypto
import android.content.Context
import android.content.SharedPreferences
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import org.bouncycastle.crypto.agreement.X25519Agreement
import org.bouncycastle.crypto.generators.Ed25519KeyPairGenerator
import org.bouncycastle.crypto.generators.X25519KeyPairGenerator
import org.bouncycastle.crypto.params.*
import org.bouncycastle.crypto.signers.Ed25519Signer
import org.bouncycastle.crypto.util.PrivateKeyFactory
import org.bouncycastle.crypto.util.PublicKeyFactory
import org.bouncycastle.jcajce.provider.digest.SHA256
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
/**
* Encryption service that's 100% compatible with iOS version
* Uses the same cryptographic algorithms and key derivation
*/
class EncryptionService(private val context: Context) {
// Key agreement keys for encryption
private val privateKey: X25519PrivateKeyParameters
private val publicKey: X25519PublicKeyParameters
// Signing keys for authentication
private val signingPrivateKey: Ed25519PrivateKeyParameters
private val signingPublicKey: Ed25519PublicKeyParameters
// Persistent identity for favorites (separate from ephemeral keys)
private lateinit var identityKey: Ed25519PrivateKeyParameters
private lateinit var identityPublicKey: Ed25519PublicKeyParameters
// Storage for peer keys
private val peerPublicKeys = mutableMapOf<String, X25519PublicKeyParameters>()
private val peerSigningKeys = mutableMapOf<String, Ed25519PublicKeyParameters>()
private val peerIdentityKeys = mutableMapOf<String, Ed25519PublicKeyParameters>()
private val sharedSecrets = mutableMapOf<String, ByteArray>()
private val prefs: SharedPreferences = context.getSharedPreferences("bitchat_crypto", Context.MODE_PRIVATE)
private val secureRandom = SecureRandom()
init {
// Generate ephemeral key pairs for this session
val x25519Generator = X25519KeyPairGenerator()
x25519Generator.init(X25519KeyGenerationParameters(secureRandom))
val x25519KeyPair = x25519Generator.generateKeyPair()
privateKey = x25519KeyPair.private as X25519PrivateKeyParameters
publicKey = x25519KeyPair.public as X25519PublicKeyParameters
val ed25519Generator = Ed25519KeyPairGenerator()
ed25519Generator.init(Ed25519KeyGenerationParameters(secureRandom))
val ed25519KeyPair = ed25519Generator.generateKeyPair()
signingPrivateKey = ed25519KeyPair.private as Ed25519PrivateKeyParameters
signingPublicKey = ed25519KeyPair.public as Ed25519PublicKeyParameters
// Load or create persistent identity key
val identityKeyBytes = prefs.getString("identity_key", null)
if (identityKeyBytes != null) {
try {
val keyBytes = android.util.Base64.decode(identityKeyBytes, android.util.Base64.DEFAULT)
identityKey = Ed25519PrivateKeyParameters(keyBytes, 0)
} catch (e: Exception) {
// Create new identity key if loading fails
val newIdentityKeyPair = ed25519Generator.generateKeyPair()
identityKey = newIdentityKeyPair.private as Ed25519PrivateKeyParameters
saveIdentityKey()
}
} else {
// First run - create and save identity key
val newIdentityKeyPair = ed25519Generator.generateKeyPair()
identityKey = newIdentityKeyPair.private as Ed25519PrivateKeyParameters
saveIdentityKey()
}
identityPublicKey = Ed25519PublicKeyParameters(identityKey.encoded, 0)
}
private fun saveIdentityKey() {
val keyBytes = android.util.Base64.encodeToString(identityKey.encoded, android.util.Base64.DEFAULT)
prefs.edit().putString("identity_key", keyBytes).apply()
}
/**
* Create combined public key data for exchange - exactly same format as iOS
* 96 bytes total: 32 (X25519) + 32 (Ed25519 signing) + 32 (Ed25519 identity)
*/
fun getCombinedPublicKeyData(): ByteArray {
val combined = ByteArray(96)
System.arraycopy(publicKey.encoded, 0, combined, 0, 32) // X25519 key
System.arraycopy(signingPublicKey.encoded, 0, combined, 32, 32) // Ed25519 signing key
System.arraycopy(identityPublicKey.encoded, 0, combined, 64, 32) // Ed25519 identity key
return combined
}
/**
* Add peer's combined public keys - exactly same logic as iOS
*/
@Throws(Exception::class)
fun addPeerPublicKey(peerID: String, publicKeyData: ByteArray) {
if (publicKeyData.size != 96) {
throw Exception("Invalid public key data size: ${publicKeyData.size}, expected 96")
}
// Extract all three keys: 32 for key agreement + 32 for signing + 32 for identity
val keyAgreementData = publicKeyData.sliceArray(0..31)
val signingKeyData = publicKeyData.sliceArray(32..63)
val identityKeyData = publicKeyData.sliceArray(64..95)
val peerPublicKey = X25519PublicKeyParameters(keyAgreementData, 0)
peerPublicKeys[peerID] = peerPublicKey
val peerSigningKey = Ed25519PublicKeyParameters(signingKeyData, 0)
peerSigningKeys[peerID] = peerSigningKey
val peerIdentityKey = Ed25519PublicKeyParameters(identityKeyData, 0)
peerIdentityKeys[peerID] = peerIdentityKey
// Generate shared secret for encryption using X25519
val agreement = X25519Agreement()
agreement.init(privateKey)
val sharedSecret = ByteArray(32)
agreement.calculateAgreement(peerPublicKey, sharedSecret, 0)
// Derive symmetric key using HKDF with same salt as iOS
val salt = "bitchat-v1".toByteArray()
val derivedKey = hkdf(sharedSecret, salt, byteArrayOf(), 32)
sharedSecrets[peerID] = derivedKey
}
/**
* Get peer's persistent identity key for favorites
*/
fun getPeerIdentityKey(peerID: String): ByteArray? {
return peerIdentityKeys[peerID]?.encoded
}
/**
* Clear persistent identity (for panic mode)
*/
fun clearPersistentIdentity() {
prefs.edit().remove("identity_key").apply()
}
/**
* Encrypt data for a specific peer using AES-256-GCM
*/
@Throws(Exception::class)
fun encrypt(data: ByteArray, peerID: String): ByteArray {
val symmetricKey = sharedSecrets[peerID]
?: throw Exception("No shared secret for peer $peerID")
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
val keySpec = SecretKeySpec(symmetricKey, "AES")
cipher.init(Cipher.ENCRYPT_MODE, keySpec)
val iv = cipher.iv
val ciphertext = cipher.doFinal(data)
// Combine IV and ciphertext (same format as iOS AES.GCM.SealedBox.combined)
val combined = ByteArray(iv.size + ciphertext.size)
System.arraycopy(iv, 0, combined, 0, iv.size)
System.arraycopy(ciphertext, 0, combined, iv.size, ciphertext.size)
return combined
}
/**
* Decrypt data from a specific peer
*/
@Throws(Exception::class)
fun decrypt(data: ByteArray, peerID: String): ByteArray {
val symmetricKey = sharedSecrets[peerID]
?: throw Exception("No shared secret for peer $peerID")
if (data.size < 16) { // 12 bytes IV + 16 bytes tag minimum for GCM
throw Exception("Invalid encrypted data size")
}
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
val keySpec = SecretKeySpec(symmetricKey, "AES")
// Extract IV and ciphertext
val iv = data.sliceArray(0..11) // GCM IV is 12 bytes
val ciphertext = data.sliceArray(12 until data.size)
val gcmSpec = GCMParameterSpec(128, iv) // 128-bit authentication tag
cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmSpec)
return cipher.doFinal(ciphertext)
}
/**
* Sign data using Ed25519
*/
@Throws(Exception::class)
fun sign(data: ByteArray): ByteArray {
val signer = Ed25519Signer()
signer.init(true, signingPrivateKey)
signer.update(data, 0, data.size)
return signer.generateSignature()
}
/**
* Verify signature using Ed25519
*/
@Throws(Exception::class)
fun verify(signature: ByteArray, data: ByteArray, peerID: String): Boolean {
val verifyingKey = peerSigningKeys[peerID]
?: throw Exception("No signing key for peer $peerID")
val signer = Ed25519Signer()
signer.init(false, verifyingKey)
signer.update(data, 0, data.size)
return signer.verifySignature(signature)
}
/**
* HKDF implementation using SHA256 - same as iOS HKDF
*/
private fun hkdf(ikm: ByteArray, salt: ByteArray, info: ByteArray, length: Int): ByteArray {
// Extract
val hmac = javax.crypto.Mac.getInstance("HmacSHA256")
val saltKey = SecretKeySpec(if (salt.isEmpty()) ByteArray(32) else salt, "HmacSHA256")
hmac.init(saltKey)
val prk = hmac.doFinal(ikm)
// Expand
hmac.init(SecretKeySpec(prk, "HmacSHA256"))
val result = ByteArray(length)
var offset = 0
var counter = 1
while (offset < length) {
hmac.reset()
if (counter > 1) {
hmac.update(result, offset - 32, 32)
}
hmac.update(info)
hmac.update(counter.toByte())
val t = hmac.doFinal()
val remaining = length - offset
val toCopy = minOf(t.size, remaining)
System.arraycopy(t, 0, result, offset, toCopy)
offset += toCopy
counter++
}
return result
}
}
/**
* Message padding utilities - exact same as iOS version
*/
object MessagePadding {
// Standard block sizes for padding
private val blockSizes = listOf(256, 512, 1024, 2048)
/**
* Add PKCS#7-style padding to reach target size
*/
fun pad(data: ByteArray, targetSize: Int): ByteArray {
if (data.size >= targetSize) return data
val paddingNeeded = targetSize - data.size
// PKCS#7 only supports padding up to 255 bytes
if (paddingNeeded > 255) return data
val padded = ByteArray(targetSize)
System.arraycopy(data, 0, padded, 0, data.size)
// Fill with random bytes except the last byte
val random = SecureRandom()
random.nextBytes(padded.sliceArray(data.size until targetSize - 1))
// Last byte indicates padding length (PKCS#7)
padded[targetSize - 1] = paddingNeeded.toByte()
return padded
}
/**
* Remove padding from data
*/
fun unpad(data: ByteArray): ByteArray {
if (data.isEmpty()) return data
// Last byte tells us how much padding to remove
val paddingLength = (data.last() and 0xFF.toByte()).toInt()
if (paddingLength <= 0 || paddingLength > data.size) return data
return data.sliceArray(0 until (data.size - paddingLength))
}
/**
* Find optimal block size for data
*/
fun optimalBlockSize(dataSize: Int): Int {
// Account for encryption overhead (~16 bytes for AES-GCM tag)
val totalSize = dataSize + 16
// Find smallest block that fits
for (blockSize in blockSizes) {
if (totalSize <= blockSize) {
return blockSize
}
}
// For very large messages, just use the original size
return dataSize
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,407 @@
package com.bitchat.android.model
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.*
/**
* Delivery status for messages - exact same as iOS version
*/
sealed class DeliveryStatus : Parcelable {
@Parcelize
object Sending : DeliveryStatus()
@Parcelize
object Sent : DeliveryStatus()
@Parcelize
data class Delivered(val to: String, val at: Date) : DeliveryStatus()
@Parcelize
data class Read(val by: String, val at: Date) : DeliveryStatus()
@Parcelize
data class Failed(val reason: String) : DeliveryStatus()
@Parcelize
data class PartiallyDelivered(val reached: Int, val total: Int) : DeliveryStatus()
fun getDisplayText(): String {
return when (this) {
is Sending -> "Sending..."
is Sent -> "Sent"
is Delivered -> "Delivered to ${this.to}"
is Read -> "Read by ${this.by}"
is Failed -> "Failed: ${this.reason}"
is PartiallyDelivered -> "Delivered to ${this.reached}/${this.total}"
}
}
}
/**
* BitchatMessage - 100% compatible with iOS version
*/
@Parcelize
data class BitchatMessage(
val id: String = UUID.randomUUID().toString(),
val sender: String,
val content: String,
val timestamp: Date,
val isRelay: Boolean = false,
val originalSender: String? = null,
val isPrivate: Boolean = false,
val recipientNickname: String? = null,
val senderPeerID: String? = null,
val mentions: List<String>? = null,
val channel: String? = null,
val encryptedContent: ByteArray? = null,
val isEncrypted: Boolean = false,
val deliveryStatus: DeliveryStatus? = null
) : Parcelable {
/**
* Convert message to binary payload format - exactly same as iOS version
*/
fun toBinaryPayload(): ByteArray? {
try {
val buffer = ByteBuffer.allocate(4096).apply { order(ByteOrder.BIG_ENDIAN) }
// Message format:
// - Flags: 1 byte (bit flags for optional fields)
// - Timestamp: 8 bytes (milliseconds since epoch, big-endian)
// - ID length: 1 byte + ID data
// - Sender length: 1 byte + sender data
// - Content length: 2 bytes + content data (or encrypted content)
// Optional fields based on flags...
var flags: UByte = 0u
if (isRelay) flags = flags or 0x01u
if (isPrivate) flags = flags or 0x02u
if (originalSender != null) flags = flags or 0x04u
if (recipientNickname != null) flags = flags or 0x08u
if (senderPeerID != null) flags = flags or 0x10u
if (mentions != null && mentions.isNotEmpty()) flags = flags or 0x20u
if (channel != null) flags = flags or 0x40u
if (isEncrypted) flags = flags or 0x80u
buffer.put(flags.toByte())
// Timestamp (in milliseconds, 8 bytes big-endian)
val timestampMillis = timestamp.time
buffer.putLong(timestampMillis)
// ID
val idBytes = id.toByteArray(Charsets.UTF_8)
buffer.put(minOf(idBytes.size, 255).toByte())
buffer.put(idBytes.take(255).toByteArray())
// Sender
val senderBytes = sender.toByteArray(Charsets.UTF_8)
buffer.put(minOf(senderBytes.size, 255).toByte())
buffer.put(senderBytes.take(255).toByteArray())
// Content or encrypted content
if (isEncrypted && encryptedContent != null) {
val length = minOf(encryptedContent.size, 65535)
buffer.putShort(length.toShort())
buffer.put(encryptedContent.take(length).toByteArray())
} else {
val contentBytes = content.toByteArray(Charsets.UTF_8)
val length = minOf(contentBytes.size, 65535)
buffer.putShort(length.toShort())
buffer.put(contentBytes.take(length).toByteArray())
}
// Optional fields
originalSender?.let { origSender ->
val origBytes = origSender.toByteArray(Charsets.UTF_8)
buffer.put(minOf(origBytes.size, 255).toByte())
buffer.put(origBytes.take(255).toByteArray())
}
recipientNickname?.let { recipient ->
val recipBytes = recipient.toByteArray(Charsets.UTF_8)
buffer.put(minOf(recipBytes.size, 255).toByte())
buffer.put(recipBytes.take(255).toByteArray())
}
senderPeerID?.let { peerID ->
val peerBytes = peerID.toByteArray(Charsets.UTF_8)
buffer.put(minOf(peerBytes.size, 255).toByte())
buffer.put(peerBytes.take(255).toByteArray())
}
// Mentions array
mentions?.let { mentionList ->
buffer.put(minOf(mentionList.size, 255).toByte())
mentionList.take(255).forEach { mention ->
val mentionBytes = mention.toByteArray(Charsets.UTF_8)
buffer.put(minOf(mentionBytes.size, 255).toByte())
buffer.put(mentionBytes.take(255).toByteArray())
}
}
// Channel hashtag
channel?.let { channelName ->
val channelBytes = channelName.toByteArray(Charsets.UTF_8)
buffer.put(minOf(channelBytes.size, 255).toByte())
buffer.put(channelBytes.take(255).toByteArray())
}
val result = ByteArray(buffer.position())
buffer.rewind()
buffer.get(result)
return result
} catch (e: Exception) {
return null
}
}
companion object {
/**
* Parse message from binary payload - exactly same logic as iOS version
*/
fun fromBinaryPayload(data: ByteArray): BitchatMessage? {
try {
if (data.size < 13) return null
val buffer = ByteBuffer.wrap(data).apply { order(ByteOrder.BIG_ENDIAN) }
// Flags
val flags = buffer.get().toUByte()
val isRelay = (flags and 0x01u) != 0u.toUByte()
val isPrivate = (flags and 0x02u) != 0u.toUByte()
val hasOriginalSender = (flags and 0x04u) != 0u.toUByte()
val hasRecipientNickname = (flags and 0x08u) != 0u.toUByte()
val hasSenderPeerID = (flags and 0x10u) != 0u.toUByte()
val hasMentions = (flags and 0x20u) != 0u.toUByte()
val hasChannel = (flags and 0x40u) != 0u.toUByte()
val isEncrypted = (flags and 0x80u) != 0u.toUByte()
// Timestamp
val timestampMillis = buffer.getLong()
val timestamp = Date(timestampMillis)
// ID
val idLength = buffer.get().toInt() and 0xFF
if (buffer.remaining() < idLength) return null
val idBytes = ByteArray(idLength)
buffer.get(idBytes)
val id = String(idBytes, Charsets.UTF_8)
// Sender
val senderLength = buffer.get().toInt() and 0xFF
if (buffer.remaining() < senderLength) return null
val senderBytes = ByteArray(senderLength)
buffer.get(senderBytes)
val sender = String(senderBytes, Charsets.UTF_8)
// Content
val contentLength = buffer.getShort().toInt() and 0xFFFF
if (buffer.remaining() < contentLength) return null
val content: String
val encryptedContent: ByteArray?
if (isEncrypted) {
val encryptedBytes = ByteArray(contentLength)
buffer.get(encryptedBytes)
encryptedContent = encryptedBytes
content = "" // Empty placeholder
} else {
val contentBytes = ByteArray(contentLength)
buffer.get(contentBytes)
content = String(contentBytes, Charsets.UTF_8)
encryptedContent = null
}
// Optional fields
val originalSender = if (hasOriginalSender && buffer.hasRemaining()) {
val length = buffer.get().toInt() and 0xFF
if (buffer.remaining() >= length) {
val bytes = ByteArray(length)
buffer.get(bytes)
String(bytes, Charsets.UTF_8)
} else null
} else null
val recipientNickname = if (hasRecipientNickname && buffer.hasRemaining()) {
val length = buffer.get().toInt() and 0xFF
if (buffer.remaining() >= length) {
val bytes = ByteArray(length)
buffer.get(bytes)
String(bytes, Charsets.UTF_8)
} else null
} else null
val senderPeerID = if (hasSenderPeerID && buffer.hasRemaining()) {
val length = buffer.get().toInt() and 0xFF
if (buffer.remaining() >= length) {
val bytes = ByteArray(length)
buffer.get(bytes)
String(bytes, Charsets.UTF_8)
} else null
} else null
// Mentions array
val mentions = if (hasMentions && buffer.hasRemaining()) {
val mentionCount = buffer.get().toInt() and 0xFF
val mentionList = mutableListOf<String>()
repeat(mentionCount) {
if (buffer.hasRemaining()) {
val length = buffer.get().toInt() and 0xFF
if (buffer.remaining() >= length) {
val bytes = ByteArray(length)
buffer.get(bytes)
mentionList.add(String(bytes, Charsets.UTF_8))
}
}
}
if (mentionList.isNotEmpty()) mentionList else null
} else null
// Channel
val channel = if (hasChannel && buffer.hasRemaining()) {
val length = buffer.get().toInt() and 0xFF
if (buffer.remaining() >= length) {
val bytes = ByteArray(length)
buffer.get(bytes)
String(bytes, Charsets.UTF_8)
} else null
} else null
return BitchatMessage(
id = id,
sender = sender,
content = content,
timestamp = timestamp,
isRelay = isRelay,
originalSender = originalSender,
isPrivate = isPrivate,
recipientNickname = recipientNickname,
senderPeerID = senderPeerID,
mentions = mentions,
channel = channel,
encryptedContent = encryptedContent,
isEncrypted = isEncrypted
)
} catch (e: Exception) {
return null
}
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as BitchatMessage
if (id != other.id) return false
if (sender != other.sender) return false
if (content != other.content) return false
if (timestamp != other.timestamp) return false
if (isRelay != other.isRelay) return false
if (originalSender != other.originalSender) return false
if (isPrivate != other.isPrivate) return false
if (recipientNickname != other.recipientNickname) return false
if (senderPeerID != other.senderPeerID) return false
if (mentions != other.mentions) return false
if (channel != other.channel) return false
if (encryptedContent != null) {
if (other.encryptedContent == null) return false
if (!encryptedContent.contentEquals(other.encryptedContent)) return false
} else if (other.encryptedContent != null) return false
if (isEncrypted != other.isEncrypted) return false
if (deliveryStatus != other.deliveryStatus) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + sender.hashCode()
result = 31 * result + content.hashCode()
result = 31 * result + timestamp.hashCode()
result = 31 * result + isRelay.hashCode()
result = 31 * result + (originalSender?.hashCode() ?: 0)
result = 31 * result + isPrivate.hashCode()
result = 31 * result + (recipientNickname?.hashCode() ?: 0)
result = 31 * result + (senderPeerID?.hashCode() ?: 0)
result = 31 * result + (mentions?.hashCode() ?: 0)
result = 31 * result + (channel?.hashCode() ?: 0)
result = 31 * result + (encryptedContent?.contentHashCode() ?: 0)
result = 31 * result + isEncrypted.hashCode()
result = 31 * result + (deliveryStatus?.hashCode() ?: 0)
return result
}
}
/**
* Delivery acknowledgment structure - exact same as iOS version
*/
@Parcelize
data class DeliveryAck(
val originalMessageID: String,
val ackID: String = UUID.randomUUID().toString(),
val recipientID: String,
val recipientNickname: String,
val timestamp: Date = Date(),
val hopCount: UByte
) : Parcelable {
fun encode(): ByteArray? {
return try {
com.google.gson.Gson().toJson(this).toByteArray(Charsets.UTF_8)
} catch (e: Exception) {
null
}
}
companion object {
fun decode(data: ByteArray): DeliveryAck? {
return try {
val json = String(data, Charsets.UTF_8)
com.google.gson.Gson().fromJson(json, DeliveryAck::class.java)
} catch (e: Exception) {
null
}
}
}
}
/**
* Read receipt structure - exact same as iOS version
*/
@Parcelize
data class ReadReceipt(
val originalMessageID: String,
val receiptID: String = UUID.randomUUID().toString(),
val readerID: String,
val readerNickname: String,
val timestamp: Date = Date()
) : Parcelable {
fun encode(): ByteArray? {
return try {
com.google.gson.Gson().toJson(this).toByteArray(Charsets.UTF_8)
} catch (e: Exception) {
null
}
}
companion object {
fun decode(data: ByteArray): ReadReceipt? {
return try {
val json = String(data, Charsets.UTF_8)
com.google.gson.Gson().fromJson(json, ReadReceipt::class.java)
} catch (e: Exception) {
null
}
}
}
}
@@ -0,0 +1,334 @@
package com.bitchat.android.protocol
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.*
/**
* Message types - exact same as iOS version
*/
enum class MessageType(val value: UByte) {
ANNOUNCE(0x01u),
KEY_EXCHANGE(0x02u),
LEAVE(0x03u),
MESSAGE(0x04u),
FRAGMENT_START(0x05u),
FRAGMENT_CONTINUE(0x06u),
FRAGMENT_END(0x07u),
CHANNEL_ANNOUNCE(0x08u),
CHANNEL_RETENTION(0x09u),
DELIVERY_ACK(0x0Au),
DELIVERY_STATUS_REQUEST(0x0Bu),
READ_RECEIPT(0x0Cu);
companion object {
fun fromValue(value: UByte): MessageType? {
return values().find { it.value == value }
}
}
}
/**
* Special recipient IDs - exact same as iOS version
*/
object SpecialRecipients {
val BROADCAST = ByteArray(8) { 0xFF.toByte() } // All 0xFF = broadcast
}
/**
* Binary packet format - 100% compatible with iOS version
*
* Header (Fixed 13 bytes):
* - Version: 1 byte
* - Type: 1 byte
* - TTL: 1 byte
* - Timestamp: 8 bytes (UInt64, big-endian)
* - Flags: 1 byte (bit 0: hasRecipient, bit 1: hasSignature, bit 2: isCompressed)
* - PayloadLength: 2 bytes (UInt16, big-endian)
*
* Variable sections:
* - SenderID: 8 bytes (fixed)
* - RecipientID: 8 bytes (if hasRecipient flag set)
* - Payload: Variable length (includes original size if compressed)
* - Signature: 64 bytes (if hasSignature flag set)
*/
@Parcelize
data class BitchatPacket(
val version: UByte = 1u,
val type: UByte,
val senderID: ByteArray,
val recipientID: ByteArray? = null,
val timestamp: ULong,
val payload: ByteArray,
val signature: ByteArray? = null,
var ttl: UByte
) : Parcelable {
constructor(
type: UByte,
ttl: UByte,
senderID: String,
payload: ByteArray
) : this(
version = 1u,
type = type,
senderID = senderID.toByteArray(),
recipientID = null,
timestamp = (System.currentTimeMillis()).toULong(),
payload = payload,
signature = null,
ttl = ttl
)
fun toBinaryData(): ByteArray? {
return BinaryProtocol.encode(this)
}
companion object {
fun fromBinaryData(data: ByteArray): BitchatPacket? {
return BinaryProtocol.decode(data)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as BitchatPacket
if (version != other.version) return false
if (type != other.type) return false
if (!senderID.contentEquals(other.senderID)) return false
if (recipientID != null) {
if (other.recipientID == null) return false
if (!recipientID.contentEquals(other.recipientID)) return false
} else if (other.recipientID != null) return false
if (timestamp != other.timestamp) return false
if (!payload.contentEquals(other.payload)) return false
if (signature != null) {
if (other.signature == null) return false
if (!signature.contentEquals(other.signature)) return false
} else if (other.signature != null) return false
if (ttl != other.ttl) return false
return true
}
override fun hashCode(): Int {
var result = version.hashCode()
result = 31 * result + type.hashCode()
result = 31 * result + senderID.contentHashCode()
result = 31 * result + (recipientID?.contentHashCode() ?: 0)
result = 31 * result + timestamp.hashCode()
result = 31 * result + payload.contentHashCode()
result = 31 * result + (signature?.contentHashCode() ?: 0)
result = 31 * result + ttl.hashCode()
return result
}
}
/**
* Binary Protocol implementation - exact same format as iOS version
*/
object BinaryProtocol {
private const val HEADER_SIZE = 13
private const val SENDER_ID_SIZE = 8
private const val RECIPIENT_ID_SIZE = 8
private const val SIGNATURE_SIZE = 64
object Flags {
const val HAS_RECIPIENT: UByte = 0x01u
const val HAS_SIGNATURE: UByte = 0x02u
const val IS_COMPRESSED: UByte = 0x04u
}
fun encode(packet: BitchatPacket): ByteArray? {
try {
// Try to compress payload if beneficial
var payload = packet.payload
var originalPayloadSize: UShort? = null
var isCompressed = false
if (CompressionUtil.shouldCompress(payload)) {
CompressionUtil.compress(payload)?.let { compressedPayload ->
originalPayloadSize = payload.size.toUShort()
payload = compressedPayload
isCompressed = true
}
}
val buffer = ByteBuffer.allocate(4096).apply { order(ByteOrder.BIG_ENDIAN) }
// Header
buffer.put(packet.version.toByte())
buffer.put(packet.type.toByte())
buffer.put(packet.ttl.toByte())
// Timestamp (8 bytes, big-endian)
buffer.putLong(packet.timestamp.toLong())
// Flags
var flags: UByte = 0u
if (packet.recipientID != null) {
flags = flags or Flags.HAS_RECIPIENT
}
if (packet.signature != null) {
flags = flags or Flags.HAS_SIGNATURE
}
if (isCompressed) {
flags = flags or Flags.IS_COMPRESSED
}
buffer.put(flags.toByte())
// Payload length (2 bytes, big-endian) - includes original size if compressed
val payloadDataSize = payload.size + if (isCompressed) 2 else 0
buffer.putShort(payloadDataSize.toShort())
// SenderID (exactly 8 bytes)
val senderBytes = packet.senderID.take(SENDER_ID_SIZE).toByteArray()
buffer.put(senderBytes)
if (senderBytes.size < SENDER_ID_SIZE) {
buffer.put(ByteArray(SENDER_ID_SIZE - senderBytes.size))
}
// RecipientID (if present)
packet.recipientID?.let { recipientID ->
val recipientBytes = recipientID.take(RECIPIENT_ID_SIZE).toByteArray()
buffer.put(recipientBytes)
if (recipientBytes.size < RECIPIENT_ID_SIZE) {
buffer.put(ByteArray(RECIPIENT_ID_SIZE - recipientBytes.size))
}
}
// Payload (with original size prepended if compressed)
if (isCompressed) {
val originalSize = originalPayloadSize
if (originalSize != null) {
buffer.putShort(originalSize.toShort())
}
}
buffer.put(payload)
// Signature (if present)
packet.signature?.let { signature ->
buffer.put(signature.take(SIGNATURE_SIZE).toByteArray())
}
val result = ByteArray(buffer.position())
buffer.rewind()
buffer.get(result)
return result
} catch (e: Exception) {
return null
}
}
fun decode(data: ByteArray): BitchatPacket? {
try {
if (data.size < HEADER_SIZE + SENDER_ID_SIZE) return null
val buffer = ByteBuffer.wrap(data).apply { order(ByteOrder.BIG_ENDIAN) }
// Header
val version = buffer.get().toUByte()
if (version != 1u.toUByte()) return null
val type = buffer.get().toUByte()
val ttl = buffer.get().toUByte()
// Timestamp
val timestamp = buffer.getLong().toULong()
// Flags
val flags = buffer.get().toUByte()
val hasRecipient = (flags and Flags.HAS_RECIPIENT) != 0u.toUByte()
val hasSignature = (flags and Flags.HAS_SIGNATURE) != 0u.toUByte()
val isCompressed = (flags and Flags.IS_COMPRESSED) != 0u.toUByte()
// Payload length
val payloadLength = buffer.getShort().toUShort()
// Calculate expected total size
var expectedSize = HEADER_SIZE + SENDER_ID_SIZE + payloadLength.toInt()
if (hasRecipient) expectedSize += RECIPIENT_ID_SIZE
if (hasSignature) expectedSize += SIGNATURE_SIZE
if (data.size < expectedSize) return null
// SenderID
val senderID = ByteArray(SENDER_ID_SIZE)
buffer.get(senderID)
// RecipientID
val recipientID = if (hasRecipient) {
val recipientBytes = ByteArray(RECIPIENT_ID_SIZE)
buffer.get(recipientBytes)
recipientBytes
} else null
// Payload
val payload = if (isCompressed) {
// First 2 bytes are original size
if (payloadLength.toInt() < 2) return null
val originalSize = buffer.getShort().toInt()
// Compressed payload
val compressedPayload = ByteArray(payloadLength.toInt() - 2)
buffer.get(compressedPayload)
// Decompress
CompressionUtil.decompress(compressedPayload, originalSize) ?: return null
} else {
val payloadBytes = ByteArray(payloadLength.toInt())
buffer.get(payloadBytes)
payloadBytes
}
// Signature
val signature = if (hasSignature) {
val signatureBytes = ByteArray(SIGNATURE_SIZE)
buffer.get(signatureBytes)
signatureBytes
} else null
return BitchatPacket(
version = version,
type = type,
senderID = senderID,
recipientID = recipientID,
timestamp = timestamp,
payload = payload,
signature = signature,
ttl = ttl
)
} catch (e: Exception) {
return null
}
}
}
/**
* Compression utilities - temporarily disabled for initial build
*/
object CompressionUtil {
private const val COMPRESSION_THRESHOLD = 100 // bytes
fun shouldCompress(data: ByteArray): Boolean {
// Temporarily disabled compression
return false
}
fun compress(data: ByteArray): ByteArray? {
// Temporarily disabled compression
return null
}
fun decompress(compressedData: ByteArray, originalSize: Int): ByteArray? {
// Temporarily disabled compression
return null
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,52 @@
package com.bitchat.android.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
// Colors that match the iOS bitchat theme
private val DarkColorScheme = darkColorScheme(
primary = Color(0xFF00FF00), // Bright green (terminal-like)
onPrimary = Color.Black,
secondary = Color(0xFF00CC00), // Darker green
onSecondary = Color.Black,
background = Color.Black,
onBackground = Color(0xFF00FF00), // Green on black
surface = Color(0xFF111111), // Very dark gray
onSurface = Color(0xFF00FF00), // Green text
error = Color(0xFFFF5555), // Red for errors
onError = Color.Black
)
private val LightColorScheme = lightColorScheme(
primary = Color(0xFF008000), // Dark green
onPrimary = Color.White,
secondary = Color(0xFF006600), // Even darker green
onSecondary = Color.White,
background = Color.White,
onBackground = Color(0xFF008000), // Dark green on white
surface = Color(0xFFF8F8F8), // Very light gray
onSurface = Color(0xFF008000), // Dark green text
error = Color(0xFFCC0000), // Dark red for errors
onError = Color.White
)
@Composable
fun BitchatTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colorScheme = when {
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
@@ -0,0 +1,53 @@
package com.bitchat.android.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Typography matching the iOS monospace design - increased font sizes for better readability
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 22.sp
),
bodyMedium = TextStyle(
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
lineHeight = 18.sp
),
bodySmall = TextStyle(
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.Normal,
fontSize = 12.sp,
lineHeight = 16.sp
),
headlineSmall = TextStyle(
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.Medium,
fontSize = 18.sp,
lineHeight = 24.sp
),
titleMedium = TextStyle(
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.Medium,
fontSize = 16.sp,
lineHeight = 22.sp
),
labelMedium = TextStyle(
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.Medium,
fontSize = 13.sp,
lineHeight = 18.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.Normal,
fontSize = 11.sp,
lineHeight = 16.sp
)
)