Modern Apps git

← Modern-Apps.git

messages: various fixes

Commit
6db1673bfc781f38e90cbbd8893b6707e079dd08
Author
Vayun Mathur <[email protected]>
When
2026-06-11 00:49 UTC (5 months ago)
Parents
07a208f

Diff

messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt b/messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.ktindex b046d053c5..8634e0005e 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt@@ -245,7 +245,8 @@ object SignalClient {     ): Boolean {         if (_state.value !is State.Connected) return false         return try {-            val pointer = AttachmentManager.upload(bytes, mime, fileName) ?: return false+            val ws = webSocket ?: return false+            val pointer = AttachmentManager.upload(ws, bytes, mime, fileName) ?: return false             val sender = messageSender ?: return false             val recipientAci = resolveRecipient(extractAci(conversationId) ?: return false) ?: return false             val timestamp = System.currentTimeMillis()@@ -381,12 +382,18 @@ object SignalClient {              val devManager = DeviceManager(ws, sessStore, idStore, pkStore, pkStore, pkStore, skStore)             val recipientStore = SignalRecipientStore(database)-            val sender = MessageSender(ws, sessStore, idStore, pkStore, pkStore, pkStore, skStore, auth.aci, auth.deviceId, devManager, recipientStore, unauthedWs)+            val groupStore = SignalGroupStore(database)+            val aciKeyPair = try { IdentityKeyPair(Base64.decode(auth.aciIdentityKeyPair, Base64.NO_WRAP)) } catch (_: Exception) { null }+            val pniKeyPair = try { IdentityKeyPair(Base64.decode(auth.pniIdentityKeyPair, Base64.NO_WRAP)) } catch (_: Exception) { null }+            val acctRecord = try {+                auth.accountRecord?.let { com.vayunmathur.messages.signal.proto.AccountRecord.parseFrom(it) }+            } catch (_: Exception) { null }+            val sender = MessageSender(ws, sessStore, idStore, pkStore, pkStore, pkStore, skStore, auth.aci, auth.deviceId, devManager, recipientStore, unauthedWs, groupStore, auth.pni, aciKeyPair, pniKeyPair, acctRecord)             messageSender = sender             contactManager = ContactManager(recipientStore)             contactDiscovery = ContactDiscovery(recipientStore, auth.aci, auth.deviceId, auth.password, appContext)             profileManager = ProfileManager(unauthedWs, recipientStore)-            groupManager = GroupManager(ws, SignalGroupStore(database), auth.aci, auth.pni, auth.password)+            groupManager = GroupManager(ws, groupStore, recipientStore, auth.aci, auth.pni, auth.password)              ws.incomingRequestHandler = { request ->                 handleIncomingRequest(request, auth, sessStore, idStore, pkStore, skStore)
messages/src/main/java/com/vayunmathur/messages/signal/auth/PreKeyManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/auth/PreKeyManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/auth/PreKeyManager.ktindex 5f175b8021..30312f9b54 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/auth/PreKeyManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/auth/PreKeyManager.kt@@ -128,7 +128,7 @@ object PreKeyManager {                 windowStartMinutes = 36 * 60                 windowSizeMinutes = 24 * 60             } catch (e: IOException) {-                if (e.message?.contains("422") == true) {+                if (e.message?.contains("PNI prekey upload rejected (422)") == true) {                     Log.e(TAG, "Got 422 on PNI prekey upload, session invalid")                     throw e                 }@@ -158,31 +158,53 @@ object PreKeyManager {         identity: String,         identityKeyPair: IdentityKeyPair,     ) {-        val random = SecureRandom()-        val preKeyBase = random.nextInt(Int.MAX_VALUE - BATCH_SIZE)-        val pqKeyBase = random.nextInt(Int.MAX_VALUE - BATCH_SIZE)+        val (ecStoreCount, nextPreKeyId) = preKeyStore.getNextPreKeyId()+        val (kyberStoreCount, nextKyberPreKeyId) = preKeyStore.getNextKyberPreKeyId() -        val preKeys = JSONArray().apply {-            for (i in 0 until BATCH_SIZE) {+        val preKeys = JSONArray()++        val existingPreKeys = preKeyStore.getAllPreKeys()+        for (record in existingPreKeys) {+            preKeys.put(JSONObject().apply {+                put("keyId", record.id)+                put("publicKey", Base64.encodeToString(record.keyPair.publicKey.serialize(), Base64.NO_WRAP))+            })+        }++        if (ecStoreCount < BATCH_SIZE) {+            val ecToGenerate = BATCH_SIZE - ecStoreCount+            for (i in 0 until ecToGenerate) {                 val kp = ECKeyPair.generate()-                val id = preKeyBase + i+                val id = nextPreKeyId + i                 val record = PreKeyRecord(id, kp)                 preKeyStore.storePreKey(id, record)-                put(JSONObject().apply {+                preKeys.put(JSONObject().apply {                     put("keyId", id)                     put("publicKey", Base64.encodeToString(kp.publicKey.serialize(), Base64.NO_WRAP))                 })             }         } -        val pqPreKeys = JSONArray().apply {-            for (i in 0 until BATCH_SIZE) {+        val pqPreKeys = JSONArray()++        val existingKyberKeys = preKeyStore.getAllNormalKyberPreKeys()+        for (record in existingKyberKeys) {+            pqPreKeys.put(JSONObject().apply {+                put("keyId", record.id)+                put("publicKey", Base64.encodeToString(record.keyPair.publicKey.serialize(), Base64.NO_WRAP))+                put("signature", Base64.encodeToString(record.signature, Base64.NO_WRAP))+            })+        }++        if (kyberStoreCount < BATCH_SIZE) {+            val kyberToGenerate = BATCH_SIZE - kyberStoreCount+            for (i in 0 until kyberToGenerate) {                 val kemKp = KEMKeyPair.generate(KEMKeyType.KYBER_1024)                 val sig = identityKeyPair.privateKey.calculateSignature(kemKp.publicKey.serialize())-                val id = pqKeyBase + i+                val id = nextKyberPreKeyId + i                 val record = KyberPreKeyRecord(id, System.currentTimeMillis(), kemKp, sig)                 preKeyStore.storeKyberPreKey(id, record)-                put(JSONObject().apply {+                pqPreKeys.put(JSONObject().apply {                     put("keyId", id)                     put("publicKey", Base64.encodeToString(kemKp.publicKey.serialize(), Base64.NO_WRAP))                     put("signature", Base64.encodeToString(sig, Base64.NO_WRAP))
messages/src/main/java/com/vayunmathur/messages/signal/auth/Provisioning.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/auth/Provisioning.kt b/messages/src/main/java/com/vayunmathur/messages/signal/auth/Provisioning.ktindex 2760e74061..3056a2eb27 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/auth/Provisioning.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/auth/Provisioning.kt@@ -117,6 +117,7 @@ object Provisioning {             val pniPqLastResort = generateKyberPreKey(1, pniIdentityKeyPair)              // Store generated keys in the local protocol stores+            // Use different IDs for ACI vs PNI to avoid overwrites (Go uses separate stores)             val database = SignalDatabase.getInstance(context)             database.sessionDao().deleteAllSessions()             database.preKeyDao().deleteAll()@@ -124,9 +125,9 @@ object Provisioning {             database.kyberPreKeyDao().deleteAll()             val preKeyStore = SignalPreKeyStore(database)             preKeyStore.storeSignedPreKey(aciSignedPreKey.id, aciSignedPreKey)-            preKeyStore.storeSignedPreKey(pniSignedPreKey.id, pniSignedPreKey)+            preKeyStore.storeSignedPreKey(pniSignedPreKey.id + 1000000, pniSignedPreKey)             preKeyStore.storeLastResortKyberPreKey(aciPqLastResort.id, aciPqLastResort)-            preKeyStore.storeLastResortKyberPreKey(pniPqLastResort.id, pniPqLastResort)+            preKeyStore.storeLastResortKyberPreKey(pniPqLastResort.id + 1000000, pniPqLastResort)              // Step 8: Encrypt device name             val encryptedName = encryptDeviceName(deviceName, aciIdentityKeyPair.publicKey.publicKey)
messages/src/main/java/com/vayunmathur/messages/signal/contacts/ContactManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ContactManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ContactManager.ktindex 0b898321eb..4b2b1670a8 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ContactManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ContactManager.kt@@ -8,6 +8,7 @@ import com.vayunmathur.messages.signal.store.SignalRecipientStore import com.vayunmathur.messages.util.ContactSuggestion import java.nio.ByteBuffer import java.security.MessageDigest+import java.util.UUID  class ContactManager(     private val recipientStore: SignalRecipientStore,@@ -17,7 +18,10 @@ class ContactManager(         contactDetails: SignalServiceProtos.ContactDetails,         avatar: ByteArray? = null,     ) {-        val aci = contactDetails.aci.takeIf { it.isNotBlank() } ?: return+        val aci = parseStringOrBinaryAci(+            contactDetails.aci,+            if (contactDetails.hasAciBinary()) contactDetails.aciBinary.toByteArray() else null,+        ) ?: return         val existing = recipientStore.getRecipient(aci)         val e164 = contactDetails.number.takeIf { it.isNotBlank() } ?: existing?.e164         val contactName = contactDetails.name@@ -104,6 +108,16 @@ class ContactManager(     companion object {         private const val TAG = "ContactManager" +        fun parseStringOrBinaryAci(str: String?, bytes: ByteArray?): String? {+            if (!str.isNullOrBlank()) return str+            if (bytes != null && bytes.size == 16) {+                val buf = ByteBuffer.wrap(bytes)+                val uuid = UUID(buf.long, buf.long)+                return uuid.toString()+            }+            return null+        }+         fun unmarshalContactDetailsMessages(             byteStream: ByteArray,         ): Pair<List<SignalServiceProtos.ContactDetails>, List<ByteArray?>> {
messages/src/main/java/com/vayunmathur/messages/signal/contacts/ProfileManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ProfileManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ProfileManager.ktindex 9a6ff96de6..f3405edb35 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ProfileManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ProfileManager.kt@@ -17,6 +17,7 @@ class ProfileInternalErrorException(status: Int) : Exception("profile get return class ProfileManager(     private val ws: SignalWebSocket,     private val recipientStore: SignalRecipientStore,+    private val unauthedWs: SignalWebSocket? = null, ) {     data class Profile(         val name: String?,@@ -81,7 +82,9 @@ class ProfileManager(                 path += "?credentialType=expiringProfileKey"             } -            val response = ws.sendRequest("GET", path,+            val useUnidentified = profileKeyHex != null && headers.containsKey("Unidentified-Access-Key")+            val profileWs = if (useUnidentified && unauthedWs != null) unauthedWs else ws+            val response = profileWs.sendRequest("GET", path,                 headers = headers)              val status = response.status@@ -90,7 +93,6 @@ class ProfileManager(                 return null             }             if (status == 404) {-                cacheError(aci, ProfileNotFoundException())                 throw ProfileNotFoundException()             }             if (status in 500..599) {
messages/src/main/java/com/vayunmathur/messages/signal/contacts/StorageServiceManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/contacts/StorageServiceManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/contacts/StorageServiceManager.ktindex ddf1e780bf..d16f92ddee 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/contacts/StorageServiceManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/contacts/StorageServiceManager.kt@@ -22,6 +22,7 @@ class StorageServiceManager(     private val recipientStore: SignalRecipientStore,     private val groupStore: SignalGroupStore,     private val ws: com.vayunmathur.messages.signal.web.SignalWebSocket,+    private val onAccountRecord: (suspend (com.vayunmathur.messages.signal.proto.AccountRecord) -> Unit)? = null, ) {     companion object {         private const val TAG = "StorageService"@@ -117,7 +118,14 @@ class StorageServiceManager(             try {                 if (r.hasContact()) processContact(r.contact)                 else if (r.hasGroupV2()) processGroup(r.groupV2)-                else if (r.hasAccount()) Log.d(TAG, "Found account record")+                else if (r.hasAccount()) {+                    Log.d(TAG, "Found account record, saving")+                    try {+                        onAccountRecord?.invoke(r.account)+                    } catch (e: Exception) {+                        Log.e(TAG, "Failed to save account record", e)+                    }+                }             } catch (e: Exception) {                 Log.w(TAG, "Failed to process record", e)             }@@ -125,8 +133,14 @@ class StorageServiceManager(     }      private suspend fun processContact(c: ContactRecord) {-        val aci = c.aci.takeIf { it.isNotBlank() }-        val pni = c.pni.takeIf { it.isNotBlank() }+        val aci = ContactManager.parseStringOrBinaryAci(+            c.aci.takeIf { it.isNotBlank() },+            c.aciBinary?.takeIf { !it.isEmpty }?.toByteArray(),+        )+        val pni = ContactManager.parseStringOrBinaryAci(+            c.pni.takeIf { it.isNotBlank() },+            c.pniBinary?.takeIf { !it.isEmpty }?.toByteArray(),+        )         if (aci == null && pni == null) {             Log.w(TAG, "Storage service has contact record with no ACI or PNI")             return
messages/src/main/java/com/vayunmathur/messages/signal/groups/GroupManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/groups/GroupManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/groups/GroupManager.ktindex 756a5b7ea2..94c8afd83a 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/groups/GroupManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/groups/GroupManager.kt@@ -4,8 +4,10 @@ import android.util.Base64 import android.util.Log import com.vayunmathur.messages.signal.proto.Group import com.vayunmathur.messages.signal.proto.GroupAttributeBlob+import com.vayunmathur.messages.signal.proto.GroupResponse import com.vayunmathur.messages.signal.store.SignalGroupEntity import com.vayunmathur.messages.signal.store.SignalGroupStore+import com.vayunmathur.messages.signal.store.SignalRecipientStore import com.vayunmathur.messages.signal.web.SignalHttpClient import com.vayunmathur.messages.signal.web.SignalWebSocket import java.nio.ByteBuffer@@ -23,10 +25,11 @@ import org.signal.libsignal.protocol.ServiceId class GroupManager(     private val ws: SignalWebSocket,     private val groupStore: SignalGroupStore,+    private val recipientStore: SignalRecipientStore,     private val aci: String,     private val pni: String,     private val password: String,-) {+)     enum class AccessControl(val value: Int) {         UNKNOWN(0), ANY(1), MEMBER(2), ADMINISTRATOR(3), UNSATISFIABLE(4)     }@@ -195,25 +198,89 @@ class GroupManager(             )             if (response.code != 200) return null -            val groupProto = Group.parseFrom(response.body?.bytes())+            val groupResponse = GroupResponse.parseFrom(response.body?.bytes())+            val groupProto = groupResponse.group++            val groupMasterKey = GroupMasterKey(masterKey)+            val groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey)+             val members = groupProto.membersList.map { member ->-                val bb = ByteBuffer.wrap(member.userId.toByteArray())+                val decryptedServiceId = groupSecretParams.decryptServiceId(member.userId.toByteArray())+                val decryptedProfileKey = groupSecretParams.decryptProfileKey(member.profileKey.toByteArray(), decryptedServiceId)+                val bb = ByteBuffer.wrap(decryptedServiceId.toByteArray())                 GroupMember(                     aci = UUID(bb.getLong(), bb.getLong()),                     role = MemberRole.entries.find { it.value == member.role.number } ?: MemberRole.UNKNOWN,-                    profileKey = member.profileKey.toByteArray(),+                    profileKey = decryptedProfileKey.serialize(),                     joinedAtRevision = member.joinedAtVersion,                 )             }++            val titleBlob = GroupAttributeBlob.parseFrom(+                groupSecretParams.decryptBlobWithPadding(groupProto.title.toByteArray())+            )+            val decryptedTitle = cleanupStringProperty(titleBlob.title)++            val decryptedDescription = runCatching {+                val descBlob = GroupAttributeBlob.parseFrom(+                    groupSecretParams.decryptBlobWithPadding(groupProto.description.toByteArray())+                )+                cleanupStringProperty(descBlob.description)+            }.getOrNull()++            val disappearingMessagesDuration = if (groupProto.disappearingMessagesTimer != null && !groupProto.disappearingMessagesTimer.isEmpty) {+                val timerBlob = GroupAttributeBlob.parseFrom(+                    groupSecretParams.decryptBlobWithPadding(groupProto.disappearingMessagesTimer.toByteArray())+                )+                timerBlob.disappearingMessagesDuration+            } else 0++            val pendingMembers = groupProto.membersPendingProfileKeyList.mapNotNull { pendingMember ->+                runCatching {+                    val memberProto = pendingMember.member ?: return@runCatching null+                    val decryptedServiceId = groupSecretParams.decryptServiceId(memberProto.userId.toByteArray())+                    val addedByServiceId = groupSecretParams.decryptServiceId(pendingMember.addedByUserId.toByteArray())+                    val addedByBb = ByteBuffer.wrap(addedByServiceId.toByteArray())+                    PendingMember(+                        serviceId = decryptedServiceId.toString(),+                        role = MemberRole.entries.find { it.value == memberProto.role.number } ?: MemberRole.UNKNOWN,+                        addedByUserId = UUID(addedByBb.getLong(), addedByBb.getLong()),+                        timestamp = pendingMember.timestamp,+                    )+                }.getOrNull()+            }++            val requestingMembers = groupProto.membersPendingAdminApprovalList.mapNotNull { reqMember ->+                runCatching {+                    val decryptedServiceId = groupSecretParams.decryptServiceId(reqMember.userId.toByteArray())+                    val decryptedProfileKey = groupSecretParams.decryptProfileKey(reqMember.profileKey.toByteArray(), decryptedServiceId)+                    val bb = ByteBuffer.wrap(decryptedServiceId.toByteArray())+                    RequestingMember(+                        aci = UUID(bb.getLong(), bb.getLong()),+                        profileKey = decryptedProfileKey.serialize(),+                        timestamp = reqMember.timestamp,+                    )+                }.getOrNull()+            }++            val bannedMembers = groupProto.membersBannedList.mapNotNull { banned ->+                runCatching {+                    val decryptedServiceId = groupSecretParams.decryptServiceId(banned.userId.toByteArray())+                    BannedMember(+                        serviceId = decryptedServiceId.toString(),+                        timestamp = banned.timestamp,+                    )+                }.getOrNull()+            }+             val group = SignalGroup(                 groupId = groupId,-                title = cleanupStringProperty(groupProto.title.toStringUtf8()),+                title = decryptedTitle,                 members = members,                 avatarPath = groupProto.avatarUrl.ifEmpty { null },                 revision = groupProto.version,-                description = runCatching {-                    cleanupStringProperty(groupProto.description.toStringUtf8())-                }.getOrNull(),+                description = decryptedDescription,+                disappearingMessagesDuration = disappearingMessagesDuration.toInt(),                 announcementsOnly = groupProto.announcementsOnly,                 accessControl = groupProto.accessControl?.let {                     GroupAccessControl(@@ -222,11 +289,21 @@ class GroupManager(                         attributes = AccessControl.entries.find { ac -> ac.value == it.attributes.number } ?: AccessControl.UNKNOWN,                     )                 },+                pendingMembers = pendingMembers,+                requestingMembers = requestingMembers,+                bannedMembers = bannedMembers,                 inviteLinkPassword = groupProto.inviteLinkPassword?.let {                     if (it.isEmpty) null else Base64.encodeToString(it.toByteArray(), Base64.NO_WRAP)                 },             ) +            for (member in group.members) {+                recipientStore.storeProfileKey(member.aci.toString(), member.profileKey)+            }+            for (reqMember in group.requestingMembers) {+                recipientStore.storeProfileKey(reqMember.aci.toString(), reqMember.profileKey)+            }+             cache[groupId] = group             groupStore.storeGroup(                 SignalGroupEntity(@@ -288,6 +365,8 @@ class GroupManager(                 host = SignalHttpClient.CDN1_HOST,                 method = "GET",                 path = avatarPath,+                username = aci,+                password = password,             )             if (response.code !in 200..299) return null             val encryptedAvatar = response.body?.bytes() ?: return null
messages/src/main/java/com/vayunmathur/messages/signal/groups/SenderKeyManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/groups/SenderKeyManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/groups/SenderKeyManager.ktindex dba64fadab..d910368194 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/groups/SenderKeyManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/groups/SenderKeyManager.kt@@ -1,15 +1,15 @@ package com.vayunmathur.messages.signal.groups  import android.util.Log+import com.vayunmathur.messages.signal.store.SignalSenderKeyStore import org.signal.libsignal.protocol.SignalProtocolAddress import org.signal.libsignal.protocol.groups.GroupCipher import org.signal.libsignal.protocol.groups.GroupSessionBuilder import org.signal.libsignal.protocol.message.SenderKeyDistributionMessage-import org.signal.libsignal.protocol.groups.state.SenderKeyStore import java.util.UUID  class SenderKeyManager(-    private val senderKeyStore: SenderKeyStore,+    private val senderKeyStore: SignalSenderKeyStore,     private val selfAci: String,     private val selfDeviceId: Int, ) {@@ -18,7 +18,8 @@ class SenderKeyManager(         private const val SENDER_KEY_MAX_AGE_MS = 14L * 24 * 60 * 60 * 1000 // 14 days     } -    private val distributedTo = mutableMapOf<String, MutableSet<String>>()+    // groupId -> (aci -> list of device IDs)+    private val distributedTo = mutableMapOf<String, MutableMap<String, List<Int>>>()     private val distributionIds = mutableMapOf<String, UUID>()     private val distributionCreatedAt = mutableMapOf<String, Long>() @@ -37,16 +38,28 @@ class SenderKeyManager(         return builder.create(selfAddress, distributionId)     } -    fun needsDistribution(groupId: String, memberAci: String): Boolean {+    fun needsDistribution(groupId: String, memberAci: String, deviceIds: List<Int>? = null): Boolean {         val distributed = distributedTo[groupId] ?: return true-        return memberAci !in distributed+        val knownDevices = distributed[memberAci] ?: return true+        if (deviceIds != null) {+            return !knownDevices.containsAll(deviceIds)+        }+        return false     } -    fun markDistributed(groupId: String, memberAci: String) {-        distributedTo.getOrPut(groupId) { mutableSetOf() }.add(memberAci)+    fun markDistributed(groupId: String, memberAci: String, deviceIds: List<Int>) {+        distributedTo.getOrPut(groupId) { mutableMapOf() }[memberAci] = deviceIds     }      fun resetForGroup(groupId: String) {+        val distributionId = distributionIds[groupId]+        if (distributionId != null) {+            val selfAddress = SignalProtocolAddress(selfAci, selfDeviceId)+            senderKeyStore.deleteSenderKey(selfAddress, distributionId)+            kotlinx.coroutines.runBlocking {+                senderKeyStore.deleteSenderKeyInfo(groupId)+            }+        }         distributedTo.remove(groupId)         distributionIds.remove(groupId)         distributionCreatedAt.remove(groupId)
messages/src/main/java/com/vayunmathur/messages/signal/media/AttachmentManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/media/AttachmentManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/media/AttachmentManager.ktindex 732ebc2230..b6e92d53e3 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/media/AttachmentManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/media/AttachmentManager.kt@@ -39,10 +39,13 @@ object AttachmentManager {                 path = path,             )             if (response.code == 404) throw AttachmentNotFoundException()-            if (response.code !in 200..299) return null+            if (response.code > 400) return null             val body = response.body?.bytes() ?: return null -            if (digest != null && !plaintextDigest) {+            if (!plaintextDigest) {+                if (digest == null) {+                    throw InvalidDigestException("Missing digest for attachment")+                }                 val hash = MessageDigest.getInstance("SHA-256").digest(body)                 if (!MessageDigest.isEqual(hash, digest)) {                     throw InvalidDigestException()@@ -61,6 +64,12 @@ object AttachmentManager {                 }             }             result+        } catch (e: InvalidMACException) {+            Log.e(TAG, "MAC validation failed for attachment", e)+            throw e+        } catch (e: InvalidDigestException) {+            Log.e(TAG, "Digest validation failed for attachment", e)+            throw e         } catch (e: Exception) {             Log.e(TAG, "Failed to download attachment", e)             null
messages/src/main/java/com/vayunmathur/messages/signal/media/BackupManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/media/BackupManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/media/BackupManager.ktindex 25f9545b2f..f41ce441ab 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/media/BackupManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/media/BackupManager.kt@@ -1,6 +1,14 @@ package com.vayunmathur.messages.signal.media  import android.util.Log+import com.google.protobuf.CodedInputStream+import com.vayunmathur.messages.signal.proto.backup.Backup.BackupInfo+import com.vayunmathur.messages.signal.proto.backup.Backup.ChatItem+import com.vayunmathur.messages.signal.proto.backup.Backup.Frame+import com.vayunmathur.messages.signal.store.SignalBackupChatEntity+import com.vayunmathur.messages.signal.store.SignalBackupChatItemEntity+import com.vayunmathur.messages.signal.store.SignalBackupRecipientEntity+import com.vayunmathur.messages.signal.store.SignalDatabase import com.vayunmathur.messages.signal.web.SignalHttpClient import com.vayunmathur.messages.signal.web.SignalWebSocket import org.json.JSONObject@@ -16,6 +24,7 @@ import javax.crypto.spec.SecretKeySpec class BackupManager(     private val ws: SignalWebSocket,     private val selfAci: String,+    private val db: SignalDatabase, ) {     companion object {         private const val TAG = "BackupManager"@@ -157,7 +166,95 @@ class BackupManager(         return baos.toByteArray()     } -    private fun processBackupFrames(data: ByteArray) {+    private suspend fun processBackupFrames(data: ByteArray) {         Log.d(TAG, "Processing ${data.size} bytes of backup data")+        val input = CodedInputStream.newInstance(data)+        var seenInfo = false+        val recipientDao = db.backupRecipientDao()+        val chatDao = db.backupChatDao()+        val chatItemDao = db.backupChatItemDao()++        // Clear existing backup data before importing+        chatItemDao.deleteAll()+        chatDao.deleteAll()+        recipientDao.deleteAll()++        while (!input.isAtEnd) {+            val length = input.readRawVarint32()+            if (length == 0) continue+            val limit = input.pushLimit(length)+            val chunk = input.readRawBytes(length)+            input.popLimit(limit)++            if (!seenInfo) {+                val info = BackupInfo.parseFrom(chunk)+                if (info.version != BACKUP_VERSION.toLong()) {+                    throw Exception("Unsupported backup version: ${info.version}")+                }+                Log.i(TAG, "Backup info: version=${info.version}")+                seenInfo = true+                continue+            }++            val frame = Frame.parseFrom(chunk)+            processFrame(frame, recipientDao, chatDao, chatItemDao)+        }+        Log.d(TAG, "Finished processing backup frames")+    }++    private suspend fun processFrame(+        frame: Frame,+        recipientDao: com.vayunmathur.messages.signal.store.SignalBackupRecipientDao,+        chatDao: com.vayunmathur.messages.signal.store.SignalBackupChatDao,+        chatItemDao: com.vayunmathur.messages.signal.store.SignalBackupChatItemDao,+    ) {+        when (frame.itemCase) {+            Frame.ItemCase.RECIPIENT -> {+                val recipient = frame.recipient+                if (recipient.destinationCase == com.vayunmathur.messages.signal.proto.backup.Backup.Recipient.DestinationCase.DESTINATION_NOT_SET) {+                    Log.d(TAG, "Ignoring recipient frame with no destination")+                    return+                }+                recipientDao.insert(+                    SignalBackupRecipientEntity(+                        id = recipient.id,+                        data = recipient.toByteArray(),+                    )+                )+            }+            Frame.ItemCase.CHAT -> {+                val chat = frame.chat+                chatDao.insert(+                    SignalBackupChatEntity(+                        id = chat.id,+                        recipientId = chat.recipientId,+                        data = chat.toByteArray(),+                    )+                )+            }+            Frame.ItemCase.CHATITEM -> {+                val chatItem = frame.chatItem+                when (chatItem.itemCase) {+                    ChatItem.ItemCase.DIRECTSTORYREPLYMESSAGE,+                    ChatItem.ItemCase.UPDATEMESSAGE,+                    ChatItem.ItemCase.ITEM_NOT_SET -> {+                        Log.d(TAG, "Not saving unsupported chat item type: ${chatItem.itemCase}")+                        return+                    }+                    else -> {}+                }+                chatItemDao.insert(+                    SignalBackupChatItemEntity(+                        chatId = chatItem.chatId,+                        authorId = chatItem.authorId,+                        messageId = chatItem.dateSent,+                        data = chatItem.toByteArray(),+                    )+                )+            }+            else -> {+                Log.d(TAG, "Ignoring backup frame: ${frame.itemCase}")+            }+        }     } }
messages/src/main/java/com/vayunmathur/messages/signal/receiving/EnvelopeDecryptor.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/receiving/EnvelopeDecryptor.kt b/messages/src/main/java/com/vayunmathur/messages/signal/receiving/EnvelopeDecryptor.ktindex 7057c5354f..c9b9c665a7 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/receiving/EnvelopeDecryptor.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/receiving/EnvelopeDecryptor.kt@@ -1,10 +1,13 @@ package com.vayunmathur.messages.signal.receiving +import android.util.Base64 import android.util.Log import com.vayunmathur.messages.signal.proto.SignalServiceProtos import com.vayunmathur.messages.signal.store.SignalProtocolStoreImpl import org.signal.libsignal.protocol.SignalProtocolAddress import org.signal.libsignal.protocol.SessionCipher+import org.signal.libsignal.protocol.ecc.Curve+import org.signal.libsignal.protocol.message.CiphertextMessage import org.signal.libsignal.protocol.message.SignalMessage import org.signal.libsignal.protocol.message.PreKeySignalMessage import org.signal.libsignal.protocol.state.IdentityKeyStore@@ -20,6 +23,10 @@ import java.util.UUID object EnvelopeDecryptor {      private const val TAG = "SignalReceiver"+    private const val CONTENT_HINT_RESENDABLE = 1+    private val SIGNAL_SERVER_TRUST_ROOT = Base64.decode(+        "BXu4Sr3OzuDoeeFab3yc3LaWGPsyVDKzp12qlMQDa2B1hQ==", Base64.DEFAULT+    )      data class DecryptionResult(         val senderAci: String,@@ -34,6 +41,8 @@ object EnvelopeDecryptor {         val unencrypted: Boolean = false,         val contentHint: Int = 0,         val groupId: ByteArray? = null,+        val ciphertext: ByteArray? = null,+        val ciphertextType: Int = 0,     )      fun decrypt(@@ -52,6 +61,12 @@ object EnvelopeDecryptor {         val senderDeviceId = envelope.sourceDeviceId         val timestamp = envelope.clientTimestamp         val serverTimestamp = envelope.serverTimestamp+        val destinationServiceId = envelope.destinationServiceId ?: ""++        if (destinationServiceId.isEmpty()) {+            return DecryptionResult(senderAci, senderDeviceId, null, timestamp, serverTimestamp,+                error = IllegalArgumentException("Envelope missing destination service ID"))+        }          val protocolStore = SignalProtocolStoreImpl(             sessionStore, identityKeyStore, preKeyStore, signedPreKeyStore, kyberPreKeyStore, senderKeyStore@@ -68,7 +83,9 @@ object EnvelopeDecryptor {                         DecryptionResult(senderAci, senderDeviceId, content, timestamp, serverTimestamp)                     } catch (e: Exception) {                         DecryptionResult(senderAci, senderDeviceId, null, timestamp, serverTimestamp,-                            error = e, retriable = true)+                            error = e, retriable = true,+                            ciphertext = envelope.content.toByteArray(),+                            ciphertextType = CiphertextMessage.WHISPER_TYPE)                     }                 } @@ -81,16 +98,24 @@ object EnvelopeDecryptor {                         DecryptionResult(senderAci, senderDeviceId, content, timestamp, serverTimestamp)                     } catch (e: Exception) {                         DecryptionResult(senderAci, senderDeviceId, null, timestamp, serverTimestamp,-                            error = e, retriable = true)+                            error = e, retriable = true,+                            ciphertext = envelope.content.toByteArray(),+                            ciphertextType = CiphertextMessage.PREKEY_TYPE)                     }                 }                  SignalServiceProtos.Envelope.Type.UNIDENTIFIED_SENDER -> {+                    if (destinationServiceId != selfAci) {+                        Log.w(TAG, "Received UNIDENTIFIED_SENDER envelope for non-ACI destination: $destinationServiceId")+                        return DecryptionResult(senderAci, senderDeviceId, null, timestamp, serverTimestamp,+                            error = IllegalArgumentException("Received unidentified sender envelope for non-ACI destination"))+                    }                     val sealedCipher = SealedSessionCipher(                         protocolStore, UUID.fromString(selfAci), selfAci, selfDeviceId                     )+                    val trustRoot = Curve.decodePoint(SIGNAL_SERVER_TRUST_ROOT, 0)                     val validator = certificateValidator-                        ?: CertificateValidator(emptyList())+                        ?: CertificateValidator(listOf(trustRoot))                     val result = sealedCipher.decrypt(validator, envelope.content.toByteArray(), serverTimestamp)                     val content = SignalServiceProtos.Content.parseFrom(stripPadding(result.paddedMessage))                     DecryptionResult(@@ -128,7 +153,25 @@ object EnvelopeDecryptor {             }         } catch (e: Exception) {             Log.e(TAG, "Decryption error for type ${envelope.type}", e)-            DecryptionResult(senderAci, senderDeviceId, null, timestamp, serverTimestamp, error = e)+            val resolvedSender = senderAci+            val resolvedDeviceId = senderDeviceId+            if (envelope.type == SignalServiceProtos.Envelope.Type.UNIDENTIFIED_SENDER) {+                try {+                    val header = org.signal.libsignal.metadata.SealedSessionCipher.parseMessageHeader(+                        envelope.content.toByteArray()+                    )+                    return DecryptionResult(+                        senderAci = header?.senderUuid ?: resolvedSender,+                        senderDeviceId = header?.deviceId ?: resolvedDeviceId,+                        content = null, timestamp = timestamp, serverTimestamp = serverTimestamp,+                        error = e,+                        retriable = (header?.contentHint ?: 0) == CONTENT_HINT_RESENDABLE,+                        ciphertext = envelope.content.toByteArray(),+                        ciphertextType = CiphertextMessage.SENDERKEY_TYPE,+                    )+                } catch (_: Exception) { }+            }+            DecryptionResult(resolvedSender, resolvedDeviceId, null, timestamp, serverTimestamp, error = e)         }     } 
messages/src/main/java/com/vayunmathur/messages/signal/receiving/MessageReceiver.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/receiving/MessageReceiver.kt b/messages/src/main/java/com/vayunmathur/messages/signal/receiving/MessageReceiver.ktindex b2f0224626..bf3842f0b1 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/receiving/MessageReceiver.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/receiving/MessageReceiver.kt@@ -12,8 +12,12 @@ import org.signal.libsignal.protocol.state.KyberPreKeyStore import org.signal.libsignal.protocol.groups.state.SenderKeyStore import org.signal.libsignal.protocol.groups.GroupSessionBuilder import org.signal.libsignal.protocol.message.SenderKeyDistributionMessage+import org.signal.libsignal.protocol.message.DecryptionErrorMessage+import org.signal.libsignal.protocol.message.CiphertextMessage import kotlinx.coroutines.runBlocking import org.signal.libsignal.protocol.SignalProtocolAddress+import java.util.concurrent.ConcurrentHashMap+import java.util.UUID  class MessageReceiver(     private val sessionStore: SessionStore,@@ -29,6 +33,17 @@ class MessageReceiver(     private val messageSender: MessageSender? = null,     private val sendWsResponse: ((Long, Int, String?) -> Unit)? = null, ) {+    private data class SendCacheKey(+        val recipientAci: String,+        val timestamp: Long,+    )++    private val sendCache = ConcurrentHashMap<SendCacheKey, SignalServiceProtos.Content>()+    private val maxCacheAge = 30L * 24 * 60 * 60 * 1000L // 30 days++    fun cacheSentMessage(recipientAci: String, timestamp: Long, content: SignalServiceProtos.Content) {+        sendCache[SendCacheKey(recipientAci, timestamp)] = content+    }     fun handleRequest(request: WebSocketProtos.WebSocketRequestMessage) {         if (request.verb == "PUT" && request.path == "/api/v1/queue/empty") {             Log.d(TAG, "Received queue empty notice")@@ -63,8 +78,9 @@ class MessageReceiver(          if (result.error != null) {             Log.e(TAG, "Decryption failed from ${result.senderAci}:${result.senderDeviceId}", result.error)-            if (result.retriable && envelope.urgent) {-                Log.d(TAG, "Decryption error is retriable for ${result.senderAci}")+            if (result.retriable && messageSender != null) {+                Log.d(TAG, "Decryption error is retriable for ${result.senderAci}, sending retry request")+                sendRetryRequest(result, envelope.clientTimestamp)             }             sendWsResponse?.invoke(request.id, 200, "OK")             return@@ -72,8 +88,16 @@ class MessageReceiver(          val content = result.content +        // Validate sender ACI type: drop messages from non-ACI senders+        if (result.senderAci.isEmpty() || !isValidAciUuid(result.senderAci)) {+            Log.w(TAG, "Dropping message from non-ACI sender: ${result.senderAci}")+            sendWsResponse?.invoke(request.id, 200, "OK")+            return+        }+         if (content != null && content.hasDecryptionErrorMessage()) {             Log.d(TAG, "Received decryption error message from ${result.senderAci}:${result.senderDeviceId}")+            handleRetryRequest(result, content.decryptionErrorMessage.toByteArray())             sendWsResponse?.invoke(request.id, 200, "OK")             return         }@@ -85,16 +109,12 @@ class MessageReceiver(         }          if (content != null && content.hasSenderKeyDistributionMessage()) {-            try {-                val skdmBytes = content.senderKeyDistributionMessage.toByteArray()-                val skdm = SenderKeyDistributionMessage(skdmBytes)-                val senderAddress = SignalProtocolAddress(result.senderAci, result.senderDeviceId)-                val groupBuilder = GroupSessionBuilder(senderKeyStore)-                groupBuilder.process(senderAddress, skdm)-                Log.d(TAG, "Processed SKDM from ${result.senderAci}:${result.senderDeviceId}")-            } catch (e: Exception) {-                Log.w(TAG, "Failed to process SKDM from ${result.senderAci}", e)-            }+            val skdmBytes = content.senderKeyDistributionMessage.toByteArray()+            val skdm = SenderKeyDistributionMessage(skdmBytes)+            val senderAddress = SignalProtocolAddress(result.senderAci, result.senderDeviceId)+            val groupBuilder = GroupSessionBuilder(senderKeyStore)+            groupBuilder.process(senderAddress, skdm)+            Log.d(TAG, "Processed SKDM from ${result.senderAci}:${result.senderDeviceId}")         }          if (content != null && content.hasDataMessage() && content.dataMessage.profileKey.size() == 32) {@@ -181,7 +201,7 @@ class MessageReceiver(         onDecrypted(message)         sendWsResponse?.invoke(request.id, 200, "OK") -        val shouldSendDeliveryReceipt = envelope.urgent && when (message.content) {+        val shouldSendDeliveryReceipt = when (message.content) {             is MessageContent.TextMessage,             is MessageContent.Reaction,             is MessageContent.Delete,@@ -210,4 +230,87 @@ class MessageReceiver(     companion object {         private const val TAG = "SignalReceiver"     }++    private fun isValidAciUuid(aci: String): Boolean {+        return try {+            UUID.fromString(aci)+            !aci.startsWith("PNI:")+        } catch (_: IllegalArgumentException) {+            false+        }+    }++    private fun sendRetryRequest(result: EnvelopeDecryptor.DecryptionResult, originalTimestamp: Long) {+        try {+            val ciphertext = result.ciphertext ?: return+            val dem = DecryptionErrorMessage.forOriginalMessage(+                ciphertext, result.ciphertextType, originalTimestamp, result.senderDeviceId+            )+            val demBytes = dem.serialize()+            val content = SignalServiceProtos.Content.newBuilder()+                .setDecryptionErrorMessage(com.google.protobuf.ByteString.copyFrom(demBytes))+                .build()+            runBlocking {+                messageSender?.sendMessage(result.senderAci, content, System.currentTimeMillis())+            }+            Log.d(TAG, "Sent retry receipt to ${result.senderAci}:${result.senderDeviceId}")+        } catch (e: Exception) {+            Log.e(TAG, "Failed to send retry request to ${result.senderAci}", e)+        }+    }++    private fun handleRetryRequest(+        result: EnvelopeDecryptor.DecryptionResult,+        demBytes: ByteArray,+    ) {+        try {+            val dem = SignalServiceProtos.DecryptionErrorMessage.parseFrom(demBytes)+            val destDeviceId = dem.deviceId+            if (destDeviceId.toInt() != deviceId) {+                Log.d(TAG, "Ignoring decryption error message for another device: $destDeviceId")+                return+            }+            val requestedTimestamp = dem.timestamp+            val age = System.currentTimeMillis() - requestedTimestamp.toLong()+            var cachedContent: SignalServiceProtos.Content? = null+            if (age < maxCacheAge) {+                cachedContent = sendCache[SendCacheKey(result.senderAci, requestedTimestamp)]+            }++            if (dem.hasRatchetKey()) {+                val senderAddress = SignalProtocolAddress(result.senderAci, result.senderDeviceId)+                val session = sessionStore.loadSession(senderAddress)+                if (session != null) {+                    session.archiveCurrentState()+                    sessionStore.storeSession(senderAddress, session)+                    Log.d(TAG, "Archived session state for ${result.senderAci}:${result.senderDeviceId}")+                }+            }++            val retryContent = cachedContent ?: run {+                if (!dem.hasRatchetKey()) {+                    Log.d(TAG, "No cached message and no ratchet key, not responding to retry")+                    return+                }+                val rng = java.security.SecureRandom()+                val padding = ByteArray(rng.nextInt(511) + 1)+                rng.nextBytes(padding)+                SignalServiceProtos.Content.newBuilder()+                    .setNullMessage(+                        SignalServiceProtos.NullMessage.newBuilder()+                            .setPadding(com.google.protobuf.ByteString.copyFrom(padding))+                            .build()+                    ).build()+            }++            val responseTimestamp = if (cachedContent != null) requestedTimestamp else System.currentTimeMillis().toULong().toLong()+            Log.d(TAG, "Responding to decryption error message from ${result.senderAci}:${result.senderDeviceId}, " ++                "cached=${cachedContent != null}, ts=$requestedTimestamp")+            runBlocking {+                messageSender?.sendMessage(result.senderAci, retryContent, responseTimestamp)+            }+        } catch (e: Exception) {+            Log.e(TAG, "Failed to handle retry request from ${result.senderAci}", e)+        }+    } }
messages/src/main/java/com/vayunmathur/messages/signal/sending/MessageSender.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/sending/MessageSender.kt b/messages/src/main/java/com/vayunmathur/messages/signal/sending/MessageSender.ktindex 5dde7d3f1f..6e50731d70 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/sending/MessageSender.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/sending/MessageSender.kt@@ -3,10 +3,14 @@ package com.vayunmathur.messages.signal.sending import android.util.Base64 import android.util.Log import com.vayunmathur.messages.signal.proto.SignalServiceProtos+import com.vayunmathur.messages.signal.store.SignalGroupStore import com.vayunmathur.messages.signal.store.SignalProtocolStoreImpl import com.vayunmathur.messages.signal.web.SignalWebSocket import org.json.JSONArray import org.json.JSONObject+import org.signal.libsignal.metadata.SealedSessionCipher+import org.signal.libsignal.metadata.certificate.SenderCertificate+import org.signal.libsignal.protocol.IdentityKeyPair import org.signal.libsignal.protocol.SessionCipher import org.signal.libsignal.protocol.SignalProtocolAddress import org.signal.libsignal.protocol.message.CiphertextMessage@@ -16,6 +20,7 @@ import org.signal.libsignal.protocol.state.PreKeyStore import org.signal.libsignal.protocol.state.SessionStore import org.signal.libsignal.protocol.state.SignedPreKeyStore import org.signal.libsignal.protocol.groups.state.SenderKeyStore+import java.util.UUID  class MessageSender(     private val ws: SignalWebSocket,@@ -30,15 +35,55 @@ class MessageSender(     private val deviceManager: DeviceManager,     private val recipientStore: com.vayunmathur.messages.signal.store.SignalRecipientStore? = null,     private var unauthedWs: SignalWebSocket? = null,+    private val groupStore: SignalGroupStore? = null,+    private val selfPni: String? = null,+    private val aciIdentityKeyPair: IdentityKeyPair? = null,+    private val pniIdentityKeyPair: IdentityKeyPair? = null,+    private val accountRecord: com.vayunmathur.messages.signal.proto.AccountRecord? = null, ) {     private val protocolStore = SignalProtocolStoreImpl(         sessionStore, identityKeyStore, preKeyStore, signedPreKeyStore, kyberPreKeyStore, senderKeyStore     )      @Volatile-    private var cachedSenderCertificate: org.signal.libsignal.metadata.certificate.SenderCertificate? = null+    private var cachedSenderCertificate: SenderCertificate? = null     private var senderCertExpiry: Long = 0 +    private val sendCache = LinkedHashMap<SendCacheKey, SignalServiceProtos.Content>(64, 0.75f, true)+    private val sendCacheLock = Any()++    private data class SendCacheKey(val recipientAci: String, val groupId: String?, val timestamp: Long)++    private fun addSendCache(recipientAci: String, groupId: String?, timestamp: Long, content: SignalServiceProtos.Content) {+        synchronized(sendCacheLock) {+            if (sendCache.size >= 128) {+                val iter = sendCache.entries.iterator()+                if (iter.hasNext()) { iter.next(); iter.remove() }+            }+            sendCache[SendCacheKey(recipientAci, groupId, timestamp)] = content+        }+    }++    fun getCachedContent(recipientAci: String, groupId: String?, timestamp: Long): SignalServiceProtos.Content? {+        synchronized(sendCacheLock) {+            return sendCache[SendCacheKey(recipientAci, groupId, timestamp)]+        }+    }++    private suspend fun fetchSenderCertificate(): SenderCertificate {+        val now = System.currentTimeMillis()+        cachedSenderCertificate?.let { cached ->+            if (senderCertExpiry - now > 24 * 60 * 60 * 1000L) return cached+        }+        val resp = ws.sendRequest("GET", "/v1/certificate/delivery?includeE164=false", null, emptyMap())+        val json = JSONObject(String(resp.body.toByteArray()))+        val certBytes = Base64.decode(json.getString("certificate"), Base64.DEFAULT)+        val cert = SenderCertificate(certBytes)+        cachedSenderCertificate = cert+        senderCertExpiry = cert.expiration+        return cert+    }+     class RecipientUnregisteredException(aci: String) : Exception("Recipient not registered (404): $aci")      suspend fun sendMessage(@@ -56,20 +101,45 @@ class MessageSender(             } else content         } else content -        val isDeliveryReceipt = contentWithProfileKey.hasReceiptMessage() &&-            contentWithProfileKey.receiptMessage.type == SignalServiceProtos.ReceiptMessage.Type.DELIVERY+        val isTypingOrReceipt = contentWithProfileKey.hasTypingMessage() ||+            contentWithProfileKey.hasReceiptMessage()++        // Gate typing indicators on account settings+        if (contentWithProfileKey.hasTypingMessage() && accountRecord != null && !accountRecord.typingIndicators) {+            Log.d(TAG, "Not sending typing message as typing indicators are disabled")+            return SendResult(success = true)+        }++        // Gate read receipts on account settings+        if (contentWithProfileKey.hasReceiptMessage() &&+            contentWithProfileKey.receiptMessage.type == SignalServiceProtos.ReceiptMessage.Type.READ &&+            accountRecord != null && !accountRecord.readReceipts) {+            Log.d(TAG, "Not sending read receipt as read receipts are disabled")+            if (contentWithProfileKey.hasReceiptMessage()) {+                sendSyncMessage(recipientAci, contentWithProfileKey, timestamp)+            }+            return SendResult(success = true)+        }++        // Attach PNI signature when needed+        val contentToSend = maybeAttachPniSignature(recipientAci, contentWithProfileKey, isTypingOrReceipt)++        val isDeliveryReceipt = contentToSend.hasReceiptMessage() &&+            contentToSend.receiptMessage.type == SignalServiceProtos.ReceiptMessage.Type.DELIVERY         if (recipientAci == selfAci && !isDeliveryReceipt) {-            if (contentWithProfileKey.hasDataMessage() || contentWithProfileKey.hasEditMessage()) {-                sendSyncMessage(null, contentWithProfileKey, timestamp)+            if (contentToSend.hasDataMessage() || contentToSend.hasEditMessage()) {+                sendSyncMessage(null, contentToSend, timestamp)             }             return SendResult(success = true)         } -        val paddedContent = padContent(contentWithProfileKey.toByteArray())+        addSendCache(recipientAci, null, timestamp, contentToSend)++        val paddedContent = padContent(contentToSend.toByteArray())         return try {-            val sentUnidentified = sendToRecipient(recipientAci, paddedContent, timestamp, isUrgent(contentWithProfileKey))-            if (contentWithProfileKey.hasDataMessage() || contentWithProfileKey.hasEditMessage()) {-                sendSyncMessage(recipientAci, contentWithProfileKey, timestamp, unidentified = sentUnidentified)+            val sentUnidentified = sendToRecipient(recipientAci, paddedContent, timestamp, isUrgent(contentToSend))+            if (contentToSend.hasDataMessage() || contentToSend.hasEditMessage()) {+                sendSyncMessage(recipientAci, contentToSend, timestamp, unidentified = sentUnidentified)             }             SendResult(success = true, unidentified = sentUnidentified)         } catch (e: Exception) {@@ -78,6 +148,33 @@ class MessageSender(         }     } +    private suspend fun maybeAttachPniSignature(+        recipientAci: String,+        content: SignalServiceProtos.Content,+        isTypingOrReceipt: Boolean,+    ): SignalServiceProtos.Content {+        if (pniIdentityKeyPair == null || aciIdentityKeyPair == null || selfPni == null) return content+        if (isTypingOrReceipt) return content+        if (content.hasPniSignatureMessage()) return content++        val recipient = recipientStore?.getRecipient(recipientAci) ?: return content+        if (!recipient.needsPniSignature) return content++        Log.d(TAG, "Including PNI signature in message to $recipientAci")+        val sig = pniIdentityKeyPair.signAlternateIdentity(aciIdentityKeyPair.publicKey)+        val pniBytes = uuidToBytes(selfPni)++        recipientStore.storeRecipient(recipient.copy(needsPniSignature = false))++        return content.toBuilder()+            .setPniSignatureMessage(+                SignalServiceProtos.PniSignatureMessage.newBuilder()+                    .setPni(com.google.protobuf.ByteString.copyFrom(pniBytes))+                    .setSignature(com.google.protobuf.ByteString.copyFrom(sig))+                    .build()+            ).build()+    }+     suspend fun sendReadReceipt(recipientAci: String, timestamps: List<Long>) {         try {             val content = ContentBuilders.readReceipt(timestamps)@@ -124,20 +221,24 @@ class MessageSender(         content: SignalServiceProtos.Content,         timestamp: Long,     ): List<SendResult> {-        val paddedContent = padContent(content.toByteArray())+        // Decorate with GroupV2 context+        val decoratedContent = decorateWithGroupContext(groupId, content)++        val paddedContent = padContent(decoratedContent.toByteArray())         val results = memberAcis.map { aci ->             if (aci == selfAci) return@map SendResult(success = true)+            addSendCache(aci, groupId, timestamp, decoratedContent)             try {-                sendToRecipient(aci, paddedContent, timestamp, isUrgent(content))+                sendToRecipient(aci, paddedContent, timestamp, isUrgent(decoratedContent))                 SendResult(success = true)             } catch (e: Exception) {                 Log.e(TAG, "Failed to send group message to $aci", e)                 SendResult(success = false, error = e.message)             }         }-        if (content.hasDataMessage() || content.hasEditMessage()) {+        if (decoratedContent.hasDataMessage() || decoratedContent.hasEditMessage()) {             try {-                sendSyncMessage(null, content, timestamp, groupId, memberAcis)+                sendSyncMessage(null, decoratedContent, timestamp, groupId, memberAcis)             } catch (e: Exception) {                 Log.w(TAG, "Failed to send group sync message", e)             }@@ -145,6 +246,36 @@ class MessageSender(         return results     } +    private suspend fun decorateWithGroupContext(+        groupId: String,+        content: SignalServiceProtos.Content,+    ): SignalServiceProtos.Content {+        val group = groupStore?.getGroup(groupId) ?: return content+        val groupContext = SignalServiceProtos.GroupContextV2.newBuilder()+            .setMasterKey(com.google.protobuf.ByteString.copyFrom(group.masterKey))+            .setRevision(group.revision)+            .build()++        val builder = content.toBuilder()+        when {+            content.hasDataMessage() -> {+                builder.setDataMessage(content.dataMessage.toBuilder().setGroupV2(groupContext))+            }+            content.hasEditMessage() && content.editMessage.hasDataMessage() -> {+                val editDm = content.editMessage.dataMessage.toBuilder().setGroupV2(groupContext)+                builder.setEditMessage(content.editMessage.toBuilder().setDataMessage(editDm))+            }+            content.hasTypingMessage() -> {+                val groupIdBytes = Base64.decode(groupId, Base64.DEFAULT)+                builder.setTypingMessage(+                    content.typingMessage.toBuilder()+                        .setGroupId(com.google.protobuf.ByteString.copyFrom(groupIdBytes))+                )+            }+        }+        return builder.build()+    }+     private suspend fun sendToRecipient(         recipientAci: String,         paddedContent: ByteArray,@@ -161,7 +292,7 @@ class MessageSender(         for (deviceId in deviceIds) {             deviceManager.ensureSession(recipientAci, deviceId)             val address = SignalProtocolAddress(recipientAci, deviceId)-            val encrypted = encryptFor(address, paddedContent)+            val encrypted = encryptFor(address, paddedContent, sealedSender = useSealedSender && unauthedWs != null && recipientAci != selfAci)             messages.put(JSONObject().apply {                 put("type", encrypted.first)                 put("destinationDeviceId", deviceId)@@ -251,19 +382,30 @@ class MessageSender(         }     } -    private fun encryptFor(+    private suspend fun encryptFor(         address: SignalProtocolAddress,         paddedContent: ByteArray,+        sealedSender: Boolean = false,     ): Triple<Int, Int, String> {         val cipher = SessionCipher(protocolStore, address)         val ciphertext = cipher.encrypt(paddedContent)+        val regId = protocolStore.loadSession(address).remoteRegistrationId++        if (sealedSender) {+            val cert = fetchSenderCertificate()+            val sealedCipher = SealedSessionCipher(+                protocolStore, UUID.fromString(selfAci), selfAci, selfDeviceId+            )+            val sealedPayload = sealedCipher.encrypt(address, cert, ciphertext.serialize())+            return Triple(6, regId, Base64.encodeToString(sealedPayload, Base64.NO_WRAP))+        }+         val type = when (ciphertext.type) {             CiphertextMessage.PREKEY_TYPE -> 3             CiphertextMessage.WHISPER_TYPE -> 1             CiphertextMessage.PLAINTEXT_CONTENT_TYPE -> 8             else -> 0         }-        val regId = protocolStore.loadSession(address).remoteRegistrationId         return Triple(type, regId, Base64.encodeToString(ciphertext.serialize(), Base64.NO_WRAP))     } @@ -289,9 +431,15 @@ class MessageSender(          if (recipientAci != null) {             sentBuilder.setDestinationServiceId(recipientAci)+            sentBuilder.setDestinationServiceIdBinary(+                com.google.protobuf.ByteString.copyFrom(uuidToBytes(recipientAci))+            )             sentBuilder.addUnidentifiedStatus(                 SignalServiceProtos.SyncMessage.Sent.UnidentifiedDeliveryStatus.newBuilder()                     .setDestinationServiceId(recipientAci)+                    .setDestinationServiceIdBinary(+                        com.google.protobuf.ByteString.copyFrom(uuidToBytes(recipientAci))+                    )                     .setUnidentified(unidentified)                     .build()             )@@ -422,6 +570,14 @@ class MessageSender(             val sync = content.syncMessage             return sync.hasSent() || sync.hasRequest()         }++        fun uuidToBytes(uuid: String): ByteArray {+            val parsed = UUID.fromString(uuid)+            val buf = java.nio.ByteBuffer.allocate(16)+            buf.putLong(parsed.mostSignificantBits)+            buf.putLong(parsed.leastSignificantBits)+            return buf.array()+        }     } }     data class SendResult(val success: Boolean, val error: String? = null, val unidentified: Boolean = false)
messages/src/main/java/com/vayunmathur/messages/signal/store/SignalDatabase.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalDatabase.kt b/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalDatabase.ktindex 99314ec4d7..33102a3799 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalDatabase.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalDatabase.kt@@ -290,6 +290,69 @@ interface SignalGroupDao {     suspend fun getAll(): List<SignalGroupEntity> } +@Entity(tableName = "signal_backup_recipients")+data class SignalBackupRecipientEntity(+    @PrimaryKey val id: Long,+    val data: ByteArray,+)++@Entity(tableName = "signal_backup_chats")+data class SignalBackupChatEntity(+    @PrimaryKey val id: Long,+    val recipientId: Long,+    val data: ByteArray,+)++@Entity(+    tableName = "signal_backup_chat_items",+    primaryKeys = ["chatId", "messageId"],+)+data class SignalBackupChatItemEntity(+    val chatId: Long,+    val authorId: Long,+    val messageId: Long,+    val data: ByteArray,+)++@Dao+interface SignalBackupRecipientDao {+    @Insert(onConflict = OnConflictStrategy.REPLACE)+    suspend fun insert(entity: SignalBackupRecipientEntity)++    @Query("SELECT * FROM signal_backup_recipients WHERE id = :id LIMIT 1")+    suspend fun get(id: Long): SignalBackupRecipientEntity?++    @Query("DELETE FROM signal_backup_recipients")+    suspend fun deleteAll()+}++@Dao+interface SignalBackupChatDao {+    @Insert(onConflict = OnConflictStrategy.REPLACE)+    suspend fun insert(entity: SignalBackupChatEntity)++    @Query("SELECT * FROM signal_backup_chats WHERE id = :id LIMIT 1")+    suspend fun get(id: Long): SignalBackupChatEntity?++    @Query("SELECT * FROM signal_backup_chats")+    suspend fun getAll(): List<SignalBackupChatEntity>++    @Query("DELETE FROM signal_backup_chats")+    suspend fun deleteAll()+}++@Dao+interface SignalBackupChatItemDao {+    @Insert(onConflict = OnConflictStrategy.IGNORE)+    suspend fun insert(entity: SignalBackupChatItemEntity)++    @Query("SELECT * FROM signal_backup_chat_items WHERE chatId = :chatId ORDER BY messageId DESC LIMIT :limit")+    suspend fun getByChatId(chatId: Long, limit: Int = 100): List<SignalBackupChatItemEntity>++    @Query("DELETE FROM signal_backup_chat_items")+    suspend fun deleteAll()+}+ @Dao interface SignalEventBufferDao {     @Query("SELECT * FROM signal_event_buffer WHERE ciphertextHash = :hash LIMIT 1")@@ -317,8 +380,11 @@ interface SignalEventBufferDao {         SignalRecipientEntity::class,         SignalGroupEntity::class,         SignalEventBufferEntity::class,+        SignalBackupRecipientEntity::class,+        SignalBackupChatEntity::class,+        SignalBackupChatItemEntity::class,     ],-    version = 4,+    version = 5,     exportSchema = false, ) abstract class SignalDatabase : RoomDatabase() {@@ -332,6 +398,9 @@ abstract class SignalDatabase : RoomDatabase() {     abstract fun recipientDao(): SignalRecipientDao     abstract fun groupDao(): SignalGroupDao     abstract fun eventBufferDao(): SignalEventBufferDao+    abstract fun backupRecipientDao(): SignalBackupRecipientDao+    abstract fun backupChatDao(): SignalBackupChatDao+    abstract fun backupChatItemDao(): SignalBackupChatItemDao      companion object {         @Volatile
messages/src/main/java/com/vayunmathur/messages/signal/store/SignalPreKeyStore.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalPreKeyStore.kt b/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalPreKeyStore.ktindex 1aae443fe9..81c0bd176c 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalPreKeyStore.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalPreKeyStore.kt@@ -134,6 +134,7 @@ class SignalPreKeyStore(private val db: SignalDatabase) : PreKeyStore, SignedPre     fun deleteAllPreKeys() {         runBlocking {             db.preKeyDao().deleteAll()+            db.signedPreKeyDao().deleteAll()             db.kyberPreKeyDao().deleteAll()         }     }
messages/src/main/java/com/vayunmathur/messages/signal/store/SignalRecipientStore.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalRecipientStore.kt b/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalRecipientStore.ktindex 73b4ca827f..b893829701 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalRecipientStore.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/store/SignalRecipientStore.kt@@ -39,6 +39,9 @@ class SignalRecipientStore(private val db: SignalDatabase) {     }      suspend fun storeProfileKey(aci: String, profileKey: ByteArray) {+        if (profileKey.size != 32) {+            return+        }         val existing = getRecipient(aci)         if (existing != null) {             storeRecipient(existing.copy(profileKey = profileKey))
messages/src/main/java/com/vayunmathur/messages/signal/web/SignalHttpClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/web/SignalHttpClient.kt b/messages/src/main/java/com/vayunmathur/messages/signal/web/SignalHttpClient.ktindex c1a62ce7ce..2fa15f1c29 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/web/SignalHttpClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/web/SignalHttpClient.kt@@ -103,8 +103,6 @@ object SignalHttpClient {         }     } -    suspend fun getAttachment-     suspend fun getAttachment(path: String, cdnNumber: Int): Response {         val host = if (cdnNumber == 0) {             CDN_HOSTS[0]
messages/src/main/java/com/vayunmathur/messages/signal/web/SignalWebSocket.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/web/SignalWebSocket.kt b/messages/src/main/java/com/vayunmathur/messages/signal/web/SignalWebSocket.ktindex 5afb3db8c4..f7162fb258 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/web/SignalWebSocket.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/web/SignalWebSocket.kt@@ -211,7 +211,7 @@ class SignalWebSocket(         val isSelfDelete = method == "DELETE" && path.startsWith("/v1/devices/")          var lastException: Exception? = null-        for (attempt in 0..MAX_REQUEST_RETRIES) {+        for (attempt in 0 until MAX_REQUEST_RETRIES) {             try {                 return sendRequestOnce(method, path, body, headers)             } catch (e: IOException) {
messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/MtProtoConnection.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/MtProtoConnection.kt b/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/MtProtoConnection.ktindex 5e5cd965ff..095092e429 100644--- a/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/MtProtoConnection.kt+++ b/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/MtProtoConnection.kt@@ -49,7 +49,7 @@ class MtProtoConnection(     private var serverTimeOffset: Long = 0L     private var serverTimeOffsetSet = false     private val futureSalts = mutableListOf<MessageFraming.FutureSalt>()-    private var pongDeferred: CompletableDeferred<Unit>? = null+    private val pongDeferreds = mutableMapOf<Long, CompletableDeferred<Unit>>()      private companion object {         const val ACK_BATCH_SIZE = 20@@ -137,12 +137,7 @@ class MtProtoConnection(         }     } -    private suspend fun handleDecrypted(data: ByteArray, msgId: Long, seqNo: Int) {-        if (MessageFraming.needsAck(seqNo)) {-            synchronized(pendingAcks) { pendingAcks.add(msgId) }-            checkAckBatchFlush()-        }-+    private suspend fun handleDecrypted(data: ByteArray, msgId: Long, seqNo: Int, fromContainer: Boolean = false) {         val buf = TlBuffer(data)         if (buf.remaining < 4) return         val typeId = buf.peekId()@@ -152,26 +147,33 @@ class MtProtoConnection(                 buf.int32() // consume type id                 val messages = MessageFraming.parseContainer(buf)                 for (msg in messages) {-                    handleDecrypted(msg.data, msg.msgId, msg.seqNo)+                    handleDecrypted(msg.data, msg.msgId, msg.seqNo, fromContainer = true)                 }             }             MessageFraming.TYPE_RPC_RESULT -> {                 buf.int32() // consume type id                 val (reqMsgId, resultBuf) = MessageFraming.parseRpcResult(buf)                 if (resultBuf.remaining >= 4) {-                    val innerType = resultBuf.peekId()-                    if (innerType == MessageFraming.TYPE_GZIP_PACKED) {+                    var innerType = resultBuf.peekId()+                    val effectiveBuf = if (innerType == MessageFraming.TYPE_GZIP_PACKED) {                         resultBuf.int32()                         val decompressed = MessageFraming.gunzipPacked(resultBuf)-                        rpcEngine.notifyResult(reqMsgId, TlBuffer(decompressed))-                    } else if (innerType == MessageFraming.TYPE_RPC_ERROR) {-                        resultBuf.int32()-                        val err = MessageFraming.parseRpcError(resultBuf)+                        val decompBuf = TlBuffer(decompressed)+                        if (decompBuf.remaining >= 4) {+                            innerType = decompBuf.peekId()+                        }+                        decompBuf+                    } else {+                        resultBuf+                    }+                    if (innerType == MessageFraming.TYPE_RPC_ERROR) {+                        effectiveBuf.int32()+                        val err = MessageFraming.parseRpcError(effectiveBuf)                         rpcEngine.notifyError(reqMsgId, err.errorCode, err.errorMessage)                     } else if (innerType == MessageFraming.TYPE_PONG) {-                        handlePong(resultBuf)+                        handlePong(effectiveBuf)                     } else {-                        rpcEngine.notifyResult(reqMsgId, resultBuf)+                        rpcEngine.notifyResult(reqMsgId, effectiveBuf)                     }                 }             }@@ -195,7 +197,8 @@ class MtProtoConnection(                 Log.d(TAG, "Updated server salt, re-sending msgId=${bss.badMsgId}")                 rpcEngine.getPendingPayload(bss.badMsgId)?.let { payload ->                     try {-                        send(payload, true)+                        val newMsgId = send(payload, true)+                        rpcEngine.migratePending(bss.badMsgId, newMsgId)                     } catch (e: Exception) {                         Log.w(TAG, "Re-send after salt update failed: ${e.message}")                     }@@ -204,12 +207,13 @@ class MtProtoConnection(             MessageFraming.TYPE_BAD_MSG_NOTIFICATION -> {                 buf.int32()                 val notification = MessageFraming.parseBadMsgNotification(buf)-                if (notification.errorCode == 16 || notification.errorCode == 17) {+                if (!serverTimeOffsetSet && (notification.errorCode == 16 || notification.errorCode == 17)) {                     val serverTime = MessageId.timeSeconds(msgId)                     val localTime = System.currentTimeMillis() / 1000                     serverTimeOffset = serverTime - localTime                     serverTimeOffsetSet = true                     MessageId.reset()+                    updateSalt()                     Log.d(TAG, "Time resynced: offset=${serverTimeOffset}s (error code ${notification.errorCode})")                 }                 rpcEngine.notifyError(notification.badMsgId, notification.errorCode,@@ -250,12 +254,19 @@ class MtProtoConnection(                 }             }         }++        if (!fromContainer && MessageFraming.needsAck(seqNo)) {+            synchronized(pendingAcks) { pendingAcks.add(msgId) }+            checkAckBatchFlush()+        }     }      private fun handlePong(buf: TlBuffer) {         buf.int32()-        MessageFraming.parsePong(buf)-        pongDeferred?.complete(Unit)+        val pong = MessageFraming.parsePong(buf)+        synchronized(pongDeferreds) {+            pongDeferreds.remove(pong.pingId)?.complete(Unit)+        }     }      private suspend fun pingLoop() {@@ -263,16 +274,20 @@ class MtProtoConnection(             delay(60_000)             if (!connected) break             try {+                val pingId = secureRandom.nextLong()                 val deferred = CompletableDeferred<Unit>()-                pongDeferred = deferred-                val ping = MessageFraming.writePingDelayDisconnect(secureRandom.nextLong(), 75)+                synchronized(pongDeferreds) { pongDeferreds[pingId] = deferred }+                val ping = MessageFraming.writePingDelayDisconnect(pingId, 75)                 send(ping, false)                 try {                     withTimeout(15_000) { deferred.await() }                 } catch (_: TimeoutCancellationException) {-                    Log.w(TAG, "Pong timeout, connection may be dead")+                    Log.w(TAG, "Pong timeout, disconnecting")+                    disconnect()+                    onDisconnected?.invoke()+                    return                 } finally {-                    pongDeferred = null+                    synchronized(pongDeferreds) { pongDeferreds.remove(pingId) }                 }             } catch (e: Exception) {                 Log.w(TAG, "Ping failed: ${e.message}")@@ -317,6 +332,17 @@ class MtProtoConnection(         }     } +    private fun updateSalt() {+        val now = (System.currentTimeMillis() / 1000) + serverTimeOffset+        synchronized(futureSalts) {+            val valid = futureSalts.firstOrNull { it.validSince <= now && now < it.validUntil }+            if (valid != null) {+                salt = valid.salt+                Log.d(TAG, "Salt updated from future salts")+            }+        }+    }+     private suspend fun handleDecrypted(data: com.vayunmathur.messages.telegram.mtproto.crypto.DecryptedMessage) {         handleDecrypted(data.data, data.messageId, data.seqNo)     }
messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/crypto/RsaKey.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/crypto/RsaKey.kt b/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/crypto/RsaKey.ktindex 87648ecfaa..3a9c4a6cee 100644--- a/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/crypto/RsaKey.kt+++ b/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/crypto/RsaKey.kt@@ -52,9 +52,9 @@ object RsaKey {          val dataWithPadding = ByteArray(192)         System.arraycopy(data, 0, dataWithPadding, 0, data.size)-        random.nextBytes(ByteArray(192 - data.size).also {-            System.arraycopy(it, 0, dataWithPadding, data.size, it.size)-        })+        val padding = ByteArray(192 - data.size)+        random.nextBytes(padding)+        System.arraycopy(padding, 0, dataWithPadding, data.size, padding.size)          val dataPadReversed = dataWithPadding.copyOf()         dataPadReversed.reverse()
messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/rpc/RpcEngine.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/rpc/RpcEngine.kt b/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/rpc/RpcEngine.ktindex 7d03b5934a..78e785c2ef 100644--- a/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/rpc/RpcEngine.kt+++ b/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/rpc/RpcEngine.kt@@ -12,6 +12,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeout import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean+import java.util.concurrent.atomic.AtomicInteger  class RpcException(val errorCode: Int, override val message: String) : Exception("RPC error $errorCode: $message") @@ -25,6 +26,8 @@ class RpcEngine(     private val acks = ConcurrentHashMap<Long, CompletableDeferred<Unit>>()     private val payloads = ConcurrentHashMap<Long, ByteArray>()     private val closed = AtomicBoolean(false)+    private val activeCount = AtomicInteger(0)+    private val idleLock = Object()     private val TAG = "RpcEngine"      suspend fun <R : TlObject> execute(@@ -33,6 +36,7 @@ class RpcEngine(         decoder: (TlBuffer) -> R,     ): R = coroutineScope {         check(!closed.get()) { "Engine is closed" }+        activeCount.incrementAndGet()          val buf = TlBuffer()         method.encode(buf)@@ -51,18 +55,18 @@ class RpcEngine(                     withTimeout(retryInterval) { ackDeferred.await() }                     return@launch                 } catch (_: TimeoutCancellationException) {+                    Log.w(TAG, "Ack timeout for msgId=$msgId, retry ${retries + 1}/$maxRetries")+                    try { sendFn(encoded, msgId) } catch (e: Exception) {+                        Log.e(TAG, "Retry send failed for msgId=$msgId", e)+                        deferred.completeExceptionally(e)+                        return@launch+                    }                     retries++                     if (retries >= maxRetries) {                         Log.e(TAG, "Retry limit reached for msgId=$msgId")                         deferred.completeExceptionally(RetryLimitReachedException(retries))                         return@launch                     }-                    Log.w(TAG, "Ack timeout for msgId=$msgId, retry $retries/$maxRetries")-                    try { sendFn(encoded, msgId) } catch (e: Exception) {-                        Log.e(TAG, "Retry send failed for msgId=$msgId", e)-                        deferred.completeExceptionally(e)-                        return@launch-                    }                 }             }         }@@ -77,6 +81,9 @@ class RpcEngine(         } finally {             retryJob.cancel()             acks.remove(msgId)+            if (activeCount.decrementAndGet() == 0) {+                synchronized(idleLock) { idleLock.notifyAll() }+            }         }     } @@ -111,6 +118,11 @@ class RpcEngine(      fun close() {         closed.set(true)+        synchronized(idleLock) {+            while (activeCount.get() > 0) {+                idleLock.wait()+            }+        }     }      fun forceClose() {@@ -136,4 +148,10 @@ class RpcEngine(     }      fun getPendingPayload(msgId: Long): ByteArray? = payloads.remove(msgId)++    fun migratePending(oldMsgId: Long, newMsgId: Long) {+        pending.remove(oldMsgId)?.let { pending[newMsgId] = it }+        acks.remove(oldMsgId)?.let { acks[newMsgId] = it }+        payloads.remove(oldMsgId)?.let { payloads[newMsgId] = it }+    } }
messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/tl/TlBuffer.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/tl/TlBuffer.kt b/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/tl/TlBuffer.ktindex 70956c5ce4..1bef666ce7 100644--- a/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/tl/TlBuffer.kt+++ b/messages/src/main/java/com/vayunmathur/messages/telegram/mtproto/tl/TlBuffer.kt@@ -135,6 +135,7 @@ class TlBuffer {             headerLen = 4         } else {             strLen = first+            if (strLen > 253) throw IllegalStateException("Invalid short string length: $strLen")             headerLen = 1         }         val totalLen = nearestPadded(headerLen + strLen)
messages/src/main/proto/signal/Backup.proto
diff --git a/messages/src/main/proto/signal/Backup.proto b/messages/src/main/proto/signal/Backup.protonew file mode 100644index 0000000000..f0d5b88ad7--- /dev/null+++ b/messages/src/main/proto/signal/Backup.proto@@ -0,0 +1,1453 @@+syntax = "proto3";++package signal.backup;++option java_package = "com.vayunmathur.messages.signal.proto.backup";++message BackupInfo {+  uint64 version = 1;+  uint64 backupTimeMs = 2;+  bytes mediaRootBackupKey = 3; // 32-byte random value generated when the backup is uploaded for the first time.+  string currentAppVersion = 4;+  string firstAppVersion = 5;+  bytes debugInfo = 6; // Client-specific data field for debug info during testing+}++// Frames must follow in the following ordering rules:+//+// 1. There is exactly one AccountData and it is the first frame.+// 2. A frame referenced by ID must come before the referencing frame.+//    e.g. a Recipient must come before any Chat referencing it.+// 3. All ChatItems must appear in global Chat rendering order.+//    (The order in which they were received by the client.)+// 4. ChatFolders must appear in render order (e.g., left to right for+//    LTR locales), but can appear anywhere relative to other frames respecting+//    rule 2 (after Recipients and Chats).+//+// Recipients, Chats, StickerPacks, AdHocCalls, and NotificationProfiles+// can be in any order. (But must respect rule 2.)+//+// For example, Chats may all be together at the beginning,+// or may each immediately precede its first ChatItem.+message Frame {+  // If unset, importers should skip this frame without throwing an error.+  oneof item {+    AccountData account = 1;+    Recipient recipient = 2;+    Chat chat = 3;+    ChatItem chatItem = 4;+    StickerPack stickerPack = 5;+    AdHocCall adHocCall = 6;+    NotificationProfile notificationProfile = 7;+    ChatFolder chatFolder = 8;+  }+}++message AccountData {+  enum PhoneNumberSharingMode {+    UNKNOWN = 0; // Interpret as "Nobody"+    EVERYBODY = 1;+    NOBODY = 2;+  }+  message UsernameLink {+    enum Color {+      UNKNOWN = 0; // Interpret as "Blue"+      BLUE = 1;+      WHITE = 2;+      GREY = 3;+      OLIVE = 4;+      GREEN = 5;+      ORANGE = 6;+      PINK = 7;+      PURPLE = 8;+    }++    bytes entropy = 1;  // 32 bytes of entropy used for encryption+    bytes serverId = 2; // 16 bytes of encoded UUID provided by the server+    Color color = 3;+  }++  enum SentMediaQuality {+    UNKNOWN_QUALITY = 0; // Interpret as "Standard"+    STANDARD = 1;+    HIGH = 2;+  }++  message AutoDownloadSettings {+    enum AutoDownloadOption {+      UNKNOWN = 0; // Interpret as "Never"+      NEVER = 1;+      WIFI = 2;+      WIFI_AND_CELLULAR = 3;+    }++    AutoDownloadOption images = 1;+    AutoDownloadOption audio = 2;+    AutoDownloadOption video = 3;+    AutoDownloadOption documents = 4;+  }++  enum AppTheme {+    UNKNOWN_APP_THEME = 0; // Interpret as "System"+    SYSTEM = 1;+    LIGHT = 2;+    DARK = 3;+  }++  enum CallsUseLessDataSetting {+    UNKNOWN_CALL_DATA_SETTING = 0; // Interpret as "Never"+    NEVER = 1;+    MOBILE_DATA_ONLY = 2;+    WIFI_AND_MOBILE_DATA = 3;+  }++  message AccountSettings {+    bool readReceipts = 1;+    bool sealedSenderIndicators = 2;+    bool typingIndicators = 3;+    bool linkPreviews = 4;+    bool notDiscoverableByPhoneNumber = 5;+    bool preferContactAvatars = 6;+    uint32 universalExpireTimerSeconds = 7; // 0 means no universal expire timer.+    repeated string preferredReactionEmoji = 8;+    bool displayBadgesOnProfile = 9;+    bool keepMutedChatsArchived = 10;+    bool hasSetMyStoriesPrivacy = 11;+    bool hasViewedOnboardingStory = 12;+    bool storiesDisabled = 13;+    optional bool storyViewReceiptsEnabled = 14;+    bool hasSeenGroupStoryEducationSheet = 15;+    bool hasCompletedUsernameOnboarding = 16;+    PhoneNumberSharingMode phoneNumberSharingMode = 17;+    ChatStyle defaultChatStyle = 18;+    repeated ChatStyle.CustomChatColor customChatColors = 19;+    bool optimizeOnDeviceStorage = 20;+    // See zkgroup for integer particular values. Unset if backups are not enabled.+    optional uint64 backupTier = 21;+    reserved /* showSealedSenderIndicators */ 22;+    SentMediaQuality defaultSentMediaQuality = 23;+    AutoDownloadSettings autoDownloadSettings = 24;+    reserved /* wifiAutoDownloadSettings */ 25;+    optional uint32 screenLockTimeoutMinutes = 26; // If unset, consider screen lock to be disabled.+    optional bool pinReminders = 27; // If unset, consider pin reminders to be enabled.+    AppTheme appTheme = 28;  // If unset, treat the same as "Unknown" case+    CallsUseLessDataSetting callsUseLessDataSetting = 29;  // If unset, treat the same as "Unknown" case+    bool allowSealedSenderFromAnyone = 30;+    bool allowAutomaticKeyVerification = 31;+    bool hasSeenAdminDeleteEducationDialog = 32;+  }++  message SubscriberData {+    bytes subscriberId = 1;+    string currencyCode = 2;+    bool manuallyCancelled = 3;+  }++  message IAPSubscriberData {+    bytes subscriberId = 1;++    // If unset, importers should ignore the subscriber data without throwing an error.+    oneof iapSubscriptionId {+      // Identifies an Android Play Store IAP subscription.+      string purchaseToken = 2;+      // Identifies an iOS App Store IAP subscription.+      uint64 originalTransactionId = 3;+    }+  }++  message AndroidSpecificSettings {+    enum NavigationBarSize {+      UNKNOWN_BAR_SIZE = 0; // Intepret as "Normal"+      NORMAL = 1;+      COMPACT = 2;+    }++    bool useSystemEmoji = 1;+    bool screenshotSecurity = 2;+    NavigationBarSize navigationBarSize = 3; // If unset, treat the same as "Unknown" case+  }++  bytes profileKey = 1;+  optional string username = 2;+  UsernameLink usernameLink = 3;+  string givenName = 4;+  string familyName = 5;+  string avatarUrlPath = 6;+  SubscriberData donationSubscriberData = 7;+  reserved /*backupsSubscriberData*/ 8; // A deprecated format+  AccountSettings accountSettings = 9;+  IAPSubscriberData backupsSubscriberData = 10;+  string svrPin = 11;+  AndroidSpecificSettings androidSpecificSettings = 12;+  string bioText = 13;+  string bioEmoji = 14;+  optional bytes keyTransparencyData = 15;+}++message Recipient {+  uint64 id = 1; // generated id for reference only within this file+  // If unset, importers should skip this frame without throwing an error.+  oneof destination {+    Contact contact = 2;+    Group group = 3;+    DistributionListItem distributionList = 4;+    Self self = 5;+    ReleaseNotes releaseNotes = 6;+    CallLink callLink = 7;+  }+}++// If unset - computed as the value of the first byte of SHA-256(msg=CONTACT_ID)+// modulo the count of colors. Once set the avatar color for a recipient is+// never recomputed or changed.+//+// `CONTACT_ID` is the first available identifier from the list:+// - ServiceIdToBinary(ACI)+// - E164+// - ServiceIdToBinary(PNI)+// - Group Id+enum AvatarColor {+  A100 = 0;+  A110 = 1;+  A120 = 2;+  A130 = 3;+  A140 = 4;+  A150 = 5;+  A160 = 6;+  A170 = 7;+  A180 = 8;+  A190 = 9;+  A200 = 10;+  A210 = 11;+}++message Contact {+  enum IdentityState {+    DEFAULT = 0; // A valid value -- indicates unset by the user+    VERIFIED = 1;+    UNVERIFIED = 2; // Was once verified and is now unverified+  }++  message Registered {}+  message NotRegistered {+    uint64 unregisteredTimestamp = 1;+  }++  enum Visibility {+    VISIBLE = 0; // A valid value -- the contact is not hidden+    HIDDEN = 1;+    HIDDEN_MESSAGE_REQUEST = 2;+  }++  message Name {+    string given = 1;+    string family = 2;+  }++  optional bytes aci = 1; // should be 16 bytes+  optional bytes pni = 2; // should be 16 bytes+  optional string username = 3;+  optional uint64 e164 = 4;+  bool blocked = 5;+  Visibility visibility = 6;++  // If unset, consider the user to be registered+  oneof registration {+    Registered registered = 7;+    NotRegistered notRegistered = 8;+  }++  optional bytes profileKey = 9;+  bool profileSharing = 10;+  optional string profileGivenName = 11;+  optional string profileFamilyName = 12;+  bool hideStory = 13;+  optional bytes identityKey = 14;+  IdentityState identityState = 15;+  Name nickname = 16; // absent iff both `given` and `family` are empty+  string note = 17;+  string systemGivenName = 18;+  string systemFamilyName = 19;+  string systemNickname = 20;+  optional AvatarColor avatarColor = 21;+  optional bytes keyTransparencyData = 22;+}++message Group {+  enum StorySendMode {+    DEFAULT = 0; // A valid value -- indicates unset by the user+    DISABLED = 1;+    ENABLED = 2;+  }++  bytes masterKey = 1;+  bool whitelisted = 2;+  bool hideStory = 3;+  StorySendMode storySendMode = 4;+  GroupSnapshot snapshot = 5;+  bool blocked = 6;+  optional AvatarColor avatarColor = 7;++  // These are simply plaintext copies of the groups proto from Groups.proto.+  // They should be kept completely in-sync with Groups.proto.+  // These exist to allow us to have the latest snapshot of a group during restoration without having to hit the network.+  // We would use Groups.proto if we could, but we want a plaintext version to improve export readability.+  // For documentation, defer to Groups.proto. The only name change is Group -> GroupSnapshot to avoid the naming conflict.+  message GroupSnapshot {+    reserved /*publicKey*/ 1;  // The field is deprecated in the context of static group state+    GroupAttributeBlob title = 2;+    GroupAttributeBlob description = 11;+    string avatarUrl = 3;+    GroupAttributeBlob disappearingMessagesTimer = 4;+    AccessControl accessControl = 5;+    uint32 version = 6;+    repeated Member members = 7;+    repeated MemberPendingProfileKey membersPendingProfileKey = 8;+    repeated MemberPendingAdminApproval membersPendingAdminApproval = 9;+    bytes inviteLinkPassword = 10;+    bool announcements_only = 12;+    repeated MemberBanned members_banned = 13;+    bool terminated = 14;+  }++  message GroupAttributeBlob {+    // If unset, consider the field it represents to not be present+    oneof content {+      string title = 1;+      bytes avatar = 2;+      uint32 disappearingMessagesDuration = 3;+      string descriptionText = 4;+    }+  }++  message Member {+    enum Role {+      UNKNOWN = 0; // Intepret as "Default"+      DEFAULT = 1;+      ADMINISTRATOR = 2;+    }++    bytes userId = 1;+    Role role = 2;+    reserved /*profileKey*/ 3; // This field is ignored in Backups, in favor of Contact frames for members+    reserved /*presentation*/ 4; // This field is deprecated in the context of static group state+    uint32 joinedAtVersion = 5;+    string labelEmoji = 6;+    string labelString = 7;+  }++  message MemberPendingProfileKey {+    Member member = 1;+    bytes addedByUserId = 2;+    uint64 timestamp = 3;+  }++  message MemberPendingAdminApproval {+    bytes userId = 1;+    reserved /*profileKey*/ 2; // This field is ignored in Backups, in favor of Contact frames for members+    reserved /*presentation*/ 3; // This field is deprecated in the context of static group state+    uint64 timestamp = 4;+  }++  message MemberBanned {+    bytes userId = 1;+    uint64 timestamp = 2;+  }++  message AccessControl {+    enum AccessRequired {+      UNKNOWN = 0; // Intepret as "Unsatisfiable"+      ANY = 1;+      MEMBER = 2;+      ADMINISTRATOR = 3;+      UNSATISFIABLE = 4;+    }++    AccessRequired attributes = 1;+    AccessRequired members = 2;+    AccessRequired addFromInviteLink = 3;+    AccessRequired memberLabel = 4;+  }+}++message Self {+  optional AvatarColor avatarColor = 1;+}++message ReleaseNotes {}++message Chat {+  uint64 id = 1; // generated id for reference only within this file+  uint64 recipientId = 2;+  bool archived = 3;+  optional uint32 pinnedOrder = 4; // will be displayed in ascending order+  optional uint64 expirationTimerMs = 5;+  optional uint64 muteUntilMs = 6; // INT64_MAX (2^63 - 1) = "always muted".+  bool markedUnread = 7;+  bool dontNotifyForMentionsIfMuted = 8;+  ChatStyle style = 9;+  uint32 expireTimerVersion = 10;+}++/**+ * Call Links have some associated data including a call, but unlike other recipients+ * are not tied to threads because they do not have messages associated with them.+ *+ * note:+ * - room id can be derived from the root key+ * - the presence of an admin key means this user is a call admin+ */+message CallLink {+  enum Restrictions {+    UNKNOWN = 0; // Interpret as "Admin Approval"+    NONE = 1;+    ADMIN_APPROVAL = 2;+  }++  bytes rootKey = 1;+  optional bytes adminKey = 2; // Only present if the user is an admin+  string name = 3;+  Restrictions restrictions = 4;+  uint64 expirationMs = 5;+  reserved /*epoch*/ 6;+}++message AdHocCall {+  enum State {+    UNKNOWN_STATE = 0; // Interpret as "Generic"+    GENERIC = 1;+  }++  uint64 callId = 1;+  // Refers to a `CallLink` recipient.+  uint64 recipientId = 2;+  State state = 3;+  uint64 callTimestamp = 4;+}++message DistributionListItem {+  // distribution ids are UUIDv4s. "My Story" is represented+  // by an all-0 UUID (00000000-0000-0000-0000-000000000000).+  bytes distributionId = 1; // distribution list ids are uuids++  // If unset, importers should skip the item entirely without showing an error.+  oneof item {+    uint64 deletionTimestamp = 2;+    DistributionList distributionList = 3;+  }+}++message DistributionList {+  enum PrivacyMode {+    UNKNOWN = 0; // Interpret as "Only with"+    ONLY_WITH = 1;+    ALL_EXCEPT = 2;+    ALL = 3;+  }++  string name = 1;+  bool allowReplies = 2;+  PrivacyMode privacyMode = 3;+  repeated uint64 memberRecipientIds = 4; // generated recipient id+}++message ChatItem {+  message IncomingMessageDetails {+    uint64 dateReceived = 1;+    optional uint64 dateServerSent = 2;+    bool read = 3;+    bool sealedSender = 4;+  }++  message OutgoingMessageDetails {+    repeated SendStatus sendStatus = 1;+    uint64 dateReceived = 2; // may be different from dateSent for sync messages+  }++  message DirectionlessMessageDetails {+  }++  message PinDetails {+    uint64 pinnedAtTimestamp = 1;+    oneof pinExpiry {+      uint64 pinExpiresAtTimestamp = 2; // timestamp when the pin should expire+      bool pinNeverExpires = 3;+    }+  }++  uint64 chatId = 1;   // conversation id+  uint64 authorId = 2; // recipient id+  uint64 dateSent = 3;+  optional uint64 expireStartDate = 4; // timestamp of when expiration timer started ticking down+  optional uint64 expiresInMs = 5; // how long timer of message is (ms)+  repeated ChatItem revisions = 6; // ordered from oldest to newest+  bool sms = 7;++  // If unset, importers should skip this item without throwing an error.+  oneof directionalDetails {+    IncomingMessageDetails incoming = 8;+    OutgoingMessageDetails outgoing = 9;+    DirectionlessMessageDetails directionless = 10;+  }++  // If unset, importers should skip this item without throwing an error.+  oneof item {+    StandardMessage standardMessage = 11;+    ContactMessage contactMessage = 12;+    StickerMessage stickerMessage = 13;+    RemoteDeletedMessage remoteDeletedMessage = 14;+    ChatUpdateMessage updateMessage = 15;+    PaymentNotification paymentNotification = 16;+    GiftBadge giftBadge = 17;+    ViewOnceMessage viewOnceMessage = 18;+    DirectStoryReplyMessage directStoryReplyMessage = 19; // group story reply messages are not backed up+    Poll poll = 20;+    AdminDeletedMessage adminDeletedMessage = 22;+  }++  PinDetails pinDetails = 21; // only set if message is pinned+}++message SendStatus {+  message Pending {}++  message Sent {+    bool sealedSender = 1;+  }++  message Delivered {+    bool sealedSender = 1;+  }++  message Read {+    bool sealedSender = 1;+  }++  message Viewed {+    bool sealedSender = 1;+  }++  // e.g. user in group was blocked, so we skipped sending to them+  message Skipped {}++  message Failed {+    enum FailureReason {+      UNKNOWN = 0; // A valid value -- could indicate a crash or lack of information+      NETWORK = 1;+      IDENTITY_KEY_MISMATCH = 2;+    }++    FailureReason reason = 1;+  }++  uint64 recipientId = 1;+  uint64 timestamp = 2; // the time the status was last updated -- if from a receipt, it should be the sentTime of the receipt++  // If unset, importers should consider the status to be "pending"+  oneof deliveryStatus {+    Pending pending = 3;+    Sent sent = 4;+    Delivered delivered = 5;+    Read read = 6;+    Viewed viewed = 7;+    Skipped skipped = 8;+    Failed failed = 9;+  }+}++message Text {+  string body = 1;+  repeated BodyRange bodyRanges = 2;+}++message StandardMessage {+  optional Quote quote = 1;+  optional Text text = 2;+  repeated MessageAttachment attachments = 3;+  repeated LinkPreview linkPreview = 4;+  optional FilePointer longText = 5;+  repeated Reaction reactions = 6;+}++message ContactMessage {+  ContactAttachment contact = 1;+  repeated Reaction reactions = 2;+}++message DirectStoryReplyMessage {+  message TextReply {+    Text text = 1;+    FilePointer longText = 2;+  }++  // If unset, importers should ignore the message without throwing an error.+  oneof reply {+    TextReply textReply = 1;+    string emoji = 2;+  }++  repeated Reaction reactions = 3;+  reserved /*storySentTimestamp*/ 4;+}++message PaymentNotification {+  message TransactionDetails {+    message MobileCoinTxoIdentification { // Used to map to payments on the ledger+      repeated bytes publicKey = 1; // for received transactions+      repeated bytes keyImages = 2; // for sent transactions+    }++    message FailedTransaction { // Failed payments can't be synced from the ledger+      enum FailureReason {+        GENERIC = 0; // A valid value -- reason unknown+        NETWORK = 1;+        INSUFFICIENT_FUNDS = 2;+      }+      FailureReason reason = 1;+    }++    message Transaction {+      enum Status {+        INITIAL = 0; // A valid value -- state unconfirmed+        SUBMITTED = 1;+        SUCCESSFUL = 2;+      }+      Status status = 1;++      // This identification is used to map the payment table to the ledger+      // and is likely required otherwise we may have issues reconciling with+      // the ledger+      MobileCoinTxoIdentification mobileCoinIdentification = 2;+      optional uint64 timestamp = 3;+      optional uint64 blockIndex = 4;+      optional uint64 blockTimestamp = 5;+      optional bytes transaction = 6; // mobile coin blobs+      optional bytes receipt = 7; // mobile coin blobs+    }++    // If unset, importers should treat the transaction as successful with no metadata.+    oneof payment {+      Transaction transaction = 1;+      FailedTransaction failedTransaction = 2;+    }+  }++  optional string amountMob = 1; // stored as a decimal string, e.g. 1.00001+  optional string feeMob = 2; // stored as a decimal string, e.g. 1.00001+  optional string note = 3;+  TransactionDetails transactionDetails = 4;+}++message GiftBadge {+  enum State {+    UNOPENED = 0; // A valid state+    OPENED = 1;+    REDEEMED = 2;+    FAILED = 3;+  }++  bytes receiptCredentialPresentation = 1;+  State state = 2;+}++message ViewOnceMessage {+  // Will be null for viewed messages+  MessageAttachment attachment = 1;+  repeated Reaction reactions = 2;+}++message ContactAttachment {+  message Name {+    string givenName = 1;+    string familyName = 2;+    string prefix = 3;+    string suffix = 4;+    string middleName = 5;+    string nickname = 6;+  }++  message Phone {+    enum Type {+      UNKNOWN = 0; // Interpret as "Home"+      HOME = 1;+      MOBILE = 2;+      WORK = 3;+      CUSTOM = 4;+    }++    string value = 1;+    Type type = 2;+    string label = 3;+  }++  message Email {+    enum Type {+      UNKNOWN = 0; // Intepret as "Home"+      HOME = 1;+      MOBILE = 2;+      WORK = 3;+      CUSTOM = 4;+    }++    string value = 1;+    Type type = 2;+    string label = 3;+  }++  message PostalAddress {+    enum Type {+      UNKNOWN = 0; // Interpret as "Home"+      HOME = 1;+      WORK = 2;+      CUSTOM = 3;+    }++    Type type = 1;+    string label = 2;+    string street = 3;+    string pobox = 4;+    string neighborhood = 5;+    string city = 6;+    string region = 7;+    string postcode = 8;+    string country = 9;+  }++  optional Name name = 1;+  repeated Phone number = 3;+  repeated Email email = 4;+  repeated PostalAddress address = 5;+  optional FilePointer avatar = 6;+  string organization = 7;+}++message StickerMessage {+  Sticker sticker = 1;+  repeated Reaction reactions = 2;+}++// Tombstone for remote delete+message RemoteDeletedMessage {}++message Sticker {+  bytes packId = 1;+  bytes packKey = 2;+  uint32 stickerId = 3;+  optional string emoji = 4;+  // Stickers are uploaded to be sent as attachments; we also+  // back them up as normal attachments when they are in messages.+  // DO NOT treat this as the definitive source of a sticker in+  // an installed StickerPack that shares the same packId.+  FilePointer data = 5;+}++message LinkPreview {+  string url = 1;+  optional string title = 2;+  optional FilePointer image = 3;+  optional string description = 4;+  optional uint64 date = 5;+}++// A FilePointer on a message that has additional+// metadata that applies only to message attachments.+message MessageAttachment {+  // Similar to SignalService.AttachmentPointer.Flags,+  // but explicitly mutually exclusive. Note the different raw values+  // (non-zero starting values are not supported in proto3.)+  enum Flag {+    NONE = 0; // A valid value -- no flag applied+    VOICE_MESSAGE = 1;+    BORDERLESS = 2;+    GIF = 3;+  }++  FilePointer pointer = 1;+  Flag flag = 2;+  bool wasDownloaded = 3;+  // Cross-client identifier for this attachment among all attachments on the+  // owning message. See: SignalService.AttachmentPointer.clientUuid.+  optional bytes clientUuid = 4;+}++message FilePointer {+  message LocatorInfo {+    // Must be non-empty if transitCdnKey or plaintextHash are set/nonempty.+    // Otherwise must be empty.+    bytes key = 1;++    reserved /*legacyDigest*/ 2;++    oneof integrityCheck {+      // Set if file was at one point downloaded and its plaintextHash was calculated+      bytes plaintextHash = 10;++      // Set if file has not been downloaded so its integrity has not been verified+      // From the sender of the attachment+      bytes encryptedDigest = 11;+    }++    // NB: This is the plaintext size, and empty content attachments are legal, so this+    // may be zero even if transitCdnKey or mediaName are set/nonempty.+    uint32 size = 3;++    // Either both transit cdn key and number are set or neither should be set.+    // Upload timestamp is optional but should only be set if key/number are set.+    optional string transitCdnKey = 4;+    optional uint32 transitCdnNumber = 5;+    optional uint64 transitTierUploadTimestamp = 6;++    // If present, the cdn number of the succesful upload to media tier.+    // If unset, may still have been uploaded, and clients+    // can discover the cdn number via the list endpoint.+    // Exporting clients should set this as long as their subscription+    // has not rotated since last upload; even if currently free tier.+    optional uint32 mediaTierCdnNumber = 7;++    reserved /*legacyMediaName*/ 8;++    // Separate key used to encrypt this file for the local backup.+    // Generally required for local backups.+    // Missing field indicates attachment was not available locally+    // when the backup was generated, but remote backup or transit+    // info was available.+    optional bytes localKey = 9;+  }++  reserved /*backupLocator*/ 1;+  reserved /*attachmentLocator*/ 2;+  reserved /*invalidAttachmentLocator*/ 3;+  reserved /*localLocator*/ 12;++  optional string contentType = 4;+  optional bytes incrementalMac = 5;+  optional uint32 incrementalMacChunkSize = 6;+  optional string fileName = 7;+  optional uint32 width = 8;+  optional uint32 height = 9;+  optional string caption = 10;+  optional string blurHash = 11;+  LocatorInfo locatorInfo = 13;+}++message Quote {+  enum Type {+    UNKNOWN = 0; // Interpret as "Normal"+    NORMAL = 1;+    GIFT_BADGE = 2;+    VIEW_ONCE = 3;+    POLL = 4;+  }++  message QuotedAttachment {+    optional string contentType = 1;+    optional string fileName = 2;+    optional MessageAttachment thumbnail = 3;+  }++  optional uint64 targetSentTimestamp = 1; // null if the target message could not be found at time of quote insert+  uint64 authorId = 2;+  optional Text text = 3;+  repeated QuotedAttachment attachments = 4;+  Type type = 5;+}++message BodyRange {+  enum Style {+    NONE = 0; // Importers should ignore the body range without throwing an error.+    BOLD = 1;+    ITALIC = 2;+    SPOILER = 3;+    STRIKETHROUGH = 4;+    MONOSPACE = 5;+  }++  // 'start' and 'length' are measured in UTF-16 code units.+  // They may refer to offsets in a longText attachment.+  uint32 start = 1;+  uint32 length = 2;++  // If unset, importers should ignore the body range without throwing an error.+  oneof associatedValue {+    bytes mentionAci = 3;+    Style style = 4;+  }+}++message Reaction {+  string emoji = 1;+  uint64 authorId = 2;+  uint64 sentTimestamp = 3;+  // A higher sort order means that a reaction is more recent. Some clients may export this as+  // incrementing numbers (e.g. 1, 2, 3), others as timestamps.+  uint64 sortOrder = 4;+}++message Poll {++  message PollOption {++    message PollVote {+      uint64 voterId = 1; // A direct reference to Recipient proto id. Must be self or contact.+      uint32 voteCount = 2; // Tracks how many times you voted.+    }++    string option = 1; // Between 1-100 characters+    repeated PollVote votes = 2;+  }++  string question = 1; // Between 1-100 characters+  bool allowMultiple = 2;+  repeated PollOption options = 3; // At least two+  bool hasEnded = 4;+  repeated Reaction reactions = 5;+}++message AdminDeletedMessage {+  uint64 adminId = 1; // id of the admin that deleted the message+}++message ChatUpdateMessage {+  // If unset, importers should ignore the update message without throwing an error.+  oneof update {+    SimpleChatUpdate simpleUpdate = 1;+    GroupChangeChatUpdate groupChange = 2;+    ExpirationTimerChatUpdate expirationTimerChange = 3;+    ProfileChangeChatUpdate profileChange = 4;+    ThreadMergeChatUpdate threadMerge = 5;+    SessionSwitchoverChatUpdate sessionSwitchover = 6;+    IndividualCall individualCall = 7;+    GroupCall groupCall = 8;+    LearnedProfileChatUpdate learnedProfileChange = 9;+    PollTerminateUpdate pollTerminate = 10;+    PinMessageUpdate pinMessage = 11;+  }+}++message IndividualCall {+  enum Type {+    UNKNOWN_TYPE = 0; // Interpret as "Audio call"+    AUDIO_CALL = 1;+    VIDEO_CALL = 2;+  }++  enum Direction {+    UNKNOWN_DIRECTION = 0; // Interpret as "Incoming"+    INCOMING = 1;+    OUTGOING = 2;+  }++  enum State {+    UNKNOWN_STATE = 0; // Interpret as "Accepted"+    ACCEPTED = 1;+    NOT_ACCEPTED = 2;+    // An incoming call that is no longer ongoing, which we neither accepted+    // not actively declined. For example, it expired, was canceled by the+    // sender, or was rejected due to being in another call.+    MISSED = 3;+    // We auto-declined an incoming call due to a notification profile.+    MISSED_NOTIFICATION_PROFILE = 4;+  }++  optional uint64 callId = 1;+  Type type = 2;+  Direction direction = 3;+  State state = 4;+  uint64 startedCallTimestamp = 5;+  bool read = 6;+}++message GroupCall {+  enum State {+    UNKNOWN_STATE = 0; // Interpret as "Generic"+    // A group call was started without ringing.+    GENERIC = 1;+    // We joined a group call that was started without ringing.+    JOINED = 2;+    // An incoming group call is actively ringing.+    RINGING = 3;+    // We accepted an incoming group ring.+    ACCEPTED = 4;+    // We declined an incoming group ring.+    DECLINED = 5;+    // We missed an incoming group ring, for example because it expired.+    MISSED = 6;+    // We auto-declined an incoming group ring due to a notification profile.+    MISSED_NOTIFICATION_PROFILE = 7;+    // An outgoing ring was started. We don't track any state for outgoing rings+    // beyond that they started.+    OUTGOING_RING = 8;+  }++  optional uint64 callId = 1;+  State state = 2;+  optional uint64 ringerRecipientId = 3;+  optional uint64 startedCallRecipientId = 4;+  uint64 startedCallTimestamp = 5;+  optional uint64 endedCallTimestamp = 6; // The time the call ended.+  bool read = 7;+}++message SimpleChatUpdate {+  enum Type {+    UNKNOWN = 0; // Importers should skip the update without throwing an error.+    JOINED_SIGNAL = 1;+    IDENTITY_UPDATE = 2;+    IDENTITY_VERIFIED = 3;+    IDENTITY_DEFAULT = 4; // marking as unverified+    CHANGE_NUMBER = 5;+    RELEASE_CHANNEL_DONATION_REQUEST = 6;+    END_SESSION = 7;+    CHAT_SESSION_REFRESH = 8;+    BAD_DECRYPT = 9;+    PAYMENTS_ACTIVATED = 10;+    PAYMENT_ACTIVATION_REQUEST = 11;+    UNSUPPORTED_PROTOCOL_MESSAGE = 12;+    REPORTED_SPAM = 13;+    BLOCKED = 14;+    UNBLOCKED = 15;+    MESSAGE_REQUEST_ACCEPTED = 16;+  }++  Type type = 1;+}++// For 1:1 chat updates only.+// For group thread updates use GroupExpirationTimerUpdate.+message ExpirationTimerChatUpdate {+  uint64 expiresInMs = 1; // 0 means the expiration timer was disabled+}++message ProfileChangeChatUpdate {+  string previousName = 1;+  string newName = 2;+}++message LearnedProfileChatUpdate {+  // If unset, importers should consider the previous name to be an empty string.+  oneof previousName {+    uint64 e164 = 1;+    string username = 2;+  }+}++message ThreadMergeChatUpdate {+  uint64 previousE164 = 1;+}++message SessionSwitchoverChatUpdate {+  uint64 e164 = 1;+}++message GroupChangeChatUpdate {+  message Update {+    // If unset, importers should consider it to be a GenericGroupUpdate with unset updaterAci+    oneof update {+      GenericGroupUpdate genericGroupUpdate = 1;+      GroupCreationUpdate groupCreationUpdate = 2;+      GroupNameUpdate groupNameUpdate = 3;+      GroupAvatarUpdate groupAvatarUpdate = 4;+      GroupDescriptionUpdate groupDescriptionUpdate = 5;+      GroupMembershipAccessLevelChangeUpdate groupMembershipAccessLevelChangeUpdate = 6;+      GroupAttributesAccessLevelChangeUpdate groupAttributesAccessLevelChangeUpdate = 7;+      GroupAnnouncementOnlyChangeUpdate groupAnnouncementOnlyChangeUpdate = 8;+      GroupAdminStatusUpdate groupAdminStatusUpdate = 9;+      GroupMemberLeftUpdate groupMemberLeftUpdate = 10;+      GroupMemberRemovedUpdate groupMemberRemovedUpdate = 11;+      SelfInvitedToGroupUpdate selfInvitedToGroupUpdate = 12;+      SelfInvitedOtherUserToGroupUpdate selfInvitedOtherUserToGroupUpdate = 13;+      GroupUnknownInviteeUpdate groupUnknownInviteeUpdate = 14;+      GroupInvitationAcceptedUpdate groupInvitationAcceptedUpdate = 15;+      GroupInvitationDeclinedUpdate groupInvitationDeclinedUpdate = 16;+      GroupMemberJoinedUpdate groupMemberJoinedUpdate = 17;+      GroupMemberAddedUpdate groupMemberAddedUpdate = 18;+      GroupSelfInvitationRevokedUpdate groupSelfInvitationRevokedUpdate = 19;+      GroupInvitationRevokedUpdate groupInvitationRevokedUpdate = 20;+      GroupJoinRequestUpdate groupJoinRequestUpdate = 21;+      GroupJoinRequestApprovalUpdate groupJoinRequestApprovalUpdate = 22;+      GroupJoinRequestCanceledUpdate groupJoinRequestCanceledUpdate = 23;+      GroupInviteLinkResetUpdate groupInviteLinkResetUpdate = 24;+      GroupInviteLinkEnabledUpdate groupInviteLinkEnabledUpdate = 25;+      GroupInviteLinkAdminApprovalUpdate groupInviteLinkAdminApprovalUpdate = 26;+      GroupInviteLinkDisabledUpdate groupInviteLinkDisabledUpdate = 27;+      GroupMemberJoinedByLinkUpdate groupMemberJoinedByLinkUpdate = 28;+      GroupV2MigrationUpdate groupV2MigrationUpdate = 29;+      GroupV2MigrationSelfInvitedUpdate groupV2MigrationSelfInvitedUpdate = 30;+      GroupV2MigrationInvitedMembersUpdate groupV2MigrationInvitedMembersUpdate = 31;+      GroupV2MigrationDroppedMembersUpdate groupV2MigrationDroppedMembersUpdate = 32;+      GroupSequenceOfRequestsAndCancelsUpdate groupSequenceOfRequestsAndCancelsUpdate = 33;+      GroupExpirationTimerUpdate groupExpirationTimerUpdate = 34;+      GroupMemberLabelAccessLevelChangeUpdate groupMemberLabelAccessLevelChangeUpdate = 35;+      GroupTerminateChangeUpdate groupTerminateChangeUpdate = 36;+    }+  }++  // Must be one or more; all updates batched together came from+  // a single batched group state update.+  repeated Update updates = 1;+}++message GenericGroupUpdate {+  optional bytes updaterAci = 1;+}++message GroupCreationUpdate {+  optional bytes updaterAci = 1;+}++message GroupNameUpdate {+  optional bytes updaterAci = 1;+  // Null value means the group name was removed.+  optional string newGroupName = 2;+}++message GroupAvatarUpdate {+  optional bytes updaterAci = 1;+  bool wasRemoved = 2;+}++message GroupDescriptionUpdate {+  optional bytes updaterAci = 1;+  // Null value means the group description was removed.+  optional string newDescription = 2;+}++enum GroupV2AccessLevel {+  UNKNOWN = 0; // Interpret as "Unsatisfiable"+  ANY = 1;+  MEMBER = 2;+  ADMINISTRATOR = 3;+  UNSATISFIABLE = 4;+}++message GroupMembershipAccessLevelChangeUpdate {+  optional bytes updaterAci = 1;+  GroupV2AccessLevel accessLevel = 2;+}++message GroupAttributesAccessLevelChangeUpdate {+  optional bytes updaterAci = 1;+  GroupV2AccessLevel accessLevel = 2;+}++message GroupMemberLabelAccessLevelChangeUpdate {+  optional bytes updaterAci = 1;+  GroupV2AccessLevel accessLevel = 2;+}++message GroupTerminateChangeUpdate {+  optional bytes updaterAci = 1;+}++message GroupAnnouncementOnlyChangeUpdate {+  optional bytes updaterAci = 1;+  bool isAnnouncementOnly = 2;+}++message GroupAdminStatusUpdate {+  optional bytes updaterAci = 1;+  // The aci who had admin status granted or revoked.+  bytes memberAci = 2;+  bool wasAdminStatusGranted = 3;+}++message GroupMemberLeftUpdate {+  bytes aci = 1;+}++message GroupMemberRemovedUpdate {+  optional bytes removerAci = 1;+  bytes removedAci = 2;+}++message SelfInvitedToGroupUpdate {+  optional bytes inviterAci = 1;+}++message SelfInvitedOtherUserToGroupUpdate {+  // If no invitee id available, use GroupUnknownInviteeUpdate+  bytes inviteeServiceId = 1;+}++message GroupUnknownInviteeUpdate {+  // Can be the self user.+  optional bytes inviterAci = 1;+  uint32 inviteeCount = 2;+}++message GroupInvitationAcceptedUpdate {+  optional bytes inviterAci = 1;+  bytes newMemberAci = 2;+}++message GroupInvitationDeclinedUpdate {+  optional bytes inviterAci = 1;+  // Note: if invited by pni, just set inviteeAci to nil.+  optional bytes inviteeAci = 2;+}++message GroupMemberJoinedUpdate {+  bytes newMemberAci = 1;+}++message GroupMemberAddedUpdate {+  optional bytes updaterAci = 1;+  bytes newMemberAci = 2;+  bool hadOpenInvitation = 3;+  // If hadOpenInvitation is true, optionally include aci of the inviter.+  optional bytes inviterAci = 4;+}++// An invitation to self was revoked.+message GroupSelfInvitationRevokedUpdate {+  optional bytes revokerAci = 1;+}++// These invitees should never be the local user.+// Use GroupSelfInvitationRevokedUpdate in those cases.+// The inviter or updater can be the local user.+message GroupInvitationRevokedUpdate {+  message Invitee {+    optional bytes inviterAci = 1;+    // Prefer to use aci over pni. No need to set+    // pni if aci is set. Both can be missing.+    optional bytes inviteeAci = 2;+    optional bytes inviteePni = 3;+  }++  // The member that revoked the invite(s), not the inviter!+  // Assumed to be an admin (at the time, may no longer be an+  // admin or even a member).+  optional bytes updaterAci = 1;+  repeated Invitee invitees = 2;+}++message GroupJoinRequestUpdate {+  bytes requestorAci = 1;+}++message GroupJoinRequestApprovalUpdate {+  bytes requestorAci = 1;+  // The aci that approved or rejected the request.+  optional bytes updaterAci = 2;+  bool wasApproved = 3;+}++message GroupJoinRequestCanceledUpdate {+  bytes requestorAci = 1;+}++// A single requestor has requested to join and cancelled+// their request repeatedly with no other updates in between.+// The last action encompassed by this update is always a+// cancellation; if there was another open request immediately+// after, it will be a separate GroupJoinRequestUpdate, either+// in the same frame or in a subsequent frame.+message GroupSequenceOfRequestsAndCancelsUpdate {+  bytes requestorAci = 1;+  uint32 count = 2;+}++message GroupInviteLinkResetUpdate {+  optional bytes updaterAci = 1;+}++message GroupInviteLinkEnabledUpdate {+  optional bytes updaterAci = 1;+  bool linkRequiresAdminApproval = 2;+}++message GroupInviteLinkAdminApprovalUpdate {+  optional bytes updaterAci = 1;+  bool linkRequiresAdminApproval = 2;+}++message GroupInviteLinkDisabledUpdate {+  optional bytes updaterAci = 1;+}++message GroupMemberJoinedByLinkUpdate {+  bytes newMemberAci = 1;+}++// A gv1->gv2 migration occurred.+message GroupV2MigrationUpdate {}++// Another user migrated gv1->gv2 but was unable to add+// the local user and invited them instead.+message GroupV2MigrationSelfInvitedUpdate {}++// The local user migrated gv1->gv2 but was unable to+// add some members and invited them instead.+// (Happens if we don't have the invitee's profile key)+message GroupV2MigrationInvitedMembersUpdate {+  uint32 invitedMembersCount = 1;+}++// The local user migrated gv1->gv2 but was unable to+// add or invite some members and dropped them instead.+// (Happens for e164 members where we don't have an aci).+message GroupV2MigrationDroppedMembersUpdate {+  uint32 droppedMembersCount = 1;+}++// For 1:1 timer updates, use ExpirationTimerChatUpdate.+message GroupExpirationTimerUpdate {+  uint64 expiresInMs = 1; // 0 means the expiration timer was disabled+  optional bytes updaterAci = 2;+}++message PollTerminateUpdate {+  uint64 targetSentTimestamp = 1;+  string question = 2; // Between 1-100 characters+}++message PinMessageUpdate {+  uint64 targetSentTimestamp = 1;+  uint64 authorId = 2; // recipient id+}++message StickerPack {+  bytes packId = 1;+  bytes packKey = 2;+}++message ChatStyle {+  message Gradient {+    uint32 angle = 1; // degrees+    repeated fixed32 colors = 2; // 0xAARRGGBB+    repeated float positions = 3; // percent from 0 to 1+  }++  message CustomChatColor {+    uint64 id = 1;++    // If unset, use the default chat color+    oneof color {+      fixed32 solid = 2; // 0xAARRGGBB+      Gradient gradient = 3;+    }+  }++  message AutomaticBubbleColor {+  }++  enum WallpaperPreset {+    UNKNOWN_WALLPAPER_PRESET = 0; // Interpret as the wallpaper being unset+    SOLID_BLUSH = 1;+    SOLID_COPPER = 2;+    SOLID_DUST = 3;+    SOLID_CELADON = 4;+    SOLID_RAINFOREST = 5;+    SOLID_PACIFIC = 6;+    SOLID_FROST = 7;+    SOLID_NAVY = 8;+    SOLID_LILAC = 9;+    SOLID_PINK = 10;+    SOLID_EGGPLANT = 11;+    SOLID_SILVER = 12;+    GRADIENT_SUNSET = 13;+    GRADIENT_NOIR = 14;+    GRADIENT_HEATMAP = 15;+    GRADIENT_AQUA = 16;+    GRADIENT_IRIDESCENT = 17;+    GRADIENT_MONSTERA = 18;+    GRADIENT_BLISS = 19;+    GRADIENT_SKY = 20;+    GRADIENT_PEACH = 21;+  }++  enum BubbleColorPreset {+    UNKNOWN_BUBBLE_COLOR_PRESET = 0; // Interpret as the user's default chat bubble color+    SOLID_ULTRAMARINE = 1;+    SOLID_CRIMSON = 2;+    SOLID_VERMILION = 3;+    SOLID_BURLAP = 4;+    SOLID_FOREST = 5;+    SOLID_WINTERGREEN = 6;+    SOLID_TEAL = 7;+    SOLID_BLUE = 8;+    SOLID_INDIGO = 9;+    SOLID_VIOLET = 10;+    SOLID_PLUM = 11;+    SOLID_TAUPE = 12;+    SOLID_STEEL = 13;+    GRADIENT_EMBER = 14;+    GRADIENT_MIDNIGHT = 15;+    GRADIENT_INFRARED = 16;+    GRADIENT_LAGOON = 17;+    GRADIENT_FLUORESCENT = 18;+    GRADIENT_BASIL = 19;+    GRADIENT_SUBLIME = 20;+    GRADIENT_SEA = 21;+    GRADIENT_TANGERINE = 22;+  }++  // If unset, importers should consider there to be no wallpaper.+  oneof wallpaper {+    WallpaperPreset wallpaperPreset = 1;+    // This `FilePointer` is expected not to contain a `fileName`, `width`,+    // `height`, or `caption`.+    FilePointer wallpaperPhoto = 2;+  }++  // If unset, importers should consider it to be AutomaticBubbleColor+  oneof bubbleColor {+    // Bubble setting is automatically determined based on the wallpaper setting,+    // or `SOLID_ULTRAMARINE` for `noWallpaper`+    AutomaticBubbleColor autoBubbleColor = 3;+    BubbleColorPreset bubbleColorPreset = 4;++    // See AccountSettings.customChatColors+    uint64 customColorId = 5;+  }++  bool dimWallpaperInDarkMode = 7;+}++message NotificationProfile {+  enum DayOfWeek {+    UNKNOWN = 0; // Interpret as "Monday"+    MONDAY = 1;+    TUESDAY = 2;+    WEDNESDAY = 3;+    THURSDAY = 4;+    FRIDAY = 5;+    SATURDAY = 6;+    SUNDAY = 7;+  }++  string name = 1;+  optional string emoji = 2;+  fixed32 color = 3; // 0xAARRGGBB+  uint64 createdAtMs = 4;+  bool allowAllCalls = 5;+  bool allowAllMentions = 6;+  repeated uint64 allowedMembers = 7; // generated recipient id for allowed groups and contacts+  bool scheduleEnabled = 8;+  uint32 scheduleStartTime = 9; // 24-hour clock int, 0000-2359 (e.g., 15, 900, 1130, 2345)+  uint32 scheduleEndTime = 10; // 24-hour clock int, 0000-2359 (e.g., 15, 900, 1130, 2345)+  repeated DayOfWeek scheduleDaysEnabled = 11;+  bytes id = 12; // should be 16 bytes+}++message ChatFolder {+  // Represents the default "All chats" folder record vs all other custom folders+  enum FolderType {+    UNKNOWN = 0; // Interpret as "Custom"+    ALL = 1;+    CUSTOM = 2;+  }++  string name = 1;+  bool showOnlyUnread = 2;+  bool showMutedChats = 3;+  // Folder includes all 1:1 chats, unless excluded+  bool includeAllIndividualChats = 4;+  // Folder includes all group chats, unless excluded+  bool includeAllGroupChats = 5;+  FolderType folderType = 6;+  repeated uint64 includedRecipientIds = 7; // generated recipient id of groups, contacts, and/or note to self+  repeated uint64 excludedRecipientIds = 8; // generated recipient id of groups, contacts, and/or note to self+  bytes id = 9; // should be 16 bytes+}