eebf68e7c358
feat: Phase 11 — Codex: GF(2⁸) Reed-Solomon erasure, deflate+stripe codec, ZXing Aztec, A4 6×6 PdfDocument, generate+restore screens, SAF import/export, 4 RS/codec tests (v2.1.11)
- time
- 2026-06-03 03:39 UTC · 5 months ago
- machine
- koh2
- agent
- claude-opus-4-8
- session
- phase 8-12 sync autofill codex integrations
- parent
- 646d106e141d
↓ peach-android-eebf68e7.tar.gzatlas at this save
files changed14 files
app/build.gradle+2 −2app/src/main/java/com/peachpasswords/codex/CodexAztec.kt+66 −0app/src/main/java/com/peachpasswords/codex/CodexCodec.kt+142 −0app/src/main/java/com/peachpasswords/codex/CodexGenerator.kt+92 −0app/src/main/java/com/peachpasswords/codex/CodexPdf.kt+76 −0app/src/main/java/com/peachpasswords/codex/CodexRestore.kt+95 −0app/src/main/java/com/peachpasswords/codex/CodexTypes.kt+91 −0app/src/main/java/com/peachpasswords/codex/ReedSolomon.kt+196 −0app/src/main/java/com/peachpasswords/ui/PeachAppNavHost.kt+4 −2app/src/main/java/com/peachpasswords/ui/codex/CodexGenerateScreen.kt+138 −0app/src/main/java/com/peachpasswords/ui/codex/CodexRestoreScreen.kt+112 −0app/src/main/java/com/peachpasswords/ui/codex/CodexViewModel.kt+116 −0app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+37 −1app/src/test/java/com/peachpasswords/codex/CodexCodecTest.kt+63 −0app/build.gradle+2 −2
@@ -16,8 +16,8 @@1616 applicationId "com.peachpasswords"1717 minSdk 261818 targetSdk 3519- versionCode 20101020- versionName "2.1.10"19+ versionCode 20101120+ versionName "2.1.11"2121 2222 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"2323 vectorDrawables {app/src/main/java/com/peachpasswords/codex/CodexAztec.kt+66 −0
@@ -0,0 +1,66 @@1+package com.peachpasswords.codex2+3+import android.graphics.Bitmap4+import android.graphics.Color5+import com.google.zxing.BarcodeFormat6+import com.google.zxing.BinaryBitmap7+import com.google.zxing.DecodeHintType8+import com.google.zxing.EncodeHintType9+import com.google.zxing.LuminanceSource10+import com.google.zxing.RGBLuminanceSource11+import com.google.zxing.aztec.AztecReader12+import com.google.zxing.aztec.AztecWriter13+import com.google.zxing.common.GlobalHistogramBinarizer14+import com.google.zxing.common.HybridBinarizer15+16+/** Aztec encode/decode for one Codex chunk, via ZXing. */17+object CodexAztec {18+19+ /** Render an envelope JSON string into a square monochrome Aztec [Bitmap]. */20+ fun encode(content: String, sizePx: Int = 320): Bitmap {21+ val hints = mapOf(EncodeHintType.ERROR_CORRECTION to AZTEC_ECC_PERCENT)22+ val matrix = AztecWriter().encode(content, BarcodeFormat.AZTEC, sizePx, sizePx, hints)23+ val w = matrix.width24+ val h = matrix.height25+ val pixels = IntArray(w * h)26+ for (y in 0 until h) {27+ val row = y * w28+ for (x in 0 until w) {29+ pixels[row + x] = if (matrix[x, y]) Color.BLACK else Color.WHITE30+ }31+ }32+ return Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888).apply { setPixels(pixels, 0, w, 0, 0, w, h) }33+ }34+35+ /**36+ * Decode an Aztec code from a tightly-cropped [Bitmap]. A rendered,37+ * cropped single code decodes most reliably with PURE_BARCODE (skip the38+ * locate-in-scene search); fall back to the full detector for codes that39+ * carry surrounding bleed. Null if neither reads.40+ */41+ fun decode(bitmap: Bitmap): String? {42+ val w = bitmap.width43+ val h = bitmap.height44+ val pixels = IntArray(w * h)45+ bitmap.getPixels(pixels, 0, w, 0, 0, w, h)46+ val source: LuminanceSource = RGBLuminanceSource(w, h, pixels)47+ val pure = mapOf(DecodeHintType.PURE_BARCODE to true, DecodeHintType.TRY_HARDER to true)48+ val scene = mapOf(DecodeHintType.TRY_HARDER to true)49+ // Cross both binarizers (Hybrid is adaptive; Global handles flat,50+ // evenly-lit renders) with both detector modes — marginal codes that51+ // miss one combination usually read on another.52+ val attempts = listOf(53+ BinaryBitmap(HybridBinarizer(source)) to pure,54+ BinaryBitmap(HybridBinarizer(source)) to scene,55+ BinaryBitmap(GlobalHistogramBinarizer(source)) to pure,56+ )57+ for ((binarizer, hints) in attempts) {58+ try {59+ return AztecReader().decode(binarizer, hints).text60+ } catch (_: Exception) {61+ // try next strategy62+ }63+ }64+ return null65+ }66+}app/src/main/java/com/peachpasswords/codex/CodexCodec.kt+142 −0
@@ -0,0 +1,142 @@1+package com.peachpasswords.codex2+3+import kotlinx.serialization.json.Json4+import java.security.MessageDigest5+import java.util.Base646+import java.util.zip.Deflater7+import java.util.zip.Inflater8+9+/**10+ * Pure (Android-free) Codex byte pipeline: compress → stripe → Reed-Solomon →11+ * envelopes, and the inverse for restore. Kept independent of Aztec/PDF so the12+ * full round-trip is unit-testable on the JVM. Port of the browser13+ * `generate.ts` / `restore.ts` / `erasure.ts` byte handling.14+ */15+object CodexCodec {16+ val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }17+18+ private val urlEncoder = Base64.getUrlEncoder().withoutPadding()19+ private val urlDecoder = Base64.getUrlDecoder()20+21+ fun base64Url(bytes: ByteArray): String = urlEncoder.encodeToString(bytes)22+ fun fromBase64Url(s: String): ByteArray = urlDecoder.decode(s)23+24+ /** Uppercase hex of SHA-256(bytes) — per-chunk hash + vault fingerprint source. */25+ fun sha256Hex(bytes: ByteArray): String {26+ val digest = MessageDigest.getInstance("SHA-256").digest(bytes)27+ val sb = StringBuilder(digest.size * 2)28+ for (b in digest) sb.append("%02X".format(b.toInt() and 0xff))29+ return sb.toString()30+ }31+32+ fun deflate(data: ByteArray): ByteArray {33+ val deflater = Deflater(Deflater.BEST_COMPRESSION).apply { setInput(data); finish() }34+ val out = java.io.ByteArrayOutputStream(data.size / 2 + 32)35+ val buf = ByteArray(8192)36+ while (!deflater.finished()) out.write(buf, 0, deflater.deflate(buf))37+ deflater.end()38+ return out.toByteArray()39+ }40+41+ fun inflate(data: ByteArray): ByteArray {42+ val inflater = Inflater().apply { setInput(data) }43+ val out = java.io.ByteArrayOutputStream(data.size * 3 + 32)44+ val buf = ByteArray(8192)45+ while (!inflater.finished()) {46+ val n = inflater.inflate(buf)47+ if (n == 0 && inflater.needsInput()) break // trailing zero-pad reached48+ out.write(buf, 0, n)49+ }50+ inflater.end()51+ return out.toByteArray()52+ }53+54+ // ── Stripe layout ─────────────────────────────────────────────────────55+56+ fun planStripeShardCounts(totalDataShards: Int): IntArray {57+ if (totalDataShards <= 0) return IntArray(0)58+ val numStripes = maxOf(1, Math.ceil(totalDataShards.toDouble() / MAX_DATA_SHARDS_PER_STRIPE).toInt())59+ val base = totalDataShards / numStripes60+ val remainder = totalDataShards % numStripes61+ return IntArray(numStripes) { base + if (it < remainder) 1 else 0 }62+ }63+64+ data class Stripe(val dataShards: Int, val parityShards: Int, val shards: Array<ByteArray>) {65+ val totalChunks: Int get() = dataShards + parityShards66+ }67+68+ /** Compress + stripe + RS-encode into envelopes for [verifyCode]. */69+ fun encodeToEnvelopes(compressed: ByteArray, verifyCode: String): Pair<List<ChunkEnvelope>, CodexLayout> {70+ val totalDataShards = maxOf(1, Math.ceil(compressed.size.toDouble() / CHUNK_SIZE).toInt())71+ val counts = planStripeShardCounts(totalDataShards)72+ val envelopes = ArrayList<ChunkEnvelope>()73+ var offset = 074+ var totalData = 075+ var totalParity = 076+ for ((sIdx, dataShards) in counts.withIndex()) {77+ val region = dataShards * CHUNK_SIZE78+ val parityShards = computeParityShards(dataShards)79+ val total = dataShards + parityShards80+ val shards = Array(total) { ByteArray(CHUNK_SIZE) }81+ for (d in 0 until dataShards) {82+ val start = offset + d * CHUNK_SIZE83+ val len = (compressed.size - start).coerceIn(0, CHUNK_SIZE)84+ if (len > 0) System.arraycopy(compressed, start, shards[d], 0, len)85+ }86+ ReedSolomon.encode(shards, dataShards, parityShards)87+ for (i in 0 until total) {88+ envelopes.add(buildEnvelope(shards[i], i, total, i >= dataShards, verifyCode, sIdx, counts.size))89+ }90+ offset += region91+ totalData += dataShards92+ totalParity += parityShards93+ }94+ return envelopes to CodexLayout(counts.size, totalData, totalParity, totalData + totalParity)95+ }96+97+ private fun buildEnvelope(98+ chunk: ByteArray, index: Int, total: Int, isParity: Boolean,99+ verifyCode: String, stripe: Int, stripeCount: Int,100+ ): ChunkEnvelope = ChunkEnvelope(101+ v = 3, c = verifyCode, s = stripe, capS = stripeCount,102+ i = index, t = total, p = isParity,103+ d = base64Url(chunk), h = sha256Hex(chunk).take(32),104+ )105+106+ fun verifyChunkIntegrity(env: ChunkEnvelope): Boolean {107+ if (env.h.length != 16 && env.h.length != 32) return false108+ return sha256Hex(fromBase64Url(env.d)).take(env.h.length).equals(env.h, ignoreCase = true)109+ }110+111+ /**112+ * Reconstruct the compressed payload from scanned envelopes, tolerating113+ * lost codes via Reed-Solomon. Groups by stripe, reconstructs each, then114+ * concatenates the data regions in stripe order.115+ */116+ fun reconstructCompressed(envelopes: List<ChunkEnvelope>): ByteArray {117+ val good = envelopes.filter { verifyChunkIntegrity(it) }118+ if (good.isEmpty()) throw CodexException(CodexErrorCode.INSUFFICIENT_CHUNKS, "no valid chunks")119+ val byStripe = good.groupBy { it.s }120+ val stripeCount = good.maxOf { it.capS }121+ val out = java.io.ByteArrayOutputStream()122+ for (sIdx in 0 until stripeCount) {123+ val chunks = byStripe[sIdx]124+ ?: throw CodexException(CodexErrorCode.INSUFFICIENT_CHUNKS, "stripe $sIdx missing entirely")125+ val total = chunks.first().t126+ val (dataShards, parityShards) = deriveShardCounts(total)127+ val shards = Array(total) { ByteArray(0) }128+ val present = BooleanArray(total)129+ for (env in chunks) {130+ if (env.i in 0 until total) {131+ shards[env.i] = fromBase64Url(env.d)132+ present[env.i] = true133+ }134+ }135+ ReedSolomon.reconstruct(shards, dataShards, parityShards, present)136+ for (d in 0 until dataShards) out.write(shards[d])137+ }138+ return out.toByteArray()139+ }140+}141+142+data class CodexLayout(val stripeCount: Int, val dataChunks: Int, val parityChunks: Int, val totalChunks: Int)app/src/main/java/com/peachpasswords/codex/CodexGenerator.kt+92 −0
@@ -0,0 +1,92 @@1+package com.peachpasswords.codex2+3+import com.peachpasswords.vault.VaultRepository4+5+/** Generation milestones surfaced to the UI. */6+enum class CodexStep { COMPRESS, ERASURE, AZTEC, VERIFY, PDF }7+8+/**9+ * Full Codex generation: vault → payload → deflate → Reed-Solomon stripes →10+ * Aztec codes → A4 PDF. Each stage is a verification gate (this is the11+ * disaster-recovery surface), mirroring the browser `generate.ts`.12+ */13+object CodexGenerator {14+15+ suspend fun generate(16+ vault: VaultRepository,17+ now: Long,18+ onProgress: (CodexStep, Int, Int) -> Unit = { _, _, _ -> },19+ ): Pair<ByteArray, CodexManifest> {20+ if (!vault.isUnlocked.value) throw CodexException(CodexErrorCode.VAULT_LOCKED, "Vault must be unlocked")21+ val entryCount = vault.getEntries().size22+ if (entryCount == 0) throw CodexException(CodexErrorCode.VAULT_EMPTY, "Vault has no entries to back up")23+ val vaultBlob = vault.codexVaultBlobBase64()24+ ?: throw CodexException(CodexErrorCode.VAULT_EMPTY, "No vault to back up")25+26+ val fingerprint = CodexCodec.sha256Hex(vaultBlob.toByteArray(Charsets.UTF_8)).take(32)27+ val verifyCode = deriveVerifyCode(fingerprint)28+ val payload = CodexPayload(29+ version = 2, verifyCode = verifyCode, vaultBlob = vaultBlob,30+ timestamp = vault.getVaultVersion(), entryCount = entryCount,31+ vaultFingerprint = fingerprint, generatedAt = now,32+ )33+34+ onProgress(CodexStep.COMPRESS, 0, 1)35+ val payloadJson = CodexCodec.json.encodeToString(CodexPayload.serializer(), payload).toByteArray(Charsets.UTF_8)36+ val compressed = CodexCodec.deflate(payloadJson)37+ if (!CodexCodec.inflate(compressed).contentEquals(payloadJson)) {38+ throw CodexException(CodexErrorCode.COMPRESSION_ROUNDTRIP_FAILED, "deflate round-trip failed")39+ }40+41+ onProgress(CodexStep.ERASURE, 0, 1)42+ val (envelopes, layout) = CodexCodec.encodeToEnvelopes(compressed, verifyCode)43+44+ onProgress(CodexStep.AZTEC, 0, envelopes.size)45+ val aztecs = ArrayList<android.graphics.Bitmap>(envelopes.size)46+ envelopes.forEachIndexed { i, env ->47+ val jsonStr = CodexCodec.json.encodeToString(ChunkEnvelope.serializer(), env)48+ aztecs.add(CodexAztec.encode(jsonStr))49+ onProgress(CodexStep.AZTEC, i + 1, envelopes.size)50+ }51+52+ onProgress(CodexStep.VERIFY, 0, 1)53+ // Simulate the worst tolerated loss and confirm the payload rebuilds.54+ verifyReconstruction(envelopes, payload)55+56+ onProgress(CodexStep.PDF, 0, 1)57+ val manifest = CodexManifest(58+ verifyCode = verifyCode, totalChunks = layout.totalChunks,59+ dataChunks = layout.dataChunks, parityChunks = layout.parityChunks,60+ stripeCount = layout.stripeCount,61+ pageCount = Math.ceil(layout.totalChunks.toDouble() / CODES_PER_PAGE).toInt(),62+ entryCount = entryCount, vaultFingerprint = fingerprint, generatedAt = now,63+ )64+ val pdf = CodexPdf.render(aztecs, manifest)65+ if (pdf.size < 1000) throw CodexException(CodexErrorCode.PDF_GENERATION_FAILED, "PDF too small: ${pdf.size}")66+ return pdf to manifest67+ }68+69+ private fun verifyReconstruction(envelopes: List<ChunkEnvelope>, expected: CodexPayload) {70+ // Drop the per-stripe maximum tolerated codes, then rebuild end-to-end.71+ val byStripe = envelopes.groupBy { it.s }72+ val survivors = ArrayList<ChunkEnvelope>()73+ for ((_, chunks) in byStripe) {74+ val (_, parity) = deriveShardCounts(chunks.first().t)75+ survivors.addAll(chunks.drop(parity)) // lose `parity` codes from this stripe76+ }77+ val compressed = CodexCodec.reconstructCompressed(survivors)78+ val rebuilt = CodexCodec.json.decodeFromString(CodexPayload.serializer(), String(CodexCodec.inflate(compressed)))79+ if (rebuilt.verifyCode != expected.verifyCode) {80+ throw CodexException(CodexErrorCode.RECONSTRUCTION_VERIFY_CODE_MISMATCH, "verify code mismatch on simulation")81+ }82+ if (rebuilt.vaultFingerprint != expected.vaultFingerprint) {83+ throw CodexException(CodexErrorCode.RECONSTRUCTION_FINGERPRINT_MISMATCH, "fingerprint mismatch on simulation")84+ }85+ }86+87+ /** "PX-XXXX-XXXX" from the vault fingerprint hex — stable per vault state. */88+ private fun deriveVerifyCode(fingerprintHex: String): String {89+ val alnum = fingerprintHex.filter { it.isLetterOrDigit() }.uppercase().padEnd(8, '0').take(8)90+ return "PX-${alnum.substring(0, 4)}-${alnum.substring(4, 8)}"91+ }92+}app/src/main/java/com/peachpasswords/codex/CodexPdf.kt+76 −0
@@ -0,0 +1,76 @@1+package com.peachpasswords.codex2+3+import android.graphics.Bitmap4+import android.graphics.Color5+import android.graphics.Paint6+import android.graphics.Rect7+import android.graphics.pdf.PdfDocument8+import java.io.ByteArrayOutputStream9+10+/**11+ * Renders the Aztec codes onto an A4 PDF in a 6×6 grid — the printed Codex.12+ * A4 at 72pt/in is 595×842pt. Header carries the verify code; the footer13+ * carries the generation date and page counter so a re-collated stack stays14+ * unambiguous.15+ */16+object CodexPdf {17+ private const val PAGE_W = 59518+ private const val PAGE_H = 84219+ private const val MARGIN = 36f20+ private const val HEADER_H = 54f21+ private const val FOOTER_H = 28f22+23+ fun render(aztecs: List<Bitmap>, manifest: CodexManifest): ByteArray {24+ val doc = PdfDocument()25+ val gridTop = MARGIN + HEADER_H26+ val gridW = PAGE_W - 2 * MARGIN27+ val gridH = PAGE_H - gridTop - MARGIN - FOOTER_H28+ val cellW = gridW / CODES_PER_ROW29+ val cellH = gridH / CODES_PER_COL30+ val cell = minOf(cellW, cellH)31+ // Tighter padding → larger codes (~78pt, close to the browser's 80pt),32+ // which keeps modules above the camera/scan decode threshold.33+ val pad = cell * 0.05f34+35+ val title = Paint().apply { color = Color.BLACK; textSize = 16f; isAntiAlias = true; isFakeBoldText = true }36+ val mono = Paint().apply { color = Color.rgb(0x55, 0x55, 0x55); textSize = 9f; isAntiAlias = true }37+ val codePaint = Paint().apply { isFilterBitmap = false }38+39+ val pageCount = Math.ceil(aztecs.size.toDouble() / CODES_PER_PAGE).toInt().coerceAtLeast(1)40+ for (page in 0 until pageCount) {41+ val info = PdfDocument.PageInfo.Builder(PAGE_W, PAGE_H, page + 1).create()42+ val pg = doc.startPage(info)43+ val canvas = pg.canvas44+45+ canvas.drawText("Peach Codex", MARGIN, MARGIN + 18f, title)46+ canvas.drawText(manifest.verifyCode, MARGIN, MARGIN + 36f, mono)47+ canvas.drawText(48+ "${manifest.entryCount} entries · ${manifest.totalChunks} codes · keep with your recovery words",49+ MARGIN + 120f, MARGIN + 36f, mono,50+ )51+52+ val first = page * CODES_PER_PAGE53+ val last = minOf(first + CODES_PER_PAGE, aztecs.size)54+ for (idx in first until last) {55+ val slot = idx - first56+ val row = slot / CODES_PER_ROW57+ val col = slot % CODES_PER_ROW58+ val left = MARGIN + col * cell + pad59+ val top = gridTop + row * cell + pad60+ val dst = Rect(left.toInt(), top.toInt(), (left + cell - 2 * pad).toInt(), (top + cell - 2 * pad).toInt())61+ canvas.drawBitmap(aztecs[idx], null, dst, codePaint)62+ }63+64+ canvas.drawText(65+ "page ${page + 1} of $pageCount · ${manifest.verifyCode}",66+ MARGIN, PAGE_H - MARGIN + 4f, mono,67+ )68+ doc.finishPage(pg)69+ }70+71+ val out = ByteArrayOutputStream()72+ doc.writeTo(out)73+ doc.close()74+ return out.toByteArray()75+ }76+}app/src/main/java/com/peachpasswords/codex/CodexRestore.kt+95 −0
@@ -0,0 +1,95 @@1+package com.peachpasswords.codex2+3+import android.content.Context4+import android.graphics.Bitmap5+import android.graphics.Color6+import android.graphics.pdf.PdfRenderer7+import android.net.Uri8+import android.os.ParcelFileDescriptor9+10+/**11+ * Restore side: render a Codex PDF back to bitmaps, crop the 6×6 grid using the12+ * same geometry [CodexPdf] laid down, decode each Aztec, then Reed-Solomon13+ * reconstruct the payload — surviving missing or unreadable codes up to the14+ * parity budget.15+ */16+object CodexRestore {17+18+ data class ScanResult(val envelopes: List<ChunkEnvelope>, val cellsTried: Int, val decoded: Int)19+20+ fun decodeFromUri(context: Context, uri: Uri, onPage: (Int, Int) -> Unit = { _, _ -> }): ScanResult {21+ val pfd: ParcelFileDescriptor = context.contentResolver.openFileDescriptor(uri, "r")22+ ?: throw CodexException(CodexErrorCode.RESTORE_FAILED, "Cannot open file")23+ val found = LinkedHashMap<String, ChunkEnvelope>()24+ var cells = 025+ var decoded = 026+ pfd.use { descriptor ->27+ PdfRenderer(descriptor).use { renderer ->28+ val pages = renderer.pageCount29+ for (p in 0 until pages) {30+ onPage(p + 1, pages)31+ val page = renderer.openPage(p)32+ for (env in decodeGrid(page)) {33+ cells++34+ found.putIfAbsent("${env.s}:${env.i}", env)35+ decoded++36+ }37+ page.close()38+ }39+ }40+ }41+ return ScanResult(found.values.toList(), cells, decoded)42+ }43+44+ /**45+ * Render each grid cell directly into a high-res bitmap via a per-cell46+ * transform (CodexPdf geometry), then decode. Per-cell rendering keeps each47+ * Aztec at ~6 px/module without allocating a giant full-page bitmap.48+ */49+ private fun decodeGrid(page: PdfRenderer.Page): List<ChunkEnvelope> {50+ val margin = 36f51+ val gridTop = margin + 54f52+ val cell = minOf((595f - 2 * margin) / CODES_PER_ROW, (842f - gridTop - margin - 28f) / CODES_PER_COL)53+ val pad = cell * 0.05f // must match CodexPdf54+ val sizePt = cell - 2 * pad55+ val bleed = sizePt * 0.10f56+ val region = sizePt + 2 * bleed57+ val target = 64058+ val scale = target / region59+60+ val out = ArrayList<ChunkEnvelope>()61+ for (row in 0 until CODES_PER_COL) for (col in 0 until CODES_PER_ROW) {62+ val leftPt = margin + col * cell + pad - bleed63+ val topPt = gridTop + row * cell + pad - bleed64+ val cellBmp = Bitmap.createBitmap(target, target, Bitmap.Config.ARGB_8888)65+ cellBmp.eraseColor(Color.WHITE)66+ val m = android.graphics.Matrix().apply {67+ postTranslate(-leftPt, -topPt)68+ postScale(scale, scale)69+ }70+ page.render(cellBmp, null, m, PdfRenderer.Page.RENDER_MODE_FOR_PRINT)71+ val text = CodexAztec.decode(cellBmp)72+ cellBmp.recycle()73+ if (text != null) parseEnvelope(text)?.let(out::add)74+ }75+ return out76+ }77+78+ fun parseEnvelope(text: String): ChunkEnvelope? = try {79+ CodexCodec.json.decodeFromString(ChunkEnvelope.serializer(), text)80+ } catch (_: Exception) {81+ null82+ }83+84+ /** Rebuild and validate the payload from decoded envelopes. */85+ fun reconstructPayload(envelopes: List<ChunkEnvelope>): CodexPayload {86+ if (envelopes.isEmpty()) throw CodexException(CodexErrorCode.INSUFFICIENT_CHUNKS, "No codes decoded")87+ val compressed = CodexCodec.reconstructCompressed(envelopes)88+ val payload = CodexCodec.json.decodeFromString(CodexPayload.serializer(), String(CodexCodec.inflate(compressed)))89+ val fp = CodexCodec.sha256Hex(payload.vaultBlob.toByteArray(Charsets.UTF_8)).take(32)90+ if (fp != payload.vaultFingerprint) {91+ throw CodexException(CodexErrorCode.RECONSTRUCTION_FINGERPRINT_MISMATCH, "Fingerprint mismatch — codes corrupted")92+ }93+ return payload94+ }95+}app/src/main/java/com/peachpasswords/codex/CodexTypes.kt+91 −0
@@ -0,0 +1,91 @@1+package com.peachpasswords.codex2+3+import kotlinx.serialization.SerialName4+import kotlinx.serialization.Serializable5+6+/**7+ * Codex on-paper format constants and shapes — port of the browser8+ * `shared/codex-types.ts`. The Codex encodes the encrypted vault as Aztec9+ * barcodes on an A4 PDF; recovery words are never included (they live on paper10+ * separately by design).11+ */12+13+/** Bytes of binary data per chunk; each chunk becomes one Aztec code. */14+const val CHUNK_SIZE = 35015+16+/** Max data shards per RS stripe — GF(2⁸) caps total shards at 256. */17+const val MAX_DATA_SHARDS_PER_STRIPE = 20018+19+const val CODEX_MIN_PARITY_SHARDS = 220+const val CODEX_MAX_PARITY_SHARDS = 3521+const val CODEX_PARITY_RATIO = 0.1522+23+const val AZTEC_ECC_PERCENT = 2524+const val CODES_PER_ROW = 625+const val CODES_PER_COL = 626+const val CODES_PER_PAGE = CODES_PER_ROW * CODES_PER_COL27+28+/** Parity shards for a stripe with [dataShards] data shards (15%, clamped). */29+fun computeParityShards(dataShards: Int): Int =30+ minOf(CODEX_MAX_PARITY_SHARDS, maxOf(CODEX_MIN_PARITY_SHARDS, Math.ceil(dataShards * CODEX_PARITY_RATIO).toInt()))31+32+/**33+ * Invert [computeParityShards] from a printed total chunk count. Restore sees34+ * only the envelope's `t` field — no manifest — so we try each candidate35+ * parity count and pick the one that round-trips. Monotonicity guarantees a36+ * unique solution.37+ */38+fun deriveShardCounts(totalChunks: Int): Pair<Int, Int> {39+ for (parity in CODEX_MIN_PARITY_SHARDS..CODEX_MAX_PARITY_SHARDS) {40+ val data = totalChunks - parity41+ if (data < 1) continue42+ if (computeParityShards(data) == parity) return data to parity43+ }44+ throw CodexException(CodexErrorCode.ERASURE_VERIFICATION_FAILED, "Cannot derive shard layout for totalChunks=$totalChunks")45+}46+47+/** One Aztec barcode's contents. Single-letter fields mirror the browser JSON. */48+@Serializable49+data class ChunkEnvelope(50+ val v: Int = 3,51+ val c: String,52+ val s: Int = 0,53+ @SerialName("S") val capS: Int = 1,54+ val i: Int,55+ val t: Int,56+ val p: Boolean,57+ val d: String,58+ val h: String,59+)60+61+/** Payload the Codex encodes: both encrypted vault slots plus metadata. */62+@Serializable63+data class CodexPayload(64+ val version: Int = 2,65+ val verifyCode: String,66+ val vaultBlob: String,67+ val timestamp: Long,68+ val entryCount: Int,69+ val vaultFingerprint: String,70+ val generatedAt: Long,71+)72+73+data class CodexManifest(74+ val verifyCode: String,75+ val totalChunks: Int,76+ val dataChunks: Int,77+ val parityChunks: Int,78+ val stripeCount: Int,79+ val pageCount: Int,80+ val entryCount: Int,81+ val vaultFingerprint: String,82+ val generatedAt: Long,83+)84+85+enum class CodexErrorCode {86+ VAULT_LOCKED, VAULT_EMPTY, COMPRESSION_ROUNDTRIP_FAILED, ERASURE_VERIFICATION_FAILED,87+ AZTEC_GENERATION_FAILED, INSUFFICIENT_CHUNKS, RECONSTRUCTION_VERIFY_CODE_MISMATCH,88+ RECONSTRUCTION_FINGERPRINT_MISMATCH, PDF_GENERATION_FAILED, INVALID_VAULT_BLOB, RESTORE_FAILED,89+}90+91+class CodexException(val code: CodexErrorCode, message: String) : Exception(message)app/src/main/java/com/peachpasswords/codex/ReedSolomon.kt+196 −0
@@ -0,0 +1,196 @@1+package com.peachpasswords.codex2+3+/**4+ * Systematic Reed-Solomon erasure codec over GF(2⁸), Backblaze/JavaReedSolomon5+ * construction (Vandermonde matrix made systematic). Mirrors the role of the6+ * browser's `reed-solomon-erasure` WASM: encode fills parity shards in place;7+ * reconstruct repairs any missing shards given an availability mask, tolerating8+ * up to `parityShards` losses.9+ *10+ * Shards are equal-length byte arrays; the code operates byte-column-wise.11+ */12+object Galois {13+ private val EXP = IntArray(512)14+ private val LOG = IntArray(256)15+16+ init {17+ var x = 118+ for (i in 0 until 255) {19+ EXP[i] = x20+ LOG[x] = i21+ x = x shl 122+ if (x and 0x100 != 0) x = x xor 0x11d23+ }24+ for (i in 255 until 512) EXP[i] = EXP[i - 255]25+ }26+27+ fun mul(a: Int, b: Int): Int =28+ if (a == 0 || b == 0) 0 else EXP[LOG[a and 0xff] + LOG[b and 0xff]]29+30+ fun div(a: Int, b: Int): Int {31+ require(b != 0) { "divide by zero" }32+ if (a == 0) return 033+ return EXP[(LOG[a and 0xff] - LOG[b and 0xff] + 255) % 255]34+ }35+36+ /** Field exponentiation a^n (used to build the Vandermonde matrix). */37+ fun exp(a: Int, n: Int): Int {38+ if (n == 0) return 139+ if (a == 0) return 040+ var result = 141+ repeat(n) { result = mul(result, a) }42+ return result43+ }44+}45+46+/** Dense GF(2⁸) matrix with the operations RS needs (multiply, invert). */47+private class GfMatrix(val rows: Int, val cols: Int) {48+ val data = Array(rows) { IntArray(cols) }49+50+ fun times(other: GfMatrix): GfMatrix {51+ require(cols == other.rows)52+ val out = GfMatrix(rows, other.cols)53+ for (r in 0 until rows) for (c in 0 until other.cols) {54+ var v = 055+ for (k in 0 until cols) v = v xor Galois.mul(data[r][k], other.data[k][c])56+ out.data[r][c] = v57+ }58+ return out59+ }60+61+ /** Gaussian-elimination inverse. Throws if singular. */62+ fun invert(): GfMatrix {63+ require(rows == cols)64+ val work = GfMatrix(rows, cols * 2)65+ for (r in 0 until rows) {66+ System.arraycopy(data[r], 0, work.data[r], 0, cols)67+ work.data[r][cols + r] = 168+ }69+ work.gaussianEliminate()70+ val out = GfMatrix(rows, cols)71+ for (r in 0 until rows) System.arraycopy(work.data[r], cols, out.data[r], 0, cols)72+ return out73+ }74+75+ private fun gaussianEliminate() {76+ for (r in 0 until rows) {77+ if (data[r][r] == 0) {78+ var swap = r + 179+ while (swap < rows && data[swap][r] == 0) swap++80+ require(swap < rows) { "matrix is singular" }81+ val tmp = data[r]; data[r] = data[swap]; data[swap] = tmp82+ }83+ val pivot = data[r][r]84+ if (pivot != 1) for (c in 0 until cols) data[r][c] = Galois.div(data[r][c], pivot)85+ for (other in 0 until rows) {86+ if (other == r) continue87+ val factor = data[other][r]88+ if (factor != 0) for (c in 0 until cols) {89+ data[other][c] = data[other][c] xor Galois.mul(factor, data[r][c])90+ }91+ }92+ }93+ }94+95+ companion object {96+ /** Encoding matrix: rows 0..dataShards-1 form the identity (systematic). */97+ fun buildEncoding(dataShards: Int, totalShards: Int): GfMatrix {98+ val vander = GfMatrix(totalShards, dataShards)99+ for (r in 0 until totalShards) for (c in 0 until dataShards) {100+ vander.data[r][c] = Galois.exp(r, c)101+ }102+ val top = GfMatrix(dataShards, dataShards)103+ for (r in 0 until dataShards) System.arraycopy(vander.data[r], 0, top.data[r], 0, dataShards)104+ return vander.times(top.invert())105+ }106+ }107+}108+109+object ReedSolomon {110+111+ /** Fill the parity shards (indices dataShards..total-1) in place. */112+ fun encode(shards: Array<ByteArray>, dataShards: Int, parityShards: Int) {113+ val total = dataShards + parityShards114+ require(shards.size == total) { "shard count mismatch" }115+ val matrix = GfMatrix.buildEncoding(dataShards, total)116+ val shardSize = shards[0].size117+ for (parityRow in dataShards until total) {118+ val out = shards[parityRow]119+ for (b in 0 until shardSize) {120+ var v = 0121+ for (dataRow in 0 until dataShards) {122+ v = v xor Galois.mul(matrix.data[parityRow][dataRow], shards[dataRow][b].toInt() and 0xff)123+ }124+ out[b] = v.toByte()125+ }126+ }127+ }128+129+ /**130+ * Reconstruct missing shards in place. [present] marks which shards were131+ * recovered intact; at least [dataShards] must be present. Repairs the132+ * data shards (and, if asked, parity) by inverting the sub-matrix of133+ * present rows.134+ */135+ fun reconstruct(136+ shards: Array<ByteArray>,137+ dataShards: Int,138+ parityShards: Int,139+ present: BooleanArray,140+ ) {141+ val total = dataShards + parityShards142+ val shardSize = shards.first { it.isNotEmpty() }.size143+ val presentCount = present.count { it }144+ if (presentCount < dataShards) {145+ throw CodexException(CodexErrorCode.INSUFFICIENT_CHUNKS, "too few shards present: $presentCount < $dataShards")146+ }147+148+ val matrix = GfMatrix.buildEncoding(dataShards, total)149+150+ // Build a dataShards×dataShards sub-matrix from the first dataShards151+ // present rows, plus the corresponding present shard data.152+ val sub = GfMatrix(dataShards, dataShards)153+ val subShards = arrayOfNulls<ByteArray>(dataShards)154+ var subRow = 0155+ var r = 0156+ while (subRow < dataShards) {157+ if (present[r]) {158+ System.arraycopy(matrix.data[r], 0, sub.data[subRow], 0, dataShards)159+ subShards[subRow] = shards[r]160+ subRow++161+ }162+ r++163+ }164+ val decode = sub.invert()165+166+ // Recover every missing data shard.167+ for (missing in 0 until dataShards) {168+ if (present[missing]) continue169+ val out = ByteArray(shardSize)170+ for (b in 0 until shardSize) {171+ var v = 0172+ for (k in 0 until dataShards) {173+ v = v xor Galois.mul(decode.data[missing][k], subShards[k]!![b].toInt() and 0xff)174+ }175+ out[b] = v.toByte()176+ }177+ shards[missing] = out178+ present[missing] = true179+ }180+181+ // Recompute any missing parity from the now-complete data shards.182+ for (parityRow in dataShards until total) {183+ if (present[parityRow]) continue184+ val out = ByteArray(shardSize)185+ for (b in 0 until shardSize) {186+ var v = 0187+ for (dataRow in 0 until dataShards) {188+ v = v xor Galois.mul(matrix.data[parityRow][dataRow], shards[dataRow][b].toInt() and 0xff)189+ }190+ out[b] = v.toByte()191+ }192+ shards[parityRow] = out193+ present[parityRow] = true194+ }195+ }196+}app/src/main/java/com/peachpasswords/ui/PeachAppNavHost.kt+4 −2
@@ -12,6 +12,8 @@1212 import androidx.navigation.compose.composable1313 import androidx.navigation.compose.rememberNavController1414 import androidx.navigation.navArgument15+import com.peachpasswords.ui.codex.CodexGenerateScreen16+import com.peachpasswords.ui.codex.CodexRestoreScreen1517 import com.peachpasswords.ui.lock.LockScreen1618 import com.peachpasswords.ui.pairing.ChirpPairScreen1719 import com.peachpasswords.ui.screens.SimpleStub@@ -89,8 +91,8 @@8991 composable(PeachNav.SettingsSync.route) { SimpleStub("Sync", back) }9092 composable(PeachNav.SettingsAppearance.route) { SimpleStub("Appearance", back) }9193 composable(PeachNav.SettingsPro.route) { SimpleStub("Peach Pro", back) }92- composable(PeachNav.CodexGenerate.route) { SimpleStub("Codex backup", back) }93- composable(PeachNav.CodexRestore.route) { SimpleStub("Codex restore", back) }94+ composable(PeachNav.CodexGenerate.route) { CodexGenerateScreen(onBack = back) }95+ composable(PeachNav.CodexRestore.route) { CodexRestoreScreen(onBack = back, onRestored = back) }9496 composable(PeachNav.ChirpPair.route) { ChirpPairScreen(onBack = back) }9597 composable(PeachNav.Health.route) { SimpleStub("Vault health", back) }9698 composable(PeachNav.Trash.route) { SimpleStub("Trash", back) }app/src/main/java/com/peachpasswords/ui/codex/CodexGenerateScreen.kt+138 −0
@@ -0,0 +1,138 @@1+package com.peachpasswords.ui.codex2+3+import androidx.activity.compose.rememberLauncherForActivityResult4+import androidx.activity.result.contract.ActivityResultContracts5+import androidx.compose.foundation.background6+import androidx.compose.foundation.clickable7+import androidx.compose.foundation.layout.Arrangement8+import androidx.compose.foundation.layout.Box9+import androidx.compose.foundation.layout.Column10+import androidx.compose.foundation.layout.Row11+import androidx.compose.foundation.layout.Spacer12+import androidx.compose.foundation.layout.fillMaxSize13+import androidx.compose.foundation.layout.fillMaxWidth14+import androidx.compose.foundation.layout.height15+import androidx.compose.foundation.layout.padding16+import androidx.compose.foundation.layout.size17+import androidx.compose.foundation.shape.CircleShape18+import androidx.compose.foundation.shape.RoundedCornerShape19+import androidx.compose.material3.LinearProgressIndicator20+import androidx.compose.material3.Text21+import androidx.compose.runtime.Composable22+import androidx.compose.runtime.getValue23+import androidx.compose.ui.Alignment24+import androidx.compose.ui.Modifier25+import androidx.compose.ui.draw.clip26+import androidx.compose.ui.graphics.Color27+import androidx.compose.ui.text.font.FontStyle28+import androidx.compose.ui.unit.dp29+import androidx.compose.ui.unit.sp30+import androidx.hilt.navigation.compose.hiltViewModel31+import androidx.lifecycle.compose.collectAsStateWithLifecycle32+import com.peachpasswords.codex.CodexStep33+import com.peachpasswords.ui.theme.LocalPeachAccent34+import com.peachpasswords.ui.theme.PeachColors35+import com.peachpasswords.ui.theme.PeachType36+import com.peachpasswords.ui.theme.ShellBackground37+38+@Composable39+fun CodexGenerateScreen(onBack: () -> Unit, vm: CodexViewModel = hiltViewModel()) {40+ val state by vm.generate.collectAsStateWithLifecycle()41+ val accent = LocalPeachAccent.current42+ val saveLauncher = rememberLauncherForActivityResult(43+ ActivityResultContracts.CreateDocument("application/pdf"),44+ ) { uri -> uri?.let { vm.writePdf(it) } }45+46+ ShellBackground {47+ Column(Modifier.fillMaxSize().padding(horizontal = 24.dp)) {48+ CodexHeader("Codex backup", onBack)49+ Spacer(Modifier.height(8.dp))50+ Text(51+ "A printable PDF of Aztec codes that encodes your encrypted vault. Keep it with your recovery words — together they restore everything, even offline.",52+ color = PeachColors.T2, fontFamily = PeachType.Body, fontSize = 13.sp,53+ )54+ Spacer(Modifier.height(28.dp))55+56+ when (val s = state) {57+ is GenerateState.Idle ->58+ CodexButton("Generate Codex PDF", accent, filled = true) { vm.startGenerate(System.currentTimeMillis()) }59+60+ is GenerateState.Running -> Column {61+ Text(stepLabel(s.step), color = PeachColors.T1, fontFamily = PeachType.Mono, fontSize = 11.sp)62+ Spacer(Modifier.height(10.dp))63+ val frac = if (s.total > 0) s.current.toFloat() / s.total else 0f64+ LinearProgressIndicator(65+ progress = { if (s.step == CodexStep.AZTEC) frac else 0.5f },66+ modifier = Modifier.fillMaxWidth().height(3.dp),67+ color = accent, trackColor = PeachColors.S2,68+ )69+ if (s.step == CodexStep.AZTEC) {70+ Spacer(Modifier.height(6.dp))71+ Text("${s.current} / ${s.total} codes", color = PeachColors.T3, fontFamily = PeachType.Mono, fontSize = 9.sp)72+ }73+ }74+75+ is GenerateState.Done -> Column {76+ SummaryRow("verify code", s.manifest.verifyCode, accent)77+ SummaryRow("entries", s.manifest.entryCount.toString(), accent)78+ SummaryRow("codes", "${s.manifest.totalChunks} (${s.manifest.parityChunks} recovery)", accent)79+ SummaryRow("pages", s.manifest.pageCount.toString(), accent)80+ Spacer(Modifier.height(24.dp))81+ CodexButton("Save PDF…", accent, filled = true) { saveLauncher.launch("peach-codex.pdf") }82+ Spacer(Modifier.height(10.dp))83+ CodexButton("Generate again", PeachColors.T2, filled = false) { vm.startGenerate(System.currentTimeMillis()) }84+ }85+86+ is GenerateState.Error -> Column {87+ Text("Couldn't generate", color = PeachColors.Breach, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 19.sp)88+ Spacer(Modifier.height(6.dp))89+ Text(s.message, color = PeachColors.T2, fontFamily = PeachType.Body, fontSize = 13.sp)90+ Spacer(Modifier.height(20.dp))91+ CodexButton("Try again", accent, filled = true) { vm.startGenerate(System.currentTimeMillis()) }92+ }93+ }94+ }95+ }96+}97+98+private fun stepLabel(step: CodexStep): String = when (step) {99+ CodexStep.COMPRESS -> "compressing vault…"100+ CodexStep.ERASURE -> "adding recovery codes…"101+ CodexStep.AZTEC -> "drawing Aztec codes…"102+ CodexStep.VERIFY -> "verifying it rebuilds…"103+ CodexStep.PDF -> "laying out the page…"104+}105+106+@Composable107+internal fun CodexHeader(title: String, onBack: () -> Unit) {108+ Row(109+ modifier = Modifier.fillMaxWidth().padding(top = 12.dp).height(48.dp),110+ verticalAlignment = Alignment.CenterVertically,111+ ) {112+ Text("‹", color = PeachColors.T1, fontSize = 26.sp,113+ modifier = Modifier.clip(CircleShape).clickable(onClick = onBack).padding(horizontal = 8.dp))114+ Spacer(Modifier.size(8.dp))115+ Text(title, color = PeachColors.T0, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 19.sp)116+ }117+}118+119+@Composable120+private fun SummaryRow(label: String, value: String, accent: Color) {121+ Row(Modifier.fillMaxWidth().padding(vertical = 7.dp), horizontalArrangement = Arrangement.SpaceBetween) {122+ Text(label, color = PeachColors.T2, fontFamily = PeachType.Mono, fontSize = 10.sp)123+ Text(value, color = accent, fontFamily = PeachType.Mono, fontSize = 12.sp)124+ }125+}126+127+@Composable128+internal fun CodexButton(label: String, color: Color, filled: Boolean, onClick: () -> Unit) {129+ val accent = LocalPeachAccent.current130+ Box(131+ modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp))132+ .background(if (filled) accent.copy(alpha = 0.14f) else Color.Transparent)133+ .clickable(onClick = onClick).padding(vertical = 15.dp),134+ contentAlignment = Alignment.Center,135+ ) {136+ Text(label, color = if (filled) accent else color, fontFamily = PeachType.Mono, fontSize = 13.sp)137+ }138+}app/src/main/java/com/peachpasswords/ui/codex/CodexRestoreScreen.kt+112 −0
@@ -0,0 +1,112 @@1+package com.peachpasswords.ui.codex2+3+import androidx.activity.compose.rememberLauncherForActivityResult4+import androidx.activity.result.contract.ActivityResultContracts5+import androidx.compose.foundation.layout.Arrangement6+import androidx.compose.foundation.layout.Column7+import androidx.compose.foundation.layout.Row8+import androidx.compose.foundation.layout.Spacer9+import androidx.compose.foundation.layout.fillMaxSize10+import androidx.compose.foundation.layout.fillMaxWidth11+import androidx.compose.foundation.layout.height12+import androidx.compose.foundation.layout.padding13+import androidx.compose.foundation.text.KeyboardOptions14+import androidx.compose.material3.OutlinedTextField15+import androidx.compose.material3.Text16+import androidx.compose.runtime.Composable17+import androidx.compose.runtime.getValue18+import androidx.compose.runtime.mutableStateOf19+import androidx.compose.runtime.remember20+import androidx.compose.runtime.setValue21+import androidx.compose.ui.Modifier22+import androidx.compose.ui.graphics.Color23+import androidx.compose.ui.text.font.FontStyle24+import androidx.compose.ui.text.input.PasswordVisualTransformation25+import androidx.compose.ui.unit.dp26+import androidx.compose.ui.unit.sp27+import androidx.hilt.navigation.compose.hiltViewModel28+import androidx.lifecycle.compose.collectAsStateWithLifecycle29+import com.peachpasswords.ui.theme.LocalPeachAccent30+import com.peachpasswords.ui.theme.PeachColors31+import com.peachpasswords.ui.theme.PeachType32+import com.peachpasswords.ui.theme.ShellBackground33+34+@Composable35+fun CodexRestoreScreen(onBack: () -> Unit, onRestored: () -> Unit, vm: CodexViewModel = hiltViewModel()) {36+ val state by vm.restore.collectAsStateWithLifecycle()37+ val accent = LocalPeachAccent.current38+ val pickLauncher = rememberLauncherForActivityResult(39+ ActivityResultContracts.GetContent(),40+ ) { uri -> uri?.let { vm.scan(it) } }41+42+ ShellBackground {43+ Column(Modifier.fillMaxSize().padding(horizontal = 24.dp)) {44+ CodexHeader("Codex restore", onBack)45+ Spacer(Modifier.height(8.dp))46+ Text(47+ "Choose a Codex PDF. Peach reads its Aztec codes — even if some pages are missing or smudged — and rebuilds your encrypted vault. You'll need the master password.",48+ color = PeachColors.T2, fontFamily = PeachType.Body, fontSize = 13.sp,49+ )50+ Spacer(Modifier.height(28.dp))51+52+ when (val s = state) {53+ is RestoreState.Idle ->54+ CodexButton("Choose Codex PDF", accent, filled = true) { pickLauncher.launch("application/pdf") }55+56+ is RestoreState.Scanning -> Text(57+ if (s.pages == 0) "Reading…" else "Reading page ${s.page} of ${s.pages}…",58+ color = PeachColors.T1, fontFamily = PeachType.Mono, fontSize = 12.sp,59+ )60+61+ is RestoreState.Decoded -> DecodedBody(s, accent, vm, onRestored)62+63+ is RestoreState.Restoring ->64+ Text("Restoring vault…", color = PeachColors.T1, fontFamily = PeachType.Mono, fontSize = 12.sp)65+66+ is RestoreState.Restored ->67+ Text("Vault restored.", color = accent, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 22.sp)68+69+ is RestoreState.Error -> Column {70+ Text("Couldn't restore", color = PeachColors.Breach, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 19.sp)71+ Spacer(Modifier.height(6.dp))72+ Text(s.message, color = PeachColors.T2, fontFamily = PeachType.Body, fontSize = 13.sp)73+ Spacer(Modifier.height(20.dp))74+ CodexButton("Choose another file", accent, filled = true) { vm.resetRestore(); pickLauncher.launch("application/pdf") }75+ }76+ }77+ }78+ }79+}80+81+@Composable82+private fun DecodedBody(s: RestoreState.Decoded, accent: Color, vm: CodexViewModel, onRestored: () -> Unit) {83+ var password by remember { mutableStateOf("") }84+ Column {85+ Row(Modifier.fillMaxWidth().padding(vertical = 7.dp), horizontalArrangement = Arrangement.SpaceBetween) {86+ Text("verify code", color = PeachColors.T2, fontFamily = PeachType.Mono, fontSize = 10.sp)87+ Text(s.payload.verifyCode, color = accent, fontFamily = PeachType.Mono, fontSize = 12.sp)88+ }89+ Row(Modifier.fillMaxWidth().padding(vertical = 7.dp), horizontalArrangement = Arrangement.SpaceBetween) {90+ Text("entries", color = PeachColors.T2, fontFamily = PeachType.Mono, fontSize = 10.sp)91+ Text(s.payload.entryCount.toString(), color = accent, fontFamily = PeachType.Mono, fontSize = 12.sp)92+ }93+ Row(Modifier.fillMaxWidth().padding(vertical = 7.dp), horizontalArrangement = Arrangement.SpaceBetween) {94+ Text("codes read", color = PeachColors.T2, fontFamily = PeachType.Mono, fontSize = 10.sp)95+ Text(s.codesFound.toString(), color = accent, fontFamily = PeachType.Mono, fontSize = 12.sp)96+ }97+ Spacer(Modifier.height(20.dp))98+ OutlinedTextField(99+ value = password,100+ onValueChange = { password = it },101+ placeholder = { Text("master password", color = PeachColors.T3, fontFamily = PeachType.Mono, fontSize = 13.sp) },102+ visualTransformation = PasswordVisualTransformation(),103+ keyboardOptions = KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Password),104+ singleLine = true,105+ modifier = Modifier.fillMaxWidth(),106+ )107+ Spacer(Modifier.height(16.dp))108+ CodexButton("Restore this vault", accent, filled = true) {109+ if (password.isNotEmpty()) vm.confirmRestore(password, onRestored)110+ }111+ }112+}app/src/main/java/com/peachpasswords/ui/codex/CodexViewModel.kt+116 −0
@@ -0,0 +1,116 @@1+package com.peachpasswords.ui.codex2+3+import android.content.Context4+import android.net.Uri5+import androidx.lifecycle.ViewModel6+import androidx.lifecycle.viewModelScope7+import com.peachpasswords.codex.CodexException8+import com.peachpasswords.codex.CodexGenerator9+import com.peachpasswords.codex.CodexManifest10+import com.peachpasswords.codex.CodexPayload11+import com.peachpasswords.codex.CodexRestore12+import com.peachpasswords.codex.CodexStep13+import com.peachpasswords.vault.UnlockResult14+import com.peachpasswords.vault.VaultRepository15+import dagger.hilt.android.lifecycle.HiltViewModel16+import dagger.hilt.android.qualifiers.ApplicationContext17+import kotlinx.coroutines.Dispatchers18+import kotlinx.coroutines.flow.MutableStateFlow19+import kotlinx.coroutines.flow.StateFlow20+import kotlinx.coroutines.flow.asStateFlow21+import kotlinx.coroutines.launch22+import kotlinx.coroutines.withContext23+import javax.inject.Inject24+25+sealed interface GenerateState {26+ data object Idle : GenerateState27+ data class Running(val step: CodexStep, val current: Int, val total: Int) : GenerateState28+ data class Done(val manifest: CodexManifest, val pdf: ByteArray) : GenerateState29+ data class Error(val message: String) : GenerateState30+}31+32+sealed interface RestoreState {33+ data object Idle : RestoreState34+ data class Scanning(val page: Int, val pages: Int) : RestoreState35+ data class Decoded(val payload: CodexPayload, val codesFound: Int) : RestoreState36+ data object Restoring : RestoreState37+ data object Restored : RestoreState38+ data class Error(val message: String) : RestoreState39+}40+41+@HiltViewModel42+class CodexViewModel @Inject constructor(43+ @ApplicationContext private val context: Context,44+ private val vault: VaultRepository,45+) : ViewModel() {46+47+ private val _generate = MutableStateFlow<GenerateState>(GenerateState.Idle)48+ val generate: StateFlow<GenerateState> = _generate.asStateFlow()49+50+ private val _restore = MutableStateFlow<RestoreState>(RestoreState.Idle)51+ val restore: StateFlow<RestoreState> = _restore.asStateFlow()52+53+ fun startGenerate(now: Long) {54+ _generate.value = GenerateState.Running(CodexStep.COMPRESS, 0, 1)55+ viewModelScope.launch {56+ try {57+ val (pdf, manifest) = withContext(Dispatchers.Default) {58+ CodexGenerator.generate(vault, now) { step, cur, total ->59+ _generate.value = GenerateState.Running(step, cur, total)60+ }61+ }62+ _generate.value = GenerateState.Done(manifest, pdf)63+ } catch (e: CodexException) {64+ _generate.value = GenerateState.Error(e.message ?: e.code.name)65+ } catch (e: Exception) {66+ _generate.value = GenerateState.Error(e.message ?: "generation_failed")67+ }68+ }69+ }70+71+ fun writePdf(uri: Uri): Boolean = try {72+ val pdf = (_generate.value as? GenerateState.Done)?.pdf ?: return false73+ context.contentResolver.openOutputStream(uri)?.use { it.write(pdf) } != null74+ } catch (_: Exception) {75+ false76+ }77+78+ fun scan(uri: Uri) {79+ _restore.value = RestoreState.Scanning(0, 0)80+ viewModelScope.launch {81+ try {82+ val payload = withContext(Dispatchers.Default) {83+ val result = CodexRestore.decodeFromUri(context, uri) { page, pages ->84+ _restore.value = RestoreState.Scanning(page, pages)85+ }86+ if (result.envelopes.isEmpty()) {87+ throw CodexException(88+ com.peachpasswords.codex.CodexErrorCode.INSUFFICIENT_CHUNKS,89+ "No Aztec codes could be read from this file",90+ )91+ }92+ CodexRestore.reconstructPayload(result.envelopes) to result.envelopes.size93+ }94+ _restore.value = RestoreState.Decoded(payload.first, payload.second)95+ } catch (e: CodexException) {96+ _restore.value = RestoreState.Error(e.message ?: e.code.name)97+ } catch (e: Exception) {98+ _restore.value = RestoreState.Error(e.message ?: "restore_failed")99+ }100+ }101+ }102+103+ fun confirmRestore(password: String, onDone: () -> Unit) {104+ val payload = (_restore.value as? RestoreState.Decoded)?.payload ?: return105+ _restore.value = RestoreState.Restoring106+ viewModelScope.launch {107+ when (val r = vault.restoreFromCodex(payload.vaultBlob, password)) {108+ is UnlockResult.Success -> { _restore.value = RestoreState.Restored; onDone() }109+ is UnlockResult.WrongPassword -> _restore.value = RestoreState.Error("Wrong master password")110+ is UnlockResult.Error -> _restore.value = RestoreState.Error(r.reason)111+ }112+ }113+ }114+115+ fun resetRestore() { _restore.value = RestoreState.Idle }116+}app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+37 −1
@@ -62,6 +62,39 @@6262 6363 fun hasVault(): Boolean = store.hasVault()6464 65+ // ---- Codex (printed paper backup) -------------------------------------66+67+ /**68+ * The at-rest slot-A envelope as base64 JSON `{"a": <StoredVault>}` — the69+ * Codex payload's vaultBlob. Slot B is noise, so it is omitted. Restorable70+ * on any device that has the master password. Null when no vault exists.71+ */72+ fun codexVaultBlobBase64(): String? {73+ val slotA = store.loadSlotA() ?: return null74+ val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""75+ return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))76+ }77+78+ /**79+ * Replace the local vault from a Codex blob, then unlock with [password].80+ * Writes slot A (and a size-matched noise slot B) before unlocking so the81+ * restored vault is at rest exactly as a freshly-created one would be.82+ */83+ suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {84+ return try {85+ val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)86+ val slotJson = Regex("\"a\"\\s*:\\s*(\\{.*\\})\\s*}\\s*$").find(wrapperJson)?.groupValues?.get(1)87+ ?: return UnlockResult.Error("invalid_codex_blob")88+ val slotA = VaultCodec.decodeSlot(slotJson) ?: return UnlockResult.Error("invalid_codex_blob")89+ if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")90+ writeMatchingNoiseSlotB(slotA)91+ store.stampLocalMutation()92+ unlockLocked(password)93+ } catch (e: Exception) {94+ UnlockResult.Error(e.message ?: "restore_failed")95+ }96+ }97+6598 suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {6699 return try {67100 val salt = VaultCrypto.generateSalt()@@ -83,7 +116,10 @@83116 }84117 }85118 86- suspend fun unlock(password: String): UnlockResult = mutex.withLock {119+ suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }120+121+ /** Unlock body without acquiring the mutex — callers must already hold it. */122+ private fun unlockLocked(password: String): UnlockResult {87123 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")88124 return try {89125 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))app/src/test/java/com/peachpasswords/codex/CodexCodecTest.kt+63 −0
@@ -0,0 +1,63 @@1+package com.peachpasswords.codex2+3+import org.junit.Assert.assertArrayEquals4+import org.junit.Assert.assertEquals5+import org.junit.Assert.assertTrue6+import org.junit.Test7+import kotlin.random.Random8+9+class CodexCodecTest {10+11+ @Test fun rs_recovers_dropped_shards() {12+ val data = 613+ val parity = computeParityShards(data) // 214+ val size = 4015+ val rng = Random(7)16+ val original = Array(data) { ByteArray(size) { rng.nextInt().toByte() } }17+ val shards = Array(data + parity) { i -> if (i < data) original[i].copyOf() else ByteArray(size) }18+ ReedSolomon.encode(shards, data, parity)19+20+ // Drop `parity` shards (the max tolerable) — here drop 2 data shards.21+ val present = BooleanArray(data + parity) { true }22+ shards[1] = ByteArray(0); present[1] = false23+ shards[4] = ByteArray(0); present[4] = false24+ ReedSolomon.reconstruct(shards, data, parity, present)25+26+ for (i in 0 until data) assertArrayEquals("shard $i", original[i], shards[i])27+ }28+29+ @Test fun gf_mul_div_are_inverse() {30+ for (a in 1..255) for (b in 1..255) {31+ assertEquals(a, Galois.div(Galois.mul(a, b), b))32+ }33+ }34+35+ @Test fun full_codec_round_trip() {36+ val payload = CodexPayload(37+ version = 2, verifyCode = "PX-AB12-CD34",38+ vaultBlob = "x".repeat(5000), timestamp = 111, entryCount = 7,39+ vaultFingerprint = "DEADBEEF".repeat(4), generatedAt = 222,40+ )41+ val bytes = CodexCodec.json.encodeToString(CodexPayload.serializer(), payload).toByteArray()42+ val compressed = CodexCodec.deflate(bytes)43+ assertArrayEquals(bytes, CodexCodec.inflate(compressed))44+45+ val (envelopes, layout) = CodexCodec.encodeToEnvelopes(compressed, payload.verifyCode)46+ assertTrue(envelopes.all { CodexCodec.verifyChunkIntegrity(it) })47+ assertEquals(layout.dataChunks + layout.parityChunks, envelopes.size)48+49+ // Lose the maximum tolerable codes in stripe 0, then rebuild.50+ val parity = layout.parityChunks / layout.stripeCount51+ val survivors = envelopes.toMutableList()52+ repeat(parity) { survivors.removeAt(0) } // drop first `parity` data shards53+ val recovered = CodexCodec.reconstructCompressed(survivors)54+ val parsed = CodexCodec.json.decodeFromString(CodexPayload.serializer(), String(CodexCodec.inflate(recovered)))55+ assertEquals(payload, parsed)56+ }57+58+ @Test fun corrupted_chunk_fails_integrity() {59+ val (envelopes, _) = CodexCodec.encodeToEnvelopes(CodexCodec.deflate("hello world".toByteArray()), "PX-0000-0000")60+ val tampered = envelopes.first().copy(d = CodexCodec.base64Url("tampered".toByteArray()))61+ assertTrue(!CodexCodec.verifyChunkIntegrity(tampered))62+ }63+}