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 persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long): Boolean = true332 suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice): Boolean = true333 suspend fun upsertPairedDevice(device: PairedDevice)334 fun hasDeviceIdentityCollision(device: PairedDevice): Boolean = false335 336337338339340 suspend fun rotateSourceIdentity(): LocalDeviceIdentity = error("rotateSourceIdentity not wired")341 val pairState: AdoptionPairState? get() = null342 343 suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? = null344 345 suspend fun outgoingDeviceManifest(): SignedDeviceManifest? = null346 347 suspend fun markSynced(deviceId: String) {}348 349 suspend fun duressSlotJson(): String? = null350}351352private val Hex64 = Regex("^[0-9a-f]{64}\$")353354fun validateRootKeyHex(rootKeyHex: String?): Boolean = rootKeyHex != null && Hex64.matches(rootKeyHex)355356fun isAdoptRequest(frame: AdoptionFrame?): Boolean =357 frame is AdoptionFrame.Request &&358 frame.sessionRequestId.isNotEmpty() &&359 isDeviceType(frame.deviceType)360361fun isAdoptGrant(frame: AdoptionFrame?): Boolean =362 frame is AdoptionFrame.Grant &&363 validateRootKeyHex(frame.rootKeyHex) &&364 Hex64.matches(frame.vaultId) &&365 isDeviceType(frame.source.deviceType) &&366 Hex64.matches(frame.source.longTermPublicKeyHex) &&367 (frame.source.relayUrl == null ||368 runCatching { Rendezvous.normalizeRelayUrl(frame.source.relayUrl) }.isSuccess)369370fun isAdoptConfirm(frame: AdoptionFrame?): Boolean =371 frame is AdoptionFrame.Confirm372373fun isAdoptIdentity(frame: AdoptionFrame?): Boolean =374 frame is AdoptionFrame.Identity &&375 frame.deviceId.isNotEmpty() &&376 isDeviceType(frame.deviceType) &&377 Hex64.matches(frame.longTermPublicKeyHex)378379fun isAdoptComplete(frame: AdoptionFrame?): Boolean =380 frame is AdoptionFrame.Complete381382fun isAdoptApplied(frame: AdoptionFrame?): Boolean =383 frame is AdoptionFrame.Applied384385fun isAdoptReject(frame: AdoptionFrame?): Boolean =386 frame is AdoptionFrame.Reject &&387 (frame.reason == "ADOPT_PRO_REQUIRED" || frame.reason == "ADOPT_DEVICE_ID_COLLISION")388389fun isAdoptSnapshot(frame: AdoptionFrame?): Boolean =390 frame is AdoptionFrame.Snapshot &&391 frame.chunkIndex >= 0 &&392 frame.chunkCount >= 1393394395396397398399400401suspend fun requestAdoption(402 channel: PairingTransport,403 deps: AdoptionReceiverDeps,404 405 406 407 408 409 onGrant: ((AdoptionFrame.Grant) -> Unit)? = null,410 nowMs: () -> Long = { System.currentTimeMillis() },411): PairedDevice? {412 val receiverLicense = deps.license()413 414 415 sendFrame(channel, AdoptionFrame.Request(416 sessionRequestId = deps.generateDeviceId(),417 deviceName = deps.deviceName,418 deviceType = deps.deviceType.wireValue,419 license = receiverLicense,420 snapshotCapable = true,421 ))422423 val confirmed = deps.confirmSas()424 sendFrame(channel, AdoptionFrame.Confirm(confirmed))425 if (!confirmed) {426 deps.onError("ADOPT_SAS_REJECTED")427 return null428 }429430 val frame = receiveFrame(channel)431 if (isAdoptReject(frame)) {432 deps.onError((frame as AdoptionFrame.Reject).reason)433 return null434 }435 if (!isAdoptGrant(frame)) {436 deps.onError("ADOPT_UNEXPECTED_FRAME")437 return null438 }439 val grant = frame as AdoptionFrame.Grant440 onGrant?.invoke(grant)441442 val rootKeyBytes = hexToPubkey(grant.rootKeyHex)443 try {444 if (computeVaultId(rootKeyBytes) != grant.vaultId) {445 deps.onError("ADOPT_VAULT_ID_MISMATCH")446 return null447 }448 } finally {449 rootKeyBytes.fill(0)450 }451 if (receiverLicense == null && grant.license == null) {452 deps.onError("ADOPT_PRO_REQUIRED")453 return null454 }455456 deps.validateSource(grant.source)457458 459 460 461 462 463 var acceptedGrant = grant464 if (deps.hasSourceIdentityCollision(acceptedGrant.source)) {465 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))466 val retry = receiveFrame(channel)467 if (!isAdoptGrant(retry)) {468 deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")469 return null470 }471 acceptedGrant = retry as AdoptionFrame.Grant472 if (deps.hasSourceIdentityCollision(acceptedGrant.source)) {473 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))474 deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")475 return null476 }477 478 val freshRootBytes = hexToPubkey(acceptedGrant.rootKeyHex)479 try {480 if (computeVaultId(freshRootBytes) != acceptedGrant.vaultId) {481 deps.onError("ADOPT_VAULT_ID_MISMATCH")482 return null483 }484 } finally {485 freshRootBytes.fill(0)486 }487 }488 if (receiverLicense == null && acceptedGrant.license == null) {489 deps.onError("ADOPT_PRO_REQUIRED")490 return null491 }492493494 if (receiverLicense == null) {495 acceptedGrant.license?.let { deps.applyLicense(it) }496 }497 val vaultId = deps.createVaultFromRootKey(acceptedGrant.rootKeyHex)498 if (vaultId != acceptedGrant.vaultId) {499 deps.onError("ADOPT_VAULT_ID_MISMATCH")500 return null501 }502503504 val identity = deps.deriveLocalIdentity()505 sendFrame(channel, AdoptionFrame.Identity(506 deviceId = identity.deviceId,507 deviceName = identity.deviceName,508 deviceType = identity.deviceType.wireValue,509 longTermPublicKeyHex = identity.longTermPublicKeyHex,510 signingPublicKeyHex = identity.signingPublicKeyHex,511 ))512513 if (!isAdoptComplete(receiveFrame(channel))) {514 deps.onError("ADOPT_COMPLETION_MISSING")515 return null516 }517518 val sourceDevice = PairedDevice(519 deviceId = acceptedGrant.source.deviceId,520 deviceName = acceptedGrant.source.deviceName,521 deviceType = acceptedGrant.source.deviceType,522 longTermPublicKeyHex = acceptedGrant.source.longTermPublicKeyHex,523 signingPublicKeyHex = acceptedGrant.source.signingPublicKeyHex,524 trustSource = "direct",525 wsPort = acceptedGrant.source.wsPort,526 rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,527 relayUrl = deps.pairState?.relayUrl ?: acceptedGrant.source.relayUrl,528 pairedAt = nowMs(),529 )530 531 532 533 deps.upsertPairedDeviceAndClearRevocation(sourceDevice)534 sendFrame(channel, AdoptionFrame.Applied)535 return sourceDevice536}537538539540541542543suspend fun grantAdoption(544 channel: PairingTransport,545 request: AdoptionFrame.Request,546 deps: AdoptionSourceDeps,547 nowMs: () -> Long = { System.currentTimeMillis() },548): PairedDevice? {549 if (!deps.onConsent(request)) return null550551 val confirmation = receiveFrame(channel)552 if (!isAdoptConfirm(confirmation) || !(confirmation as AdoptionFrame.Confirm).confirmed) {553 return null554 }555556 var sourceLicense = deps.license()557 if (sourceLicense == null && request.license != null) {558 sourceLicense = runCatching {559 deps.applyLicense(request.license)560 deps.license()561 }.getOrNull()562 }563 if (sourceLicense == null) {564 sendFrame(channel, AdoptionFrame.Reject("ADOPT_PRO_REQUIRED"))565 throw IllegalStateException("ADOPT_PRO_REQUIRED")566 }567568 if (!deps.persistPendingHolder(request, nowMs())) return null569 val rootKeyHex = deps.rootKeyHex()570 if (!validateRootKeyHex(rootKeyHex)) throw IllegalStateException("ADOPT_INVALID_ROOT_KEY")571572 var sourceIdentity = deps.sourceIdentity573 var grantAttempts = 0574 while (true) {575 sendFrame(channel, AdoptionFrame.Grant(576 rootKeyHex = rootKeyHex,577 vaultId = deps.vaultId(),578 license = sourceLicense,579 source = AdoptionFrame.Source(580 deviceId = sourceIdentity.deviceId,581 deviceName = sourceIdentity.deviceName,582 deviceType = sourceIdentity.deviceType.wireValue,583 longTermPublicKeyHex = sourceIdentity.longTermPublicKeyHex,584 signingPublicKeyHex = sourceIdentity.signingPublicKeyHex,585 wsPort = sourceIdentity.wsPort,586 relayUrl = deps.pairState?.relayUrl,587 ),588 snapshotCapable = request.snapshotCapable == true,589 ))590591 var identity = receiveFrame(channel)592593 594 595 if (identity is AdoptionFrame.Reject &&596 identity.reason == "ADOPT_DEVICE_ID_COLLISION" &&597 grantAttempts == 0598 ) {599 sourceIdentity = deps.rotateSourceIdentity()600 grantAttempts++601 continue602 }603604 if (!isAdoptIdentity(identity)) return null605 identity as AdoptionFrame.Identity606607 var device = PairedDevice(608 deviceId = identity.deviceId,609 deviceName = identity.deviceName,610 deviceType = identity.deviceType,611 longTermPublicKeyHex = identity.longTermPublicKeyHex,612 signingPublicKeyHex = identity.signingPublicKeyHex,613 trustSource = "direct",614 rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,615 relayUrl = deps.pairState?.relayUrl,616 pairedAt = nowMs(),617 )618 if (deps.hasDeviceIdentityCollision(device)) {619 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))620 identity = receiveFrame(channel)621 if (!isAdoptIdentity(identity)) return null622 identity as AdoptionFrame.Identity623 device = device.copy(624 deviceId = identity.deviceId,625 deviceName = identity.deviceName,626 deviceType = identity.deviceType,627 longTermPublicKeyHex = identity.longTermPublicKeyHex,628 signingPublicKeyHex = identity.signingPublicKeyHex,629 )630 if (deps.hasDeviceIdentityCollision(device)) {631 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))632 return null633 }634 }635 deps.upsertPairedDevice(device)636 sendFrame(channel, AdoptionFrame.Complete)637 if (!isAdoptApplied(receiveFrame(channel))) return null638 if (!deps.completePendingHolder(request, device)) return null639 return device640 }641}642643644645646647648val AdoptJson: Json = Json {649 classDiscriminator = "type"650 encodeDefaults = false651 ignoreUnknownKeys = true652}653654suspend fun sendFrame(channel: PairingTransport, frame: AdoptionFrame) {655 channel.send(AdoptJson.encodeToString(AdoptionFrame.serializer(), frame).toByteArray(Charsets.UTF_8))656}657658659suspend fun receiveFrame(channel: PairingTransport): AdoptionFrame? =660 runCatching {661 AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(channel.receive(), Charsets.UTF_8))662 }.getOrNull()663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694suspend fun sendVaultSnapshot(695 channel: PairingTransport,696 entries: Map<String, String>,697 tombstones: Map<String, Long>,698 duressSlot: String? = null,699) {700 val frames = buildAdoptSnapshotFrames(entries, tombstones, duressSlot)701 702 703 704 705 706 val acc = createAdoptSnapshotBudget()707 val encoded = frames.map {708 AdoptJson.encodeToString(AdoptionFrame.serializer(), it).encodeToByteArray()709 }710 for (i in frames.indices) {711 val frame = frames[i]712 applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, encoded[i].size)713 }714 for (raw in encoded) channel.send(SyncPadding.pad(raw))715}716717718719720721722private fun buildAdoptSnapshotFrames(723 entries: Map<String, String>,724 tombstones: Map<String, Long>,725 duressSlot: String?,726): List<AdoptionFrame.Snapshot> {727 val includeDuress = !duressSlot.isNullOrBlank()728 729 730 val entryCap = MAX_SNAPSHOT_CHUNKS - 1731732 val chunks = mutableListOf<Map<String, String>>()733 var current = LinkedHashMap<String, String>()734 var currentBytes = 2 735 for ((id, envelope) in entries) {736 737 val entryBytes = AdoptJson.encodeToString(mapOf(id to envelope)).length + 1738 if (current.isNotEmpty() && currentBytes + entryBytes >= MAX_SNAPSHOT_CHUNK_BYTES) {739 chunks.add(current)740 current = LinkedHashMap()741 currentBytes = 2742 }743 current[id] = envelope744 currentBytes += entryBytes745 }746 chunks.add(current)747748 val entriesChunkCount = minOf(chunks.size, entryCap)749 val totalChunks = entriesChunkCount + 1750 val supplementalFrame = AdoptionFrame.Snapshot(751 chunkIndex = entriesChunkCount,752 chunkCount = totalChunks,753 entries = emptyMap(),754 tombstones = tombstones,755 duressSlot = duressSlot.takeIf { includeDuress },756 )757758 if (759 AdoptJson.encodeToString(AdoptionFrame.serializer(), supplementalFrame)760 .encodeToByteArray().size > SNAPSHOT_FRAME_WIRE_CEILING761 ) {762 if (includeDuress) throw SnapshotDuressFrameTooLargeException()763 throw IllegalStateException("ADOPT_SNAPSHOT_SUPPLEMENTAL_FRAME_TOO_LARGE")764 }765766 val frames = mutableListOf<AdoptionFrame.Snapshot>()767 for (index in 0 until entriesChunkCount) {768 frames.add(AdoptionFrame.Snapshot(769 chunkIndex = index,770 chunkCount = totalChunks,771 entries = chunks[index],772 tombstones = emptyMap(),773 duressSlot = null,774 ))775 }776 frames.add(supplementalFrame)777 return frames778}779780internal class SnapshotDuressFrameTooLargeException :781 IllegalStateException("ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE")782783784785786787788789790791792793794suspend fun receiveVaultSnapshot(795 channel: PairingTransport,796): ReceivedSnapshot {797 val acc = createAdoptSnapshotBudget()798 var chunkCount = -1799 var received = 0800 while (chunkCount == -1 || received < chunkCount) {801 val wire = channel.receive()802 if (wire.size > MAX_PADDED_SNAPSHOT_FRAME_BYTES) {803 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")804 }805 val raw = runCatching { SyncPadding.unpad(wire) }806 .getOrElse { throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME", it) }807 if (raw.size > MAX_ADOPT_SNAPSHOT_BYTES - acc.bytes) {808 throw IllegalStateException("ADOPT_SNAPSHOT_OVER_BUDGET")809 }810 if (raw.size > SNAPSHOT_FRAME_WIRE_CEILING) {811 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")812 }813 val frame = runCatching {814 AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(raw, Charsets.UTF_8))815 }.getOrNull()816 if (!isAdoptSnapshot(frame)) throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME")817 frame as AdoptionFrame.Snapshot818 if (chunkCount == -1) {819 chunkCount = frame.chunkCount820 if (chunkCount > MAX_SNAPSHOT_CHUNKS) {821 throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_CHUNKS")822 }823 } else if (frame.chunkCount != chunkCount) {824 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_COUNT_MISMATCH")825 }826 if (frame.chunkIndex != received) {827 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_OUT_OF_ORDER")828 }829 applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, raw.size)830 received++831 }832 return ReceivedSnapshot(acc.entries, acc.tombstones, acc.duressSlot)833}834835private fun isDeviceType(value: String): Boolean =836 DeviceType.entries.any { it.wireValue == value }