1package com.peachpasswords.sync23import kotlinx.serialization.SerialName4import kotlinx.serialization.Serializable5import kotlinx.serialization.encodeToString6import kotlinx.serialization.json.Json78910111213141516171819202122@Serializable23sealed class AdoptionFrame {24 25262728293031323334 @Serializable35 @SerialName("ADOPT_REQUEST")36 data class Request(37 @SerialName("device_id") val sessionRequestId: String,38 @SerialName("device_name") val deviceName: String,39 @SerialName("device_type") val deviceType: String,40 val license: String? = null,41 @SerialName("snapshot_capable") val snapshotCapable: Boolean? = null,42 ) : AdoptionFrame()4344 @Serializable45 @SerialName("ADOPT_CONFIRM")46 data class Confirm(47 val confirmed: Boolean,48 ) : AdoptionFrame()4950 @Serializable51 @SerialName("ADOPT_GRANT")52 data class Grant(53 @SerialName("root_key_hex") val rootKeyHex: String,54 @SerialName("vault_id") val vaultId: String,55 val license: String? = null,56 val source: Source,57 58 59 60 61 62 63 64 @SerialName("snapshot_capable") val snapshotCapable: Boolean = false,65 ) : AdoptionFrame()6667 @Serializable68 @SerialName("ADOPT_IDENTITY")69 data class Identity(70 @SerialName("device_id") val deviceId: String,71 @SerialName("device_name") val deviceName: String,72 @SerialName("device_type") val deviceType: String,73 @SerialName("long_term_public_key_hex") val longTermPublicKeyHex: String,74 @SerialName("signing_public_key_hex") val signingPublicKeyHex: String? = null,75 ) : AdoptionFrame()7677 7879808182 @Serializable83 @SerialName("ADOPT_COMPLETE")84 data object Complete : AdoptionFrame()8586 87 @Serializable88 @SerialName("ADOPT_APPLIED")89 data object Applied : AdoptionFrame()9091 92 @Serializable93 @SerialName("ADOPT_REJECT")94 data class Reject(95 val reason: String,96 ) : AdoptionFrame()9798 99100101102103 @Serializable104 @SerialName("ADOPT_SNAPSHOT")105 data class Snapshot(106 @SerialName("chunk_index") val chunkIndex: Int,107 @SerialName("chunk_count") val chunkCount: Int,108 val entries: Map<String, String>,109 val tombstones: Map<String, Long>,110 @SerialName("duress_slot") val duressSlot: String? = null,111 ) : AdoptionFrame()112113 114 @Serializable115 @SerialName("ADOPT_SNAPSHOT_APPLIED")116 data class SnapshotApplied(117 @SerialName("entries_received") val entriesReceived: Int,118 @SerialName("tombstones_received") val tombstonesReceived: Int,119 ) : AdoptionFrame()120121 122 @Serializable123 @SerialName("ADOPT_DEVICE_MANIFEST")124 data class DeviceManifestFrame(125 val manifest: SignedDeviceManifest,126 ) : AdoptionFrame()127128 129 @Serializable130 @SerialName("ADOPT_DEVICE_MANIFEST_APPLIED")131 data object DeviceManifestApplied : AdoptionFrame()132133 @Serializable134 data class Source(135 @SerialName("device_id") val deviceId: String,136 @SerialName("device_name") val deviceName: String,137 @SerialName("device_type") val deviceType: String,138 @SerialName("long_term_public_key_hex") val longTermPublicKeyHex: String,139 @SerialName("signing_public_key_hex") val signingPublicKeyHex: String? = null,140 @SerialName("ws_port") val wsPort: Int? = null,141 @SerialName("relay_url") val relayUrl: String? = null,142 )143}144145data class AdoptionPairState(146 val rendezvousSecretHex: String,147 val relayUrl: String? = null,148)149150151152153154155data class ReceivedSnapshot(156 val entries: Map<String, String>,157 val tombstones: Map<String, Long>,158 val duressSlot: String? = null,159)160161162163164165166167const val MAX_SNAPSHOT_CHUNK_BYTES = 512 * 1024 168const val MAX_SNAPSHOT_CHUNKS = 200169170171172internal const val SNAPSHOT_FRAME_WIRE_CEILING = MAX_SNAPSHOT_CHUNK_BYTES + 256 * 1024173internal val MAX_PADDED_SNAPSHOT_FRAME_BYTES = SyncPadding.bucket(SNAPSHOT_FRAME_WIRE_CEILING + 4)174175176177178179180181const val MAX_ADOPT_SNAPSHOT_BYTES = 10 * 1024 * 1024 182const val MAX_ADOPT_SNAPSHOT_ENTRIES = 25_000183const val MAX_ADOPT_SNAPSHOT_TOMBSTONES = 25_000184185const val MAX_ADOPT_SNAPSHOT_ID_CHARS = SyncLimits.MAX_ID_LENGTH186187188189190191const val MAX_ADOPT_SNAPSHOT_ENVELOPE_BYTES = SyncLimits.MAX_ENTRY_ENVELOPE_BYTES192193194195196197class AdoptSnapshotBudget {198 val entries = LinkedHashMap<String, String>()199 val tombstones = LinkedHashMap<String, Long>()200 var duressSlot: String? = null201 202 var bytes: Int = 0203 var entryCount: Int = 0204 var tombstoneCount: Int = 0205}206207fun createAdoptSnapshotBudget(): AdoptSnapshotBudget = AdoptSnapshotBudget()208209210211212213214215216217218219fun applyAdoptSnapshotFrame(220 acc: AdoptSnapshotBudget,221 entries: Map<String, String>,222 tombstones: Map<String, Long>,223 duressSlot: String?,224 frameBytes: Int,225) {226 if (frameBytes > MAX_ADOPT_SNAPSHOT_BYTES - acc.bytes) {227 throw IllegalStateException("ADOPT_SNAPSHOT_OVER_BUDGET")228 }229 for ((id, envelope) in entries) {230 if (id.length > MAX_ADOPT_SNAPSHOT_ID_CHARS) throw IllegalStateException("ADOPT_SNAPSHOT_ID_TOO_LONG")231 if (envelope.length > MAX_ADOPT_SNAPSHOT_ENVELOPE_BYTES) {232 throw IllegalStateException("ADOPT_SNAPSHOT_ENVELOPE_TOO_LARGE")233 }234 if (acc.entryCount >= MAX_ADOPT_SNAPSHOT_ENTRIES) {235 throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_ENTRIES")236 }237 acc.entryCount++238 acc.entries[id] = envelope239 }240 for ((id, ts) in tombstones) {241 if (id.length > MAX_ADOPT_SNAPSHOT_ID_CHARS) throw IllegalStateException("ADOPT_SNAPSHOT_ID_TOO_LONG")242 243 244 if (acc.tombstoneCount >= MAX_ADOPT_SNAPSHOT_TOMBSTONES) {245 throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_TOMBSTONES")246 }247 acc.tombstoneCount++248 acc.tombstones[id] = ts249 }250 if (!duressSlot.isNullOrEmpty()) {251 252 253 if (duressSlot.length > SNAPSHOT_FRAME_WIRE_CEILING) {254 throw IllegalStateException("ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE")255 }256 acc.duressSlot = duressSlot257 }258 acc.bytes += frameBytes259}260261262interface AdoptionReceiverDeps {263 val deviceName: String264 val deviceType: DeviceType265 fun generateDeviceId(): String266 267 suspend fun confirmSas(): Boolean268 269270271272 suspend fun validateSource(source: AdoptionFrame.Source) {}273274 275276277278279 suspend fun hasSourceIdentityCollision(source: AdoptionFrame.Source): Boolean = false280281 282 suspend fun createVaultFromRootKey(rootKeyHex: String): String283 284 suspend fun deriveLocalIdentity(): LocalDeviceIdentity285 286 suspend fun upsertPairedDeviceAndClearRevocation(device: PairedDevice) {287 upsertPairedDevice(device)288 clearPairedDeviceRevocation(device.deviceId)289 }290 suspend fun clearPairedDeviceRevocation(deviceId: String) {}291 suspend fun upsertPairedDevice(device: PairedDevice)292 suspend fun applyLicense(license: String) {}293 294 suspend fun license(): String? = null295 val pairState: AdoptionPairState? get() = null296 fun onError(error: String)297 298 suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String? = null) {}299 300301302303304305306307 suspend fun applyIncomingDeviceManifest(308 manifest: SignedDeviceManifest,309 authenticatedRemoteStaticPublicKey: ByteArray,310 ) {}311 312 suspend fun markSynced(deviceId: String) {}313}314315316interface AdoptionSourceDeps {317 val sourceIdentity: LocalDeviceIdentity318 suspend fun rootKeyHex(): String319 suspend fun vaultId(): String320 suspend fun license(): String? = null321 322 suspend fun applyLicense(license: String) {}323324 325326327328329330 suspend fun onConsent(request: AdoptionFrame.Request): Boolean331 suspend fun upsertPairedDevice(device: PairedDevice)332 fun hasDeviceIdentityCollision(device: PairedDevice): Boolean = false333 334335336337338 suspend fun rotateSourceIdentity(): LocalDeviceIdentity = error("rotateSourceIdentity not wired")339 val pairState: AdoptionPairState? get() = null340 341 suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? = null342 343 suspend fun outgoingDeviceManifest(): SignedDeviceManifest? = null344 345 suspend fun markSynced(deviceId: String) {}346 347 suspend fun duressSlotJson(): String? = null348}349350private val Hex64 = Regex("^[0-9a-f]{64}\$")351352fun validateRootKeyHex(rootKeyHex: String?): Boolean = rootKeyHex != null && Hex64.matches(rootKeyHex)353354fun isAdoptRequest(frame: AdoptionFrame?): Boolean =355 frame is AdoptionFrame.Request &&356 frame.sessionRequestId.isNotEmpty() &&357 isDeviceType(frame.deviceType)358359fun isAdoptGrant(frame: AdoptionFrame?): Boolean =360 frame is AdoptionFrame.Grant &&361 validateRootKeyHex(frame.rootKeyHex) &&362 Hex64.matches(frame.vaultId) &&363 isDeviceType(frame.source.deviceType) &&364 Hex64.matches(frame.source.longTermPublicKeyHex) &&365 (frame.source.relayUrl == null ||366 runCatching { Rendezvous.normalizeRelayUrl(frame.source.relayUrl) }.isSuccess)367368fun isAdoptConfirm(frame: AdoptionFrame?): Boolean =369 frame is AdoptionFrame.Confirm370371fun isAdoptIdentity(frame: AdoptionFrame?): Boolean =372 frame is AdoptionFrame.Identity &&373 frame.deviceId.isNotEmpty() &&374 isDeviceType(frame.deviceType) &&375 Hex64.matches(frame.longTermPublicKeyHex)376377fun isAdoptComplete(frame: AdoptionFrame?): Boolean =378 frame is AdoptionFrame.Complete379380fun isAdoptApplied(frame: AdoptionFrame?): Boolean =381 frame is AdoptionFrame.Applied382383fun isAdoptReject(frame: AdoptionFrame?): Boolean =384 frame is AdoptionFrame.Reject &&385 (frame.reason == "ADOPT_PRO_REQUIRED" || frame.reason == "ADOPT_DEVICE_ID_COLLISION")386387fun isAdoptSnapshot(frame: AdoptionFrame?): Boolean =388 frame is AdoptionFrame.Snapshot &&389 frame.chunkIndex >= 0 &&390 frame.chunkCount >= 1391392393394395396397398399suspend fun requestAdoption(400 channel: PairingTransport,401 deps: AdoptionReceiverDeps,402 403 404 405 406 407 onGrant: ((AdoptionFrame.Grant) -> Unit)? = null,408 nowMs: () -> Long = { System.currentTimeMillis() },409): PairedDevice? {410 val receiverLicense = deps.license()411 412 413 sendFrame(channel, AdoptionFrame.Request(414 sessionRequestId = deps.generateDeviceId(),415 deviceName = deps.deviceName,416 deviceType = deps.deviceType.wireValue,417 license = receiverLicense,418 snapshotCapable = true,419 ))420421 val confirmed = deps.confirmSas()422 sendFrame(channel, AdoptionFrame.Confirm(confirmed))423 if (!confirmed) {424 deps.onError("ADOPT_SAS_REJECTED")425 return null426 }427428 val frame = receiveFrame(channel)429 if (isAdoptReject(frame)) {430 deps.onError((frame as AdoptionFrame.Reject).reason)431 return null432 }433 if (!isAdoptGrant(frame)) {434 deps.onError("ADOPT_UNEXPECTED_FRAME")435 return null436 }437 val grant = frame as AdoptionFrame.Grant438 onGrant?.invoke(grant)439440 val rootKeyBytes = hexToPubkey(grant.rootKeyHex)441 try {442 if (computeVaultId(rootKeyBytes) != grant.vaultId) {443 deps.onError("ADOPT_VAULT_ID_MISMATCH")444 return null445 }446 } finally {447 rootKeyBytes.fill(0)448 }449 if (receiverLicense == null && grant.license == null) {450 deps.onError("ADOPT_PRO_REQUIRED")451 return null452 }453454 deps.validateSource(grant.source)455456 457 458 459 460 461 var acceptedGrant = grant462 if (deps.hasSourceIdentityCollision(acceptedGrant.source)) {463 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))464 val retry = receiveFrame(channel)465 if (!isAdoptGrant(retry)) {466 deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")467 return null468 }469 acceptedGrant = retry as AdoptionFrame.Grant470 if (deps.hasSourceIdentityCollision(acceptedGrant.source)) {471 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))472 deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")473 return null474 }475 476 val freshRootBytes = hexToPubkey(acceptedGrant.rootKeyHex)477 try {478 if (computeVaultId(freshRootBytes) != acceptedGrant.vaultId) {479 deps.onError("ADOPT_VAULT_ID_MISMATCH")480 return null481 }482 } finally {483 freshRootBytes.fill(0)484 }485 }486 if (receiverLicense == null && acceptedGrant.license == null) {487 deps.onError("ADOPT_PRO_REQUIRED")488 return null489 }490491492 if (receiverLicense == null) {493 acceptedGrant.license?.let { deps.applyLicense(it) }494 }495 val vaultId = deps.createVaultFromRootKey(acceptedGrant.rootKeyHex)496 if (vaultId != acceptedGrant.vaultId) {497 deps.onError("ADOPT_VAULT_ID_MISMATCH")498 return null499 }500501502 val identity = deps.deriveLocalIdentity()503 sendFrame(channel, AdoptionFrame.Identity(504 deviceId = identity.deviceId,505 deviceName = identity.deviceName,506 deviceType = identity.deviceType.wireValue,507 longTermPublicKeyHex = identity.longTermPublicKeyHex,508 signingPublicKeyHex = identity.signingPublicKeyHex,509 ))510511 if (!isAdoptComplete(receiveFrame(channel))) {512 deps.onError("ADOPT_COMPLETION_MISSING")513 return null514 }515516 val sourceDevice = PairedDevice(517 deviceId = acceptedGrant.source.deviceId,518 deviceName = acceptedGrant.source.deviceName,519 deviceType = acceptedGrant.source.deviceType,520 longTermPublicKeyHex = acceptedGrant.source.longTermPublicKeyHex,521 signingPublicKeyHex = acceptedGrant.source.signingPublicKeyHex,522 trustSource = "direct",523 wsPort = acceptedGrant.source.wsPort,524 rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,525 relayUrl = deps.pairState?.relayUrl ?: acceptedGrant.source.relayUrl,526 pairedAt = nowMs(),527 )528 529 530 531 deps.upsertPairedDeviceAndClearRevocation(sourceDevice)532 sendFrame(channel, AdoptionFrame.Applied)533 return sourceDevice534}535536537538539540541suspend fun grantAdoption(542 channel: PairingTransport,543 request: AdoptionFrame.Request,544 deps: AdoptionSourceDeps,545 nowMs: () -> Long = { System.currentTimeMillis() },546): PairedDevice? {547 if (!deps.onConsent(request)) return null548549 val confirmation = receiveFrame(channel)550 if (!isAdoptConfirm(confirmation) || !(confirmation as AdoptionFrame.Confirm).confirmed) {551 return null552 }553554 var sourceLicense = deps.license()555 if (sourceLicense == null && request.license != null) {556 sourceLicense = runCatching {557 deps.applyLicense(request.license)558 deps.license()559 }.getOrNull()560 }561 if (sourceLicense == null) {562 sendFrame(channel, AdoptionFrame.Reject("ADOPT_PRO_REQUIRED"))563 throw IllegalStateException("ADOPT_PRO_REQUIRED")564 }565566 val rootKeyHex = deps.rootKeyHex()567 if (!validateRootKeyHex(rootKeyHex)) throw IllegalStateException("ADOPT_INVALID_ROOT_KEY")568569 var sourceIdentity = deps.sourceIdentity570 var grantAttempts = 0571 while (true) {572 sendFrame(channel, AdoptionFrame.Grant(573 rootKeyHex = rootKeyHex,574 vaultId = deps.vaultId(),575 license = sourceLicense,576 source = AdoptionFrame.Source(577 deviceId = sourceIdentity.deviceId,578 deviceName = sourceIdentity.deviceName,579 deviceType = sourceIdentity.deviceType.wireValue,580 longTermPublicKeyHex = sourceIdentity.longTermPublicKeyHex,581 signingPublicKeyHex = sourceIdentity.signingPublicKeyHex,582 wsPort = sourceIdentity.wsPort,583 relayUrl = deps.pairState?.relayUrl,584 ),585 snapshotCapable = request.snapshotCapable == true,586 ))587588 var identity = receiveFrame(channel)589590 591 592 if (identity is AdoptionFrame.Reject &&593 identity.reason == "ADOPT_DEVICE_ID_COLLISION" &&594 grantAttempts == 0595 ) {596 sourceIdentity = deps.rotateSourceIdentity()597 grantAttempts++598 continue599 }600601 if (!isAdoptIdentity(identity)) return null602 identity as AdoptionFrame.Identity603604 var device = PairedDevice(605 deviceId = identity.deviceId,606 deviceName = identity.deviceName,607 deviceType = identity.deviceType,608 longTermPublicKeyHex = identity.longTermPublicKeyHex,609 signingPublicKeyHex = identity.signingPublicKeyHex,610 trustSource = "direct",611 rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,612 relayUrl = deps.pairState?.relayUrl,613 pairedAt = nowMs(),614 )615 if (deps.hasDeviceIdentityCollision(device)) {616 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))617 identity = receiveFrame(channel)618 if (!isAdoptIdentity(identity)) return null619 identity as AdoptionFrame.Identity620 device = device.copy(621 deviceId = identity.deviceId,622 deviceName = identity.deviceName,623 deviceType = identity.deviceType,624 longTermPublicKeyHex = identity.longTermPublicKeyHex,625 signingPublicKeyHex = identity.signingPublicKeyHex,626 )627 if (deps.hasDeviceIdentityCollision(device)) {628 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))629 return null630 }631 }632 deps.upsertPairedDevice(device)633 sendFrame(channel, AdoptionFrame.Complete)634 if (!isAdoptApplied(receiveFrame(channel))) return null635 return device636 }637}638639640641642643644val AdoptJson: Json = Json {645 classDiscriminator = "type"646 encodeDefaults = false647 ignoreUnknownKeys = true648}649650suspend fun sendFrame(channel: PairingTransport, frame: AdoptionFrame) {651 channel.send(AdoptJson.encodeToString(AdoptionFrame.serializer(), frame).toByteArray(Charsets.UTF_8))652}653654655suspend fun receiveFrame(channel: PairingTransport): AdoptionFrame? =656 runCatching {657 AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(channel.receive(), Charsets.UTF_8))658 }.getOrNull()659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690suspend fun sendVaultSnapshot(691 channel: PairingTransport,692 entries: Map<String, String>,693 tombstones: Map<String, Long>,694 duressSlot: String? = null,695) {696 val frames = buildAdoptSnapshotFrames(entries, tombstones, duressSlot)697 698 699 700 701 702 val acc = createAdoptSnapshotBudget()703 val encoded = frames.map {704 AdoptJson.encodeToString(AdoptionFrame.serializer(), it).encodeToByteArray()705 }706 for (i in frames.indices) {707 val frame = frames[i]708 applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, encoded[i].size)709 }710 for (raw in encoded) channel.send(SyncPadding.pad(raw))711}712713714715716717718private fun buildAdoptSnapshotFrames(719 entries: Map<String, String>,720 tombstones: Map<String, Long>,721 duressSlot: String?,722): List<AdoptionFrame.Snapshot> {723 val includeDuress = !duressSlot.isNullOrBlank()724 725 726 val entryCap = MAX_SNAPSHOT_CHUNKS - 1727728 val chunks = mutableListOf<Map<String, String>>()729 var current = LinkedHashMap<String, String>()730 var currentBytes = 2 731 for ((id, envelope) in entries) {732 733 val entryBytes = AdoptJson.encodeToString(mapOf(id to envelope)).length + 1734 if (current.isNotEmpty() && currentBytes + entryBytes >= MAX_SNAPSHOT_CHUNK_BYTES) {735 chunks.add(current)736 current = LinkedHashMap()737 currentBytes = 2738 }739 current[id] = envelope740 currentBytes += entryBytes741 }742 chunks.add(current)743744 val entriesChunkCount = minOf(chunks.size, entryCap)745 val totalChunks = entriesChunkCount + 1746 val supplementalFrame = AdoptionFrame.Snapshot(747 chunkIndex = entriesChunkCount,748 chunkCount = totalChunks,749 entries = emptyMap(),750 tombstones = tombstones,751 duressSlot = duressSlot.takeIf { includeDuress },752 )753754 if (755 AdoptJson.encodeToString(AdoptionFrame.serializer(), supplementalFrame)756 .encodeToByteArray().size > SNAPSHOT_FRAME_WIRE_CEILING757 ) {758 if (includeDuress) throw SnapshotDuressFrameTooLargeException()759 throw IllegalStateException("ADOPT_SNAPSHOT_SUPPLEMENTAL_FRAME_TOO_LARGE")760 }761762 val frames = mutableListOf<AdoptionFrame.Snapshot>()763 for (index in 0 until entriesChunkCount) {764 frames.add(AdoptionFrame.Snapshot(765 chunkIndex = index,766 chunkCount = totalChunks,767 entries = chunks[index],768 tombstones = emptyMap(),769 duressSlot = null,770 ))771 }772 frames.add(supplementalFrame)773 return frames774}775776internal class SnapshotDuressFrameTooLargeException :777 IllegalStateException("ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE")778779780781782783784785786787788789790suspend fun receiveVaultSnapshot(791 channel: PairingTransport,792): ReceivedSnapshot {793 val acc = createAdoptSnapshotBudget()794 var chunkCount = -1795 var received = 0796 while (chunkCount == -1 || received < chunkCount) {797 val wire = channel.receive()798 if (wire.size > MAX_PADDED_SNAPSHOT_FRAME_BYTES) {799 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")800 }801 val raw = runCatching { SyncPadding.unpad(wire) }802 .getOrElse { throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME", it) }803 if (raw.size > MAX_ADOPT_SNAPSHOT_BYTES - acc.bytes) {804 throw IllegalStateException("ADOPT_SNAPSHOT_OVER_BUDGET")805 }806 if (raw.size > SNAPSHOT_FRAME_WIRE_CEILING) {807 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")808 }809 val frame = runCatching {810 AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(raw, Charsets.UTF_8))811 }.getOrNull()812 if (!isAdoptSnapshot(frame)) throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME")813 frame as AdoptionFrame.Snapshot814 if (chunkCount == -1) {815 chunkCount = frame.chunkCount816 if (chunkCount > MAX_SNAPSHOT_CHUNKS) {817 throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_CHUNKS")818 }819 } else if (frame.chunkCount != chunkCount) {820 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_COUNT_MISMATCH")821 }822 if (frame.chunkIndex != received) {823 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_OUT_OF_ORDER")824 }825 applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, raw.size)826 received++827 }828 return ReceivedSnapshot(acc.entries, acc.tombstones, acc.duressSlot)829}830831private fun isDeviceType(value: String): Boolean =832 DeviceType.entries.any { it.wireValue == value }