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 suspend fun deriveLocalIdentity(): LocalDeviceIdentity284 285 suspend fun clearPairedDeviceRevocation(deviceId: String) {}286 suspend fun upsertPairedDevice(device: PairedDevice)287 suspend fun applyLicense(license: String) {}288 289 suspend fun license(): String? = null290 val pairState: AdoptionPairState? get() = null291 fun onError(error: String)292 293 suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String? = null) {}294 295296297298299300301302 suspend fun applyIncomingDeviceManifest(303 manifest: SignedDeviceManifest,304 authenticatedRemoteStaticPublicKey: ByteArray,305 ) {}306 307 suspend fun markSynced(deviceId: String) {}308}309310311interface AdoptionSourceDeps {312 val sourceIdentity: LocalDeviceIdentity313 suspend fun rootKeyHex(): String314 suspend fun vaultId(): String315 suspend fun license(): String? = null316 317 suspend fun applyLicense(license: String) {}318319 320321322323324325 suspend fun onConsent(request: AdoptionFrame.Request): Boolean326 suspend fun upsertPairedDevice(device: PairedDevice)327 fun hasDeviceIdentityCollision(device: PairedDevice): Boolean = false328 329330331332333 suspend fun rotateSourceIdentity(): LocalDeviceIdentity = error("rotateSourceIdentity not wired")334 val pairState: AdoptionPairState? get() = null335 336 suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? = null337 338 suspend fun outgoingDeviceManifest(): SignedDeviceManifest? = null339 340 suspend fun markSynced(deviceId: String) {}341 342 suspend fun duressSlotJson(): String? = null343}344345private val Hex64 = Regex("^[0-9a-f]{64}\$")346347fun validateRootKeyHex(rootKeyHex: String?): Boolean = rootKeyHex != null && Hex64.matches(rootKeyHex)348349fun isAdoptRequest(frame: AdoptionFrame?): Boolean =350 frame is AdoptionFrame.Request &&351 frame.sessionRequestId.isNotEmpty() &&352 isDeviceType(frame.deviceType)353354fun isAdoptGrant(frame: AdoptionFrame?): Boolean =355 frame is AdoptionFrame.Grant &&356 validateRootKeyHex(frame.rootKeyHex) &&357 Hex64.matches(frame.vaultId) &&358 isDeviceType(frame.source.deviceType) &&359 Hex64.matches(frame.source.longTermPublicKeyHex) &&360 (frame.source.relayUrl == null ||361 runCatching { Rendezvous.normalizeRelayUrl(frame.source.relayUrl) }.isSuccess)362363fun isAdoptConfirm(frame: AdoptionFrame?): Boolean =364 frame is AdoptionFrame.Confirm365366fun isAdoptIdentity(frame: AdoptionFrame?): Boolean =367 frame is AdoptionFrame.Identity &&368 frame.deviceId.isNotEmpty() &&369 isDeviceType(frame.deviceType) &&370 Hex64.matches(frame.longTermPublicKeyHex)371372fun isAdoptComplete(frame: AdoptionFrame?): Boolean =373 frame is AdoptionFrame.Complete374375fun isAdoptApplied(frame: AdoptionFrame?): Boolean =376 frame is AdoptionFrame.Applied377378fun isAdoptReject(frame: AdoptionFrame?): Boolean =379 frame is AdoptionFrame.Reject &&380 (frame.reason == "ADOPT_PRO_REQUIRED" || frame.reason == "ADOPT_DEVICE_ID_COLLISION")381382fun isAdoptSnapshot(frame: AdoptionFrame?): Boolean =383 frame is AdoptionFrame.Snapshot &&384 frame.chunkIndex >= 0 &&385 frame.chunkCount >= 1386387388389390391392393394suspend fun requestAdoption(395 channel: PairingTransport,396 deps: AdoptionReceiverDeps,397 398 399 400 401 402 onGrant: ((AdoptionFrame.Grant) -> Unit)? = null,403 nowMs: () -> Long = { System.currentTimeMillis() },404): PairedDevice? {405 val receiverLicense = deps.license()406 407 408 sendFrame(channel, AdoptionFrame.Request(409 sessionRequestId = deps.generateDeviceId(),410 deviceName = deps.deviceName,411 deviceType = deps.deviceType.wireValue,412 license = receiverLicense,413 snapshotCapable = true,414 ))415416 val confirmed = deps.confirmSas()417 sendFrame(channel, AdoptionFrame.Confirm(confirmed))418 if (!confirmed) {419 deps.onError("ADOPT_SAS_REJECTED")420 return null421 }422423 val frame = receiveFrame(channel)424 if (isAdoptReject(frame)) {425 deps.onError((frame as AdoptionFrame.Reject).reason)426 return null427 }428 if (!isAdoptGrant(frame)) {429 deps.onError("ADOPT_UNEXPECTED_FRAME")430 return null431 }432 val grant = frame as AdoptionFrame.Grant433 onGrant?.invoke(grant)434435 val rootKeyBytes = hexToPubkey(grant.rootKeyHex)436 try {437 if (computeVaultId(rootKeyBytes) != grant.vaultId) {438 deps.onError("ADOPT_VAULT_ID_MISMATCH")439 return null440 }441 } finally {442 rootKeyBytes.fill(0)443 }444 if (receiverLicense == null && grant.license == null) {445 deps.onError("ADOPT_PRO_REQUIRED")446 return null447 }448449 deps.validateSource(grant.source)450451 452 453 454 455 456 var acceptedGrant = grant457 if (deps.hasSourceIdentityCollision(acceptedGrant.source)) {458 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))459 val retry = receiveFrame(channel)460 if (!isAdoptGrant(retry)) {461 deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")462 return null463 }464 acceptedGrant = retry as AdoptionFrame.Grant465 if (deps.hasSourceIdentityCollision(acceptedGrant.source)) {466 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))467 deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")468 return null469 }470 471 val freshRootBytes = hexToPubkey(acceptedGrant.rootKeyHex)472 try {473 if (computeVaultId(freshRootBytes) != acceptedGrant.vaultId) {474 deps.onError("ADOPT_VAULT_ID_MISMATCH")475 return null476 }477 } finally {478 freshRootBytes.fill(0)479 }480 }481482 val vaultId = deps.createVaultFromRootKey(acceptedGrant.rootKeyHex)483 if (vaultId != acceptedGrant.vaultId) {484 deps.onError("ADOPT_VAULT_ID_MISMATCH")485 return null486 }487488 if (receiverLicense == null) {489 acceptedGrant.license?.let { deps.applyLicense(it) }490 }491492 val identity = deps.deriveLocalIdentity()493 sendFrame(channel, AdoptionFrame.Identity(494 deviceId = identity.deviceId,495 deviceName = identity.deviceName,496 deviceType = identity.deviceType.wireValue,497 longTermPublicKeyHex = identity.longTermPublicKeyHex,498 signingPublicKeyHex = identity.signingPublicKeyHex,499 ))500501 if (!isAdoptComplete(receiveFrame(channel))) {502 deps.onError("ADOPT_COMPLETION_MISSING")503 return null504 }505506 val sourceDevice = PairedDevice(507 deviceId = acceptedGrant.source.deviceId,508 deviceName = acceptedGrant.source.deviceName,509 deviceType = acceptedGrant.source.deviceType,510 longTermPublicKeyHex = acceptedGrant.source.longTermPublicKeyHex,511 signingPublicKeyHex = acceptedGrant.source.signingPublicKeyHex,512 trustSource = "direct",513 wsPort = acceptedGrant.source.wsPort,514 rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,515 relayUrl = deps.pairState?.relayUrl ?: acceptedGrant.source.relayUrl,516 pairedAt = nowMs(),517 )518 519 520 521 deps.clearPairedDeviceRevocation(sourceDevice.deviceId)522 deps.upsertPairedDevice(sourceDevice)523 sendFrame(channel, AdoptionFrame.Applied)524 return sourceDevice525}526527528529530531532suspend fun grantAdoption(533 channel: PairingTransport,534 request: AdoptionFrame.Request,535 deps: AdoptionSourceDeps,536 nowMs: () -> Long = { System.currentTimeMillis() },537): PairedDevice? {538 if (!deps.onConsent(request)) return null539540 val confirmation = receiveFrame(channel)541 if (!isAdoptConfirm(confirmation) || !(confirmation as AdoptionFrame.Confirm).confirmed) {542 return null543 }544545 var sourceLicense = deps.license()546 if (sourceLicense == null && request.license != null) {547 sourceLicense = runCatching {548 deps.applyLicense(request.license)549 deps.license()550 }.getOrNull()551 }552 if (sourceLicense == null) {553 sendFrame(channel, AdoptionFrame.Reject("ADOPT_PRO_REQUIRED"))554 throw IllegalStateException("ADOPT_PRO_REQUIRED")555 }556557 val rootKeyHex = deps.rootKeyHex()558 if (!validateRootKeyHex(rootKeyHex)) throw IllegalStateException("ADOPT_INVALID_ROOT_KEY")559560 var sourceIdentity = deps.sourceIdentity561 var grantAttempts = 0562 while (true) {563 sendFrame(channel, AdoptionFrame.Grant(564 rootKeyHex = rootKeyHex,565 vaultId = deps.vaultId(),566 license = sourceLicense,567 source = AdoptionFrame.Source(568 deviceId = sourceIdentity.deviceId,569 deviceName = sourceIdentity.deviceName,570 deviceType = sourceIdentity.deviceType.wireValue,571 longTermPublicKeyHex = sourceIdentity.longTermPublicKeyHex,572 signingPublicKeyHex = sourceIdentity.signingPublicKeyHex,573 wsPort = sourceIdentity.wsPort,574 relayUrl = deps.pairState?.relayUrl,575 ),576 snapshotCapable = request.snapshotCapable == true,577 ))578579 var identity = receiveFrame(channel)580581 582 583 if (identity is AdoptionFrame.Reject &&584 identity.reason == "ADOPT_DEVICE_ID_COLLISION" &&585 grantAttempts == 0586 ) {587 sourceIdentity = deps.rotateSourceIdentity()588 grantAttempts++589 continue590 }591592 if (!isAdoptIdentity(identity)) return null593 identity as AdoptionFrame.Identity594595 var device = PairedDevice(596 deviceId = identity.deviceId,597 deviceName = identity.deviceName,598 deviceType = identity.deviceType,599 longTermPublicKeyHex = identity.longTermPublicKeyHex,600 signingPublicKeyHex = identity.signingPublicKeyHex,601 trustSource = "direct",602 rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,603 relayUrl = deps.pairState?.relayUrl,604 pairedAt = nowMs(),605 )606 if (deps.hasDeviceIdentityCollision(device)) {607 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))608 identity = receiveFrame(channel)609 if (!isAdoptIdentity(identity)) return null610 identity as AdoptionFrame.Identity611 device = device.copy(612 deviceId = identity.deviceId,613 deviceName = identity.deviceName,614 deviceType = identity.deviceType,615 longTermPublicKeyHex = identity.longTermPublicKeyHex,616 signingPublicKeyHex = identity.signingPublicKeyHex,617 )618 if (deps.hasDeviceIdentityCollision(device)) {619 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))620 return null621 }622 }623 deps.upsertPairedDevice(device)624 sendFrame(channel, AdoptionFrame.Complete)625 if (!isAdoptApplied(receiveFrame(channel))) return null626 return device627 }628}629630631632633634635val AdoptJson: Json = Json {636 classDiscriminator = "type"637 encodeDefaults = false638 ignoreUnknownKeys = true639}640641suspend fun sendFrame(channel: PairingTransport, frame: AdoptionFrame) {642 channel.send(AdoptJson.encodeToString(AdoptionFrame.serializer(), frame).toByteArray(Charsets.UTF_8))643}644645646suspend fun receiveFrame(channel: PairingTransport): AdoptionFrame? =647 runCatching {648 AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(channel.receive(), Charsets.UTF_8))649 }.getOrNull()650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681suspend fun sendVaultSnapshot(682 channel: PairingTransport,683 entries: Map<String, String>,684 tombstones: Map<String, Long>,685 duressSlot: String? = null,686) {687 val frames = buildAdoptSnapshotFrames(entries, tombstones, duressSlot)688 689 690 691 692 693 val acc = createAdoptSnapshotBudget()694 val encoded = frames.map {695 AdoptJson.encodeToString(AdoptionFrame.serializer(), it).encodeToByteArray()696 }697 for (i in frames.indices) {698 val frame = frames[i]699 applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, encoded[i].size)700 }701 for (raw in encoded) channel.send(SyncPadding.pad(raw))702}703704705706707708709private fun buildAdoptSnapshotFrames(710 entries: Map<String, String>,711 tombstones: Map<String, Long>,712 duressSlot: String?,713): List<AdoptionFrame.Snapshot> {714 val includeDuress = !duressSlot.isNullOrBlank()715 716 717 val entryCap = MAX_SNAPSHOT_CHUNKS - 1718719 val chunks = mutableListOf<Map<String, String>>()720 var current = LinkedHashMap<String, String>()721 var currentBytes = 2 722 for ((id, envelope) in entries) {723 724 val entryBytes = AdoptJson.encodeToString(mapOf(id to envelope)).length + 1725 if (current.isNotEmpty() && currentBytes + entryBytes >= MAX_SNAPSHOT_CHUNK_BYTES) {726 chunks.add(current)727 current = LinkedHashMap()728 currentBytes = 2729 }730 current[id] = envelope731 currentBytes += entryBytes732 }733 chunks.add(current)734735 val entriesChunkCount = minOf(chunks.size, entryCap)736 val totalChunks = entriesChunkCount + 1737 val supplementalFrame = AdoptionFrame.Snapshot(738 chunkIndex = entriesChunkCount,739 chunkCount = totalChunks,740 entries = emptyMap(),741 tombstones = tombstones,742 duressSlot = duressSlot.takeIf { includeDuress },743 )744745 if (746 AdoptJson.encodeToString(AdoptionFrame.serializer(), supplementalFrame)747 .encodeToByteArray().size > SNAPSHOT_FRAME_WIRE_CEILING748 ) {749 if (includeDuress) throw SnapshotDuressFrameTooLargeException()750 throw IllegalStateException("ADOPT_SNAPSHOT_SUPPLEMENTAL_FRAME_TOO_LARGE")751 }752753 val frames = mutableListOf<AdoptionFrame.Snapshot>()754 for (index in 0 until entriesChunkCount) {755 frames.add(AdoptionFrame.Snapshot(756 chunkIndex = index,757 chunkCount = totalChunks,758 entries = chunks[index],759 tombstones = emptyMap(),760 duressSlot = null,761 ))762 }763 frames.add(supplementalFrame)764 return frames765}766767internal class SnapshotDuressFrameTooLargeException :768 IllegalStateException("ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE")769770771772773774775776777778779780781suspend fun receiveVaultSnapshot(782 channel: PairingTransport,783): ReceivedSnapshot {784 val acc = createAdoptSnapshotBudget()785 var chunkCount = -1786 var received = 0787 while (chunkCount == -1 || received < chunkCount) {788 val wire = channel.receive()789 if (wire.size > MAX_PADDED_SNAPSHOT_FRAME_BYTES) {790 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")791 }792 val raw = runCatching { SyncPadding.unpad(wire) }793 .getOrElse { throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME", it) }794 if (raw.size > MAX_ADOPT_SNAPSHOT_BYTES - acc.bytes) {795 throw IllegalStateException("ADOPT_SNAPSHOT_OVER_BUDGET")796 }797 if (raw.size > SNAPSHOT_FRAME_WIRE_CEILING) {798 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")799 }800 val frame = runCatching {801 AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(raw, Charsets.UTF_8))802 }.getOrNull()803 if (!isAdoptSnapshot(frame)) throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME")804 frame as AdoptionFrame.Snapshot805 if (chunkCount == -1) {806 chunkCount = frame.chunkCount807 if (chunkCount > MAX_SNAPSHOT_CHUNKS) {808 throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_CHUNKS")809 }810 } else if (frame.chunkCount != chunkCount) {811 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_COUNT_MISMATCH")812 }813 if (frame.chunkIndex != received) {814 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_OUT_OF_ORDER")815 }816 applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, raw.size)817 received++818 }819 return ReceivedSnapshot(acc.entries, acc.tombstones, acc.duressSlot)820}821822private fun isDeviceType(value: String): Boolean =823 DeviceType.entries.any { it.wireValue == value }