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 @SerialName("snapshot_capable") val snapshotCapable: Boolean = false,59 ) : AdoptionFrame()6061 @Serializable62 @SerialName("ADOPT_IDENTITY")63 data class Identity(64 @SerialName("device_id") val deviceId: String,65 @SerialName("device_name") val deviceName: String,66 @SerialName("device_type") val deviceType: String,67 @SerialName("long_term_public_key_hex") val longTermPublicKeyHex: String,68 @SerialName("signing_public_key_hex") val signingPublicKeyHex: String? = null,69 ) : AdoptionFrame()7071 7273747576 @Serializable77 @SerialName("ADOPT_COMPLETE")78 data object Complete : AdoptionFrame()7980 81 @Serializable82 @SerialName("ADOPT_APPLIED")83 data object Applied : AdoptionFrame()8485 86 @Serializable87 @SerialName("ADOPT_REJECT")88 data class Reject(89 val reason: String,90 ) : AdoptionFrame()9192 9394959697 @Serializable98 @SerialName("ADOPT_SNAPSHOT")99 data class Snapshot(100 @SerialName("chunk_index") val chunkIndex: Int,101 @SerialName("chunk_count") val chunkCount: Int,102 val entries: Map<String, String>,103 val tombstones: Map<String, Long>,104 @SerialName("duress_slot") val duressSlot: String? = null,105 ) : AdoptionFrame()106107 108 @Serializable109 @SerialName("ADOPT_SNAPSHOT_APPLIED")110 data class SnapshotApplied(111 @SerialName("entries_received") val entriesReceived: Int,112 @SerialName("tombstones_received") val tombstonesReceived: Int,113 ) : AdoptionFrame()114115 116 @Serializable117 @SerialName("ADOPT_DEVICE_MANIFEST")118 data class DeviceManifestFrame(119 val manifest: SignedDeviceManifest,120 ) : AdoptionFrame()121122 123 @Serializable124 @SerialName("ADOPT_DEVICE_MANIFEST_APPLIED")125 data object DeviceManifestApplied : AdoptionFrame()126 @Serializable127 @SerialName("ADOPT_REQUEST_V2")128 data class RequestV2(129 @SerialName("adoptionVersion") val adoptionVersion: Int,130 @SerialName("device_id") val deviceId: String,131 @SerialName("device_name") val deviceName: String,132 @SerialName("device_type") val deviceType: String,133 @SerialName("long_term_public_key_hex") val longTermPublicKeyHex: String,134 @SerialName("signing_public_key_hex") val signingPublicKeyHex: String,135 val license: String? = null,136 @SerialName("snapshot_capable") val snapshotCapable: Boolean? = null,137 ) : AdoptionFrame()138139 @Serializable @SerialName("ADOPT_CONFIRM_REQUIRED")140 data object ConfirmRequired : AdoptionFrame()141142 @Serializable @SerialName("ADOPT_PREPARE")143 data class Prepare(144 @SerialName("device_id") val deviceId: String,145 @SerialName("device_name") val deviceName: String,146 @SerialName("device_type") val deviceType: String,147 @SerialName("long_term_public_key_hex") val longTermPublicKeyHex: String,148 @SerialName("signing_public_key_hex") val signingPublicKeyHex: String,149 @SerialName("vault_id") val vaultId: String,150 @SerialName("ws_port") val wsPort: Int? = null,151 @SerialName("relay_url") val relayUrl: String? = null,152 val license: String? = null,153 @SerialName("snapshot_capable") val snapshotCapable: Boolean? = null,154 ) : AdoptionFrame()155 @Serializable @SerialName("ADOPT_READY")156 data object Ready : AdoptionFrame()157 @Serializable158 data class Source(159 @SerialName("device_id") val deviceId: String,160 @SerialName("device_name") val deviceName: String,161 @SerialName("device_type") val deviceType: String,162 @SerialName("long_term_public_key_hex") val longTermPublicKeyHex: String,163 @SerialName("signing_public_key_hex") val signingPublicKeyHex: String? = null,164 @SerialName("ws_port") val wsPort: Int? = null,165 @SerialName("relay_url") val relayUrl: String? = null,166 )167}168169data class AdoptionPairState(170 val rendezvousSecretHex: String,171 val relayUrl: String? = null,172)173174175176177178179data class ReceivedSnapshot(180 val entries: Map<String, String>,181 val tombstones: Map<String, Long>,182 val duressSlot: String? = null,183)184185186187188189190191const val MAX_SNAPSHOT_CHUNK_BYTES = 512 * 1024 192const val MAX_SNAPSHOT_CHUNKS = 200193194195196internal const val SNAPSHOT_FRAME_WIRE_CEILING = MAX_SNAPSHOT_CHUNK_BYTES + 256 * 1024197internal val MAX_PADDED_SNAPSHOT_FRAME_BYTES = SyncPadding.bucket(SNAPSHOT_FRAME_WIRE_CEILING + 4)198199200201202203204205const val MAX_ADOPT_SNAPSHOT_BYTES = 10 * 1024 * 1024 206const val MAX_ADOPT_SNAPSHOT_ENTRIES = 25_000207const val MAX_ADOPT_SNAPSHOT_TOMBSTONES = 25_000208209const val MAX_ADOPT_SNAPSHOT_ID_CHARS = SyncLimits.MAX_ID_LENGTH210211212213214215const val MAX_ADOPT_SNAPSHOT_ENVELOPE_BYTES = SyncLimits.MAX_ENTRY_ENVELOPE_BYTES216217218219220221class AdoptSnapshotBudget {222 val entries = LinkedHashMap<String, String>()223 val tombstones = LinkedHashMap<String, Long>()224 var duressSlot: String? = null225 226 var bytes: Int = 0227 var entryCount: Int = 0228 var tombstoneCount: Int = 0229}230231fun createAdoptSnapshotBudget(): AdoptSnapshotBudget = AdoptSnapshotBudget()232233234235236237238239240241242243fun applyAdoptSnapshotFrame(244 acc: AdoptSnapshotBudget,245 entries: Map<String, String>,246 tombstones: Map<String, Long>,247 duressSlot: String?,248 frameBytes: Int,249) {250 if (frameBytes > MAX_ADOPT_SNAPSHOT_BYTES - acc.bytes) {251 throw IllegalStateException("ADOPT_SNAPSHOT_OVER_BUDGET")252 }253 for ((id, envelope) in entries) {254 if (id.length > MAX_ADOPT_SNAPSHOT_ID_CHARS) throw IllegalStateException("ADOPT_SNAPSHOT_ID_TOO_LONG")255 if (envelope.length > MAX_ADOPT_SNAPSHOT_ENVELOPE_BYTES) {256 throw IllegalStateException("ADOPT_SNAPSHOT_ENVELOPE_TOO_LARGE")257 }258 if (acc.entryCount >= MAX_ADOPT_SNAPSHOT_ENTRIES) {259 throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_ENTRIES")260 }261 acc.entryCount++262 acc.entries[id] = envelope263 }264 for ((id, ts) in tombstones) {265 if (id.length > MAX_ADOPT_SNAPSHOT_ID_CHARS) throw IllegalStateException("ADOPT_SNAPSHOT_ID_TOO_LONG")266 267 268 if (acc.tombstoneCount >= MAX_ADOPT_SNAPSHOT_TOMBSTONES) {269 throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_TOMBSTONES")270 }271 acc.tombstoneCount++272 acc.tombstones[id] = ts273 }274 if (!duressSlot.isNullOrEmpty()) {275 276 277 if (duressSlot.length > SNAPSHOT_FRAME_WIRE_CEILING) {278 throw IllegalStateException("ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE")279 }280 acc.duressSlot = duressSlot281 }282 acc.bytes += frameBytes283}284285286interface AdoptionReceiverDeps {287 val deviceName: String288 val deviceType: DeviceType289 fun generateDeviceId(): String290 291 suspend fun confirmSas(): Boolean292 293294295296 suspend fun validateSource(source: AdoptionFrame.Source) {}297298 299300301302303 suspend fun hasSourceIdentityCollision(source: AdoptionFrame.Source): Boolean = false304305 306 suspend fun createVaultFromRootKey(rootKeyHex: String): String307 308 suspend fun deriveLocalIdentity(): LocalDeviceIdentity309 310 suspend fun upsertPairedDeviceAndClearRevocation(device: PairedDevice) {311 upsertPairedDevice(device)312 clearPairedDeviceRevocation(device.deviceId)313 }314 suspend fun clearPairedDeviceRevocation(deviceId: String) {}315 suspend fun upsertPairedDevice(device: PairedDevice)316 suspend fun applyLicense(license: String) {}317 318 suspend fun license(): String? = null319 val pairState: AdoptionPairState? get() = null320 fun onError(error: String)321 322 suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String? = null) {}323 324325326327328329330331 suspend fun applyIncomingDeviceManifest(332 manifest: SignedDeviceManifest,333 authenticatedRemoteStaticPublicKey: ByteArray,334 ) {}335 336 suspend fun markSynced(deviceId: String) {}337}338339340interface AdoptionSourceDeps {341 val sourceIdentity: LocalDeviceIdentity342 suspend fun rootKeyHex(): String343 suspend fun vaultId(): String344 suspend fun license(): String? = null345 346 suspend fun applyLicense(license: String) {}347 348349350351352353 suspend fun onConsent(request: AdoptionFrame.Request): Boolean354 suspend fun persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long): Boolean = true355 suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice): Boolean = true356 suspend fun upsertPairedDevice(device: PairedDevice)357 fun hasDeviceIdentityCollision(device: PairedDevice): Boolean = false358 359360361362363 suspend fun rotateSourceIdentity(): LocalDeviceIdentity = error("rotateSourceIdentity not wired")364 val pairState: AdoptionPairState? get() = null365 366 suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? = null367 368 suspend fun outgoingDeviceManifest(): SignedDeviceManifest? = null369 370 suspend fun markSynced(deviceId: String) {}371 372 suspend fun duressSlotJson(): String? = null373}374375internal val Hex64 = Regex("^[0-9a-f]{64}$")376377fun validateRootKeyHex(rootKeyHex: String?): Boolean = rootKeyHex != null && Hex64.matches(rootKeyHex)378379fun isAdoptRequest(frame: AdoptionFrame?): Boolean =380 frame is AdoptionFrame.Request &&381 frame.sessionRequestId.isNotEmpty() &&382 isDeviceType(frame.deviceType)383384fun isAdoptGrant(frame: AdoptionFrame?): Boolean =385 frame is AdoptionFrame.Grant &&386 validateRootKeyHex(frame.rootKeyHex) &&387 Hex64.matches(frame.vaultId) &&388 isDeviceType(frame.source.deviceType) &&389 Hex64.matches(frame.source.longTermPublicKeyHex) &&390 (frame.source.relayUrl == null ||391 runCatching { Rendezvous.normalizeRelayUrl(frame.source.relayUrl) }.isSuccess)392393fun isAdoptConfirm(frame: AdoptionFrame?): Boolean =394 frame is AdoptionFrame.Confirm395396fun isAdoptIdentity(frame: AdoptionFrame?): Boolean =397 frame is AdoptionFrame.Identity &&398 frame.deviceId.isNotEmpty() &&399 isDeviceType(frame.deviceType) &&400 Hex64.matches(frame.longTermPublicKeyHex)401402fun isAdoptComplete(frame: AdoptionFrame?): Boolean =403 frame is AdoptionFrame.Complete404405fun isAdoptApplied(frame: AdoptionFrame?): Boolean =406 frame is AdoptionFrame.Applied407408fun isAdoptReject(frame: AdoptionFrame?): Boolean =409 frame is AdoptionFrame.Reject &&410 (frame.reason == "ADOPT_PRO_REQUIRED" || frame.reason == "ADOPT_DEVICE_ID_COLLISION")411412fun isAdoptSnapshot(frame: AdoptionFrame?): Boolean =413 frame is AdoptionFrame.Snapshot &&414 frame.chunkIndex >= 0 &&415 frame.chunkCount >= 1416417418419420421422423424suspend fun requestAdoption(425 channel: PairingTransport,426 deps: AdoptionReceiverDeps,427 428 429 430 431 432 onGrant: ((AdoptionFrame.Grant) -> Unit)? = null,433 nowMs: () -> Long = { System.currentTimeMillis() },434): PairedDevice? {435 val receiverLicense = deps.license()436 437 438 sendFrame(channel, AdoptionFrame.Request(439 sessionRequestId = deps.generateDeviceId(),440 deviceName = deps.deviceName,441 deviceType = deps.deviceType.wireValue,442 license = receiverLicense,443 snapshotCapable = true,444 ))445446 val confirmed = deps.confirmSas()447 sendFrame(channel, AdoptionFrame.Confirm(confirmed))448 if (!confirmed) {449 deps.onError("ADOPT_SAS_REJECTED")450 return null451 }452453 val frame = receiveFrame(channel)454 if (isAdoptReject(frame)) {455 deps.onError((frame as AdoptionFrame.Reject).reason)456 return null457 }458 if (!isAdoptGrant(frame)) {459 deps.onError("ADOPT_UNEXPECTED_FRAME")460 return null461 }462 val grant = frame as AdoptionFrame.Grant463 onGrant?.invoke(grant)464465 val rootKeyBytes = hexToPubkey(grant.rootKeyHex)466 try {467 if (computeVaultId(rootKeyBytes) != grant.vaultId) {468 deps.onError("ADOPT_VAULT_ID_MISMATCH")469 return null470 }471 } finally {472 rootKeyBytes.fill(0)473 }474 if (receiverLicense == null && grant.license == null) {475 deps.onError("ADOPT_PRO_REQUIRED")476 return null477 }478479 var acceptedGrant = grant480 var acceptedSource = grant.source ?: run {481 deps.onError("ADOPT_UNEXPECTED_FRAME")482 return null483 }484 deps.validateSource(acceptedSource)485486 487 488 489 490 491 if (deps.hasSourceIdentityCollision(acceptedSource)) {492 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))493 val retry = receiveFrame(channel)494 if (!isAdoptGrant(retry)) {495 deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")496 return null497 }498 acceptedGrant = retry as AdoptionFrame.Grant499 acceptedSource = acceptedGrant.source ?: run {500 deps.onError("ADOPT_UNEXPECTED_FRAME")501 return null502 }503 if (deps.hasSourceIdentityCollision(acceptedSource)) {504 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))505 deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")506 return null507 }508 509 val freshRootBytes = hexToPubkey(acceptedGrant.rootKeyHex)510 try {511 if (computeVaultId(freshRootBytes) != acceptedGrant.vaultId) {512 deps.onError("ADOPT_VAULT_ID_MISMATCH")513 return null514 }515 } finally {516 freshRootBytes.fill(0)517 }518 }519 if (receiverLicense == null && acceptedGrant.license == null) {520 deps.onError("ADOPT_PRO_REQUIRED")521 return null522 }523524525 if (receiverLicense == null) {526 acceptedGrant.license?.let { deps.applyLicense(it) }527 }528 val vaultId = deps.createVaultFromRootKey(acceptedGrant.rootKeyHex)529 if (vaultId != acceptedGrant.vaultId) {530 deps.onError("ADOPT_VAULT_ID_MISMATCH")531 return null532 }533534535 val identity = deps.deriveLocalIdentity()536 sendFrame(channel, AdoptionFrame.Identity(537 deviceId = identity.deviceId,538 deviceName = identity.deviceName,539 deviceType = identity.deviceType.wireValue,540 longTermPublicKeyHex = identity.longTermPublicKeyHex,541 signingPublicKeyHex = identity.signingPublicKeyHex,542 ))543544 if (!isAdoptComplete(receiveFrame(channel))) {545 deps.onError("ADOPT_COMPLETION_MISSING")546 return null547 }548549 val sourceDevice = PairedDevice(550 deviceId = acceptedSource.deviceId,551 deviceName = acceptedSource.deviceName,552 deviceType = acceptedSource.deviceType,553 longTermPublicKeyHex = acceptedSource.longTermPublicKeyHex,554 signingPublicKeyHex = acceptedSource.signingPublicKeyHex,555 trustSource = "direct",556 wsPort = acceptedSource.wsPort,557 rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,558 relayUrl = deps.pairState?.relayUrl ?: acceptedSource.relayUrl,559 pairedAt = nowMs(),560 )561 562 563 564 deps.upsertPairedDeviceAndClearRevocation(sourceDevice)565 sendFrame(channel, AdoptionFrame.Applied)566 return sourceDevice567}568569570571572573574suspend fun grantAdoption(575 channel: PairingTransport,576 request: AdoptionFrame.Request,577 deps: AdoptionSourceDeps,578 nowMs: () -> Long = { System.currentTimeMillis() },579): PairedDevice? {580 if (!deps.onConsent(request)) return null581582 val confirmation = receiveFrame(channel)583 if (!isAdoptConfirm(confirmation) || !(confirmation as AdoptionFrame.Confirm).confirmed) {584 return null585 }586587 var sourceLicense = deps.license()588 if (sourceLicense == null && request.license != null) {589 sourceLicense = runCatching {590 deps.applyLicense(request.license)591 deps.license()592 }.getOrNull()593 }594 if (sourceLicense == null) {595 sendFrame(channel, AdoptionFrame.Reject("ADOPT_PRO_REQUIRED"))596 throw IllegalStateException("ADOPT_PRO_REQUIRED")597 }598599 if (!deps.persistPendingHolder(request, nowMs())) return null600 val rootKeyHex = deps.rootKeyHex()601 if (!validateRootKeyHex(rootKeyHex)) throw IllegalStateException("ADOPT_INVALID_ROOT_KEY")602603 var sourceIdentity = deps.sourceIdentity604 var grantAttempts = 0605 while (true) {606 sendFrame(channel, AdoptionFrame.Grant(607 rootKeyHex = rootKeyHex,608 vaultId = deps.vaultId(),609 license = sourceLicense,610 source = AdoptionFrame.Source(611 deviceId = sourceIdentity.deviceId,612 deviceName = sourceIdentity.deviceName,613 deviceType = sourceIdentity.deviceType.wireValue,614 longTermPublicKeyHex = sourceIdentity.longTermPublicKeyHex,615 signingPublicKeyHex = sourceIdentity.signingPublicKeyHex,616 wsPort = sourceIdentity.wsPort,617 relayUrl = deps.pairState?.relayUrl,618 ),619 snapshotCapable = request.snapshotCapable == true,620 ))621622 var identity = receiveFrame(channel)623624 625 626 if (identity is AdoptionFrame.Reject &&627 identity.reason == "ADOPT_DEVICE_ID_COLLISION" &&628 grantAttempts == 0629 ) {630 sourceIdentity = deps.rotateSourceIdentity()631 grantAttempts++632 continue633 }634635 if (!isAdoptIdentity(identity)) return null636 identity as AdoptionFrame.Identity637638 var device = PairedDevice(639 deviceId = identity.deviceId,640 deviceName = identity.deviceName,641 deviceType = identity.deviceType,642 longTermPublicKeyHex = identity.longTermPublicKeyHex,643 signingPublicKeyHex = identity.signingPublicKeyHex,644 trustSource = "direct",645 rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,646 relayUrl = deps.pairState?.relayUrl,647 pairedAt = nowMs(),648 )649 if (deps.hasDeviceIdentityCollision(device)) {650 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))651 identity = receiveFrame(channel)652 if (!isAdoptIdentity(identity)) return null653 identity as AdoptionFrame.Identity654 device = device.copy(655 deviceId = identity.deviceId,656 deviceName = identity.deviceName,657 deviceType = identity.deviceType,658 longTermPublicKeyHex = identity.longTermPublicKeyHex,659 signingPublicKeyHex = identity.signingPublicKeyHex,660 )661 if (deps.hasDeviceIdentityCollision(device)) {662 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))663 return null664 }665 }666 deps.upsertPairedDevice(device)667 sendFrame(channel, AdoptionFrame.Complete)668 if (!isAdoptApplied(receiveFrame(channel))) return null669 if (!deps.completePendingHolder(request, device)) return null670 return device671 }672}673674675676677678679val AdoptJson: Json = Json {680 classDiscriminator = "type"681 encodeDefaults = false682 ignoreUnknownKeys = true683}684685suspend fun sendFrame(channel: PairingTransport, frame: AdoptionFrame) {686 channel.send(AdoptJson.encodeToString(AdoptionFrame.serializer(), frame).toByteArray(Charsets.UTF_8))687}688689690suspend fun receiveFrame(channel: PairingTransport): AdoptionFrame? =691 runCatching {692 AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(channel.receive(), Charsets.UTF_8))693 }.getOrNull()694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725suspend fun sendVaultSnapshot(726 channel: PairingTransport,727 entries: Map<String, String>,728 tombstones: Map<String, Long>,729 duressSlot: String? = null,730) {731 val frames = buildAdoptSnapshotFrames(entries, tombstones, duressSlot)732 733 734 735 736 737 val acc = createAdoptSnapshotBudget()738 val encoded = frames.map {739 AdoptJson.encodeToString(AdoptionFrame.serializer(), it).encodeToByteArray()740 }741 for (i in frames.indices) {742 val frame = frames[i]743 applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, encoded[i].size)744 }745 for (raw in encoded) channel.send(SyncPadding.pad(raw))746}747748749750751752753private fun buildAdoptSnapshotFrames(754 entries: Map<String, String>,755 tombstones: Map<String, Long>,756 duressSlot: String?,757): List<AdoptionFrame.Snapshot> {758 val includeDuress = !duressSlot.isNullOrBlank()759 760 761 val entryCap = MAX_SNAPSHOT_CHUNKS - 1762763 val chunks = mutableListOf<Map<String, String>>()764 var current = LinkedHashMap<String, String>()765 var currentBytes = 2 766 for ((id, envelope) in entries) {767 768 val entryBytes = AdoptJson.encodeToString(mapOf(id to envelope)).length + 1769 if (current.isNotEmpty() && currentBytes + entryBytes >= MAX_SNAPSHOT_CHUNK_BYTES) {770 chunks.add(current)771 current = LinkedHashMap()772 currentBytes = 2773 }774 current[id] = envelope775 currentBytes += entryBytes776 }777 chunks.add(current)778779 val entriesChunkCount = minOf(chunks.size, entryCap)780 val totalChunks = entriesChunkCount + 1781 val supplementalFrame = AdoptionFrame.Snapshot(782 chunkIndex = entriesChunkCount,783 chunkCount = totalChunks,784 entries = emptyMap(),785 tombstones = tombstones,786 duressSlot = duressSlot.takeIf { includeDuress },787 )788789 if (790 AdoptJson.encodeToString(AdoptionFrame.serializer(), supplementalFrame)791 .encodeToByteArray().size > SNAPSHOT_FRAME_WIRE_CEILING792 ) {793 if (includeDuress) throw SnapshotDuressFrameTooLargeException()794 throw IllegalStateException("ADOPT_SNAPSHOT_SUPPLEMENTAL_FRAME_TOO_LARGE")795 }796797 val frames = mutableListOf<AdoptionFrame.Snapshot>()798 for (index in 0 until entriesChunkCount) {799 frames.add(AdoptionFrame.Snapshot(800 chunkIndex = index,801 chunkCount = totalChunks,802 entries = chunks[index],803 tombstones = emptyMap(),804 duressSlot = null,805 ))806 }807 frames.add(supplementalFrame)808 return frames809}810811internal class SnapshotDuressFrameTooLargeException :812 IllegalStateException("ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE")813814815816817818819820821822823824825suspend fun receiveVaultSnapshot(826 channel: PairingTransport,827): ReceivedSnapshot {828 val acc = createAdoptSnapshotBudget()829 var chunkCount = -1830 var received = 0831 while (chunkCount == -1 || received < chunkCount) {832 val wire = channel.receive()833 if (wire.size > MAX_PADDED_SNAPSHOT_FRAME_BYTES) {834 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")835 }836 val raw = runCatching { SyncPadding.unpad(wire) }837 .getOrElse { throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME", it) }838 if (raw.size > MAX_ADOPT_SNAPSHOT_BYTES - acc.bytes) {839 throw IllegalStateException("ADOPT_SNAPSHOT_OVER_BUDGET")840 }841 if (raw.size > SNAPSHOT_FRAME_WIRE_CEILING) {842 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")843 }844 val frame = runCatching {845 AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(raw, Charsets.UTF_8))846 }.getOrNull()847 if (!isAdoptSnapshot(frame)) throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME")848 frame as AdoptionFrame.Snapshot849 if (chunkCount == -1) {850 chunkCount = frame.chunkCount851 if (chunkCount > MAX_SNAPSHOT_CHUNKS) {852 throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_CHUNKS")853 }854 } else if (frame.chunkCount != chunkCount) {855 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_COUNT_MISMATCH")856 }857 if (frame.chunkIndex != received) {858 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_OUT_OF_ORDER")859 }860 applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, raw.size)861 received++862 }863 return ReceivedSnapshot(acc.entries, acc.tombstones, acc.duressSlot)864}865866fun isDeviceType(value: String): Boolean =867 DeviceType.entries.any { it.wireValue == value }