feat: a pure-Kotlin codec for v3 recovery codes (recovery-code-v3, Phase 1)

Parse, normalise, validate, locate a typo and generate Muun's nine-block
recovery codes, ported from libwallet's recoverycode at 7d58eb2e and run
against all 77 of the spec's normative vectors. A located typo is a
suggestion the caller has to accept; it never becomes a code on its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-25 22:58:11 +02:00
1 parent dffe64c3d5
commit ed706d5f80
6 files changed
+1205

No files matched your search

@@ -0,0 +1,157 @@
package mobi.giza.compose.identity.recoverycode
import com.vitorpamplona.crypto.random.RandomInstance
import fr.acinq.bitcoin.ByteVector32
import fr.acinq.bitcoin.PrivateKey
import fr.acinq.bitcoin.crypto.Digest
import fr.acinq.bitcoin.crypto.hmac
import mobi.giza.compose.identity.recoverycode.RecoveryCodeFormat.Checked
/**
* Why an input is not a recovery code. The first check to fail decides it, in the order of
* the spec's §4 -- which the spec's vectors assert.
*/
enum class RecoveryCodeProblem {
/** The wrong number of symbols for the version the first two name. */
Length,
/** A symbol outside the alphabet, or a dash out of place. */
Characters,
/** `L` followed by a symbol that names no version this app knows. */
Version,
/** Well formed, and the ninth block disagrees: a typo, more than one symbol's worth. */
Checksum,
}
/**
* A version 3 recovery code, canonical and checksummed: nine blocks of four, 44 characters
* with their dashes. The only way to hold one is through [parse] or [generate], so a
* `RecoveryCode` is always one that derives a key.
*
* The format is Muun's (libwallet's `recoverycode`, at the `recovery-code-v3-checksum`
* branch of `kngako/libwallet`); what Giza derives from it is Giza's. See
* docs/recovery-code-v3.md.
*/
class RecoveryCode private constructor(
/** The 44-character form, dashes included. This exact string is what [rootKey] hashes. */
val canonical: String,
) {
/** The nine blocks, in order, for showing a person one at a time. */
val blocks: List<String> get() = canonical.split('-')
/**
* `HMAC-SHA256(key = "muun:rc", message = canonical)` -- the spec's §7 for versions 2 and
* 3. Thirty-two bytes, and the root of everything a code derives.
*/
fun rootKey(): ByteVector32 = ByteVector32(rootKeyOf(canonical))
override fun equals(other: Any?): Boolean = other is RecoveryCode && other.canonical == canonical
override fun hashCode(): Int = canonical.hashCode()
/** Never the code: it is a secret, and a log line is not a place for one. */
override fun toString(): String = "RecoveryCode(***)"
companion object {
private val KDF_KEY = "muun:rc".encodeToByteArray()
private fun rootKeyOf(canonical: String): ByteArray =
Digest.sha256().hmac(KDF_KEY, canonical.encodeToByteArray(), 64)
/**
* What [input] is, read as a person types a code: any case, dashes or spaces or
* neither. A [Parse.Typo] is a suggestion and nothing more; the only way to turn one
* into a [RecoveryCode] is for a person to accept [Parse.Typo.suggested].
*/
fun parse(input: String): Parse {
val canonical = when (val normalized = RecoveryCodeFormat.normalize(input)) {
is Checked.Ok -> normalized.value
is Checked.Failed -> return typoOr(input, normalized.problem)
}
return when (val version = RecoveryCodeFormat.version(canonical)) {
is Checked.Failed -> typoOr(input, version.problem)
is Checked.Ok -> when (version.value) {
3 -> Parse.Valid(RecoveryCode(canonical))
else -> Parse.UnsupportedVersion(version.value)
}
}
}
/**
* A typo where there is exactly one, and otherwise the problem as found. A version
* symbol mistyped -- `LC…` for `LB…` -- fails normalisation before it fails the
* checksum, so a 36-symbol input is searched whatever the first failure was.
*/
private fun typoOr(input: String, problem: RecoveryCodeProblem): Parse {
val typo = RecoveryCodeFormat.locateTypo(input)
if (typo != null) return Parse.Typo(typo.position, RecoveryCode(typo.corrected))
return Parse.Invalid(problem)
}
/**
* A fresh version 3 code: `L`, `B`, thirty symbols drawn without modulo bias, and the
* checksum block.
*
* Each symbol is one byte from [random], rejected below `256 % 30 = 16` so that the
* bytes kept are an exact multiple of thirty. That threshold is the one libwallet
* fixed in `75e43b45`: the idiom it replaced rejected nothing, and the first sixteen
* symbols came up 9/256 of the time instead of 8/256.
*
* A code whose root key is not a valid secp256k1 scalar is drawn again -- about one in
* 2¹²⁸ -- so that every code Giza makes is a valid key to every implementation of the
* spec, which calls the key a scalar.
*/
fun generate(random: (Int) -> ByteArray = RandomInstance::bytes): RecoveryCode {
while (true) {
val symbols = CharArray(RecoveryCodeFormat.V3_SYMBOLS)
symbols[0] = 'L'
symbols[1] = RecoveryCodeFormat.versionChar(3)
for (i in 0 until RecoveryCodeFormat.RANDOM_SYMBOLS) symbols[2 + i] = randomSymbol(random)
val (s1, s2) = RecoveryCodeFormat.checksum(symbols)
RecoveryCodeFormat.encodeChecksum(s1, s2).copyInto(symbols, RecoveryCodeFormat.BODY_SYMBOLS)
val canonical = RecoveryCodeFormat.format(symbols.concatToString())
if (PrivateKey(rootKeyOf(canonical)).isValid()) return RecoveryCode(canonical)
}
}
private fun randomSymbol(random: (Int) -> ByteArray): Char {
val alphabet = RecoveryCodeFormat.ALPHABET
val min = 256 % alphabet.length
while (true) {
val r = random(1)[0].toInt() and 0xff
if (r < min) continue
return alphabet[r % alphabet.length]
}
}
/**
* How many blocks a code beginning with [prefix] has -- 8 for the older versions, 9 for
* version 3 -- or null while the prefix cannot tell. For an input that sizes itself.
*/
fun blockCount(prefix: String): Int? = RecoveryCodeFormat.blockCount(prefix)
}
/** What an input turned out to be. */
sealed interface Parse {
data class Valid(val code: RecoveryCode) : Parse
/**
* One symbol away from exactly one valid code. [position] is 0-based over the 36
* symbols, dashes excluded; [block] and [character] are 1-based, for a sentence.
*/
data class Typo(val position: Int, val suggested: RecoveryCode) : Parse {
val block: Int get() = position / RecoveryCodeFormat.BLOCK_SIZE + 1
val character: Int get() = position % RecoveryCodeFormat.BLOCK_SIZE + 1
/** The symbol the suggestion puts at [position]. */
val suggestedSymbol: Char get() = suggested.canonical.filter { it != '-' }[position]
}
/** Not a code, or a code with more wrong than one symbol can explain. */
data class Invalid(val problem: RecoveryCodeProblem) : Parse
/** A well-formed code of version 1 or 2. Giza never made either. */
data class UnsupportedVersion(val version: Int) : Parse
}
}
@@ -0,0 +1,194 @@
package mobi.giza.compose.identity.recoverycode
/**
* Muun's recovery code format, versions 1 to 3, as specified on the
* `recovery-code-v3-checksum` branch of `kngako/libwallet` at `7d58eb2e`
* (`recoverycode/SPEC.md`). One function per section of the spec, so that each is tested
* against its own table of the spec's vectors; see docs/recovery-code-v3.md, Phase 1.
*
* Internal: the app reads codes through [RecoveryCode.parse] and makes them through
* [RecoveryCode.generate]. This is the arithmetic underneath, ported line for line from
* libwallet's `recoverycode.go` so that a disagreement with the Go is a bug here.
*/
internal object RecoveryCodeFormat {
/** The thirty symbols of a version 2 or 3 code: no `0 1 6 G I O`. */
const val ALPHABET = "ABCDEFHJKLMNPQRSTUVWXYZ2345789"
/** The twenty-nine symbols of a version 1 code: [ALPHABET] without `L`. */
const val ALPHABET_LEGACY = "ABCDEFHJKMNPQRSTUVWXYZ2345789"
const val LATEST_VERSION = 3
const val BLOCK_SIZE = 4
const val RANDOM_SYMBOLS = 30
/** `L`, the version symbol, and the random symbols: what the checksum covers. */
const val BODY_SYMBOLS = 32
/** A version 3 code without its dashes. */
const val V3_SYMBOLS = 36
const val LEGACY_BLOCKS = 8
const val V3_BLOCKS = 9
/** Prime, and above every weight times every symbol difference, so none of them is zero. */
private const val CHECKSUM_MODULUS = 887
sealed interface Checked<out T> {
data class Ok<T>(val value: T) : Checked<T>
data class Failed(val problem: RecoveryCodeProblem) : Checked<Nothing>
}
/** A single wrong symbol and the one valid code it is a symbol away from (§6). */
data class Typo(val position: Int, val corrected: String)
/** The version symbol of a version 2 or later code. Version 2 is the alphabet's first symbol. */
fun versionChar(version: Int): Char = ALPHABET[version - 2]
private fun versionFromChar(c: Char): Int? {
val index = ALPHABET.indexOf(c)
if (index == -1) return null
val version = index + 2
return if (version > LATEST_VERSION) null else version
}
private fun blockCountFor(version: Int): Int = if (version >= 3) V3_BLOCKS else LEGACY_BLOCKS
private fun formattedLength(blocks: Int): Int = blocks * (BLOCK_SIZE + 1) - 1
/**
* §4. The version of a code that is already canonical: upper case, dashes in place, no
* whitespace. Strict on purpose -- [normalize] is what forgives.
*/
fun version(code: String): Checked<Int> {
if (code.length >= 2 && code[0] == 'L') {
val version = versionFromChar(code[1]) ?: return Checked.Failed(RecoveryCodeProblem.Version)
if (code.length != formattedLength(blockCountFor(version))) return Checked.Failed(RecoveryCodeProblem.Length)
if (!validateFormat(code, ALPHABET)) return Checked.Failed(RecoveryCodeProblem.Characters)
if (version >= 3 && !checksumMatches(stripDashes(code))) return Checked.Failed(RecoveryCodeProblem.Checksum)
return Checked.Ok(version)
}
if (code.length != formattedLength(LEGACY_BLOCKS)) return Checked.Failed(RecoveryCodeProblem.Length)
if (!validateFormat(code, ALPHABET_LEGACY)) return Checked.Failed(RecoveryCodeProblem.Characters)
return Checked.Ok(1)
}
/**
* §5. User input in canonical form: upper case, separators dropped, the symbol count
* checked for the version the first two symbols name, a dash after every four. Checks
* neither the alphabet nor the checksum; [version] does, on the result.
*/
fun normalize(input: String): Checked<String> {
val symbols = stripSeparators(input)
var want = LEGACY_BLOCKS * BLOCK_SIZE
if (symbols.length >= 2 && symbols[0] == 'L') {
val version = versionFromChar(symbols[1]) ?: return Checked.Failed(RecoveryCodeProblem.Version)
want = blockCountFor(version) * BLOCK_SIZE
}
if (symbols.length != want) return Checked.Failed(RecoveryCodeProblem.Length)
return Checked.Ok(format(symbols))
}
/**
* §6. The one symbol of a not-quite-valid version 3 code that, changed, makes it valid --
* or null: the input is valid already, is not 36 symbols, has two or more symbols outside
* the alphabet, or is a symbol away from no valid code or from more than one.
*
* Exhaustive, as the spec states it: 36 positions by 29 replacements is nothing. The
* result is a suggestion. Two errors can sit one symbol from a *different* valid code.
*/
fun locateTypo(input: String): Typo? {
val symbols = stripSeparators(input).toCharArray()
if (symbols.size != V3_SYMBOLS) return null
val bad = symbols.indices.filter { ALPHABET.indexOf(symbols[it]) == -1 }
val candidates = when (bad.size) {
0 -> if (isValidV3(symbols)) return null else symbols.indices.toList()
1 -> bad
else -> return null
}
var found: Typo? = null
for (i in candidates) {
val original = symbols[i]
for (c in ALPHABET) {
if (c == original) continue
symbols[i] = c
if (isValidV3(symbols)) {
if (found != null) return null // ambiguous; distance 3 says it cannot happen
found = Typo(i, format(symbols.concatToString()))
}
}
symbols[i] = original
}
return found
}
/**
* §8. How many blocks a code that starts with [prefix] has: 8 for versions 1 and 2, 9 for
* version 3. Null when the prefix cannot tell -- empty, a lone `L` -- or names no version.
*/
fun blockCount(prefix: String): Int? {
val symbols = stripSeparators(prefix)
if (symbols.isEmpty()) return null
if (symbols[0] != 'L') return LEGACY_BLOCKS
if (symbols.length < 2) return null
return versionFromChar(symbols[1])?.let(::blockCountFor)
}
/** §3. The two weighted sums over symbols 0–31, which must all be in [ALPHABET]. */
fun checksum(symbols: CharArray): Pair<Int, Int> {
var s1 = 0
var s2 = 0
for (i in 0 until BODY_SYMBOLS) {
val v = ALPHABET.indexOf(symbols[i])
val w = i + 1
s1 = (s1 + w * v) % CHECKSUM_MODULUS
s2 = (s2 + w * w * v) % CHECKSUM_MODULUS
}
return s1 to s2
}
fun encodeChecksum(s1: Int, s2: Int): CharArray {
val n = ALPHABET.length
return charArrayOf(ALPHABET[s1 / n], ALPHABET[s1 % n], ALPHABET[s2 / n], ALPHABET[s2 % n])
}
private fun decodeChecksumPair(a: Char, b: Char): Int? {
val hi = ALPHABET.indexOf(a)
val lo = ALPHABET.indexOf(b)
if (hi == -1 || lo == -1) return null
val v = hi * ALPHABET.length + lo
return if (v >= CHECKSUM_MODULUS) null else v
}
private fun checksumMatches(symbols: CharArray): Boolean {
if (symbols.size != V3_SYMBOLS) return false
val (s1, s2) = checksum(symbols)
val d1 = decodeChecksumPair(symbols[32], symbols[33])
val d2 = decodeChecksumPair(symbols[34], symbols[35])
return d1 == s1 && d2 == s2
}
private fun isValidV3(symbols: CharArray): Boolean {
if (symbols[0] != 'L' || symbols[1] != versionChar(3)) return false
if (symbols.any { ALPHABET.indexOf(it) == -1 }) return false
return checksumMatches(symbols)
}
/** Every fifth character a dash, every other one in [alphabet]. The caller checks the length. */
private fun validateFormat(code: String, alphabet: String): Boolean =
code.indices.all { i ->
if (i % (BLOCK_SIZE + 1) == BLOCK_SIZE) code[i] == '-' else alphabet.indexOf(code[i]) != -1
}
private fun stripDashes(code: String): CharArray = code.filter { it != '-' }.toCharArray()
/** Upper case, without dashes or whitespace. */
fun stripSeparators(input: String): String =
input.uppercase().filter { it != '-' && !it.isWhitespace() }
/** A dash after every four symbols. */
fun format(symbols: String): String = symbols.chunked(BLOCK_SIZE).joinToString("-")
}
@@ -0,0 +1,131 @@
package mobi.giza.compose.identity.recoverycode
import fr.acinq.bitcoin.crypto.hmac
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertIs
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
/**
* The codec on every target. The spec's full vector table runs in
* `RecoveryCodeVectorsJvmTest`; these are a handful of its rows inline, so that Android and
* iOS run them too, and the properties the app leans on that no vector states.
*/
class RecoveryCodeTest {
private val base = "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ"
private fun valid(input: String): RecoveryCode =
assertIs<RecoveryCode.Parse.Valid>(RecoveryCode.parse(input)).code
// From v3_vectors.json: the base code and its key, and two random codes and theirs.
@Test
fun `the spec's keys`() {
assertEquals("74b36e622ce1e120de4e8fcd91be629498ffa196fc565da20a3676867693207b", valid(base).rootKey().toHex())
assertEquals(
"bcb2551cd4ea5bf335ed9ff74cddfbddb2aa848afce13497e62e9f682bb02137",
valid("LB33-MXW2-RPRD-ZREJ-QRHW-RBW9-982X-HLSC-Z2U8").rootKey().toHex(),
)
assertEquals(
"950788cea9b20692c244849317668baa82130b1ebe091786b7cca66d241f2233",
valid("LBDD-UYP8-Z59U-FV4M-VZXR-HRV9-LAZA-FCMD-UB8Q").rootKey().toHex(),
)
}
@Test
fun `a code typed any way is the same code`() {
val canonical = valid(base)
assertEquals(canonical, valid(base.lowercase()))
assertEquals(canonical, valid(base.replace('-', ' ')))
assertEquals(canonical, valid(base.replace("-", "")))
assertEquals(canonical, valid(" ${base.replace('-', '\t')}\n"))
assertEquals(base, canonical.canonical)
}
/**
* The key hashes the canonical string *with* its dashes. Two implementations that
* disagree about that derive two different people from one piece of paper.
*/
@Test
fun `the dashes are part of what is hashed`() {
val withoutDashes = fr.acinq.bitcoin.crypto.Digest.sha256().hmac(
"muun:rc".encodeToByteArray(),
base.replace("-", "").encodeToByteArray(),
64,
)
assertNotEquals(valid(base).rootKey().toByteArray().toList(), withoutDashes.toList())
}
@Test
fun `one wrong symbol is a suggestion, not a code`() {
val typo = assertIs<RecoveryCode.Parse.Typo>(RecoveryCode.parse("LBTP-WJRN-FXBT-U8KT-ZP5P-AQN9-XK3J-K3CV-2TB5"))
assertEquals(17, typo.position)
assertEquals(5, typo.block)
assertEquals(2, typo.character)
assertEquals('4', typo.suggestedSymbol)
assertEquals("LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5", typo.suggested.canonical)
}
@Test
fun `two wrong symbols are refused without a suggestion`() {
assertEquals(
RecoveryCode.Parse.Invalid(RecoveryCodeProblem.Checksum),
RecoveryCode.parse("LBTP-RJRN-FXBT-U8KT-Z45P-AQN9-XK33-K3CV-2TB5"),
)
}
@Test
fun `older versions are recognised and not accepted`() {
assertEquals(RecoveryCode.Parse.UnsupportedVersion(2), RecoveryCode.parse("LA2Q-48Z3-25JR-S5JB-5SUS-HXHJ-RCMM-8YUA"))
assertEquals(RecoveryCode.Parse.UnsupportedVersion(1), RecoveryCode.parse("R52Q-48Z3-25JR-S5JB-5SUS-HXHJ-RCMM-8YUA"))
}
@Test
fun `not a code`() {
assertEquals(RecoveryCode.Parse.Invalid(RecoveryCodeProblem.Length), RecoveryCode.parse(""))
assertEquals(RecoveryCode.Parse.Invalid(RecoveryCodeProblem.Length), RecoveryCode.parse("abandon ability able"))
assertEquals(RecoveryCode.Parse.Invalid(RecoveryCodeProblem.Version), RecoveryCode.parse("LC"))
}
@Test
fun `a generated code parses back to itself`() {
repeat(20) {
val code = RecoveryCode.generate()
assertEquals(code, valid(code.canonical))
assertEquals(9, code.blocks.size)
assertTrue(code.canonical.startsWith("LB"))
}
}
/**
* Bytes below 16 are thrown away, so that the 240 kept are eight of each of the thirty
* symbols. Fed 0..15 and then 16 over and over, every random symbol is the alphabet's
* `16 % 30`th, and none is its first.
*/
@Test
fun `generation rejects the biased bytes`() {
var next = 0
val source: (Int) -> ByteArray = { n -> ByteArray(n) { (if (next < 16) next++ else 16).toByte() } }
val code = RecoveryCode.generate(source)
val random = code.canonical.replace("-", "").substring(2, 32)
assertEquals(RecoveryCodeFormat.ALPHABET[16].toString().repeat(30), random)
}
@Test
fun `the code is never printed`() {
val code = valid(base)
assertFalse(code.toString().contains("LBZC"))
assertFalse(RecoveryCode.Parse.Valid(code).toString().contains("LBZC"))
}
@Test
fun `block count from a prefix`() {
assertEquals(9, RecoveryCode.blockCount("lb"))
assertEquals(8, RecoveryCode.blockCount("LA2Q"))
assertEquals(8, RecoveryCode.blockCount("R5"))
assertEquals(null, RecoveryCode.blockCount("L"))
assertEquals(null, RecoveryCode.blockCount("LC"))
}
}
@@ -0,0 +1,128 @@
package mobi.giza.compose.identity.recoverycode
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.boolean
import kotlinx.serialization.json.int
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import mobi.giza.compose.identity.recoverycode.RecoveryCodeFormat.Checked
import fr.acinq.bitcoin.crypto.hmac
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlin.test.fail
/**
* Every row of the spec's normative vectors (resources/recoverycode/v3_vectors.json, whose
* README names the commit it was copied from), against the port.
*
* The two version 1 key rows are the only ones skipped: a version 1 key is scrypt over a
* salt from Muun's Emergency Kit, and Giza never derives one. Their validity and version are
* still checked.
*/
class RecoveryCodeVectorsJvmTest {
private val vectors: JsonObject by lazy {
val text = javaClass.getResource("/recoverycode/v3_vectors.json")?.readText()
?: fail("v3_vectors.json is not on the test classpath")
Json.parseToJsonElement(text).jsonObject
}
private fun rows(section: String): List<JsonObject> =
vectors.getValue(section).jsonArray.map { it.jsonObject }
private fun JsonObject.string(key: String): String = getValue(key).jsonPrimitive.content
private fun problemName(problem: RecoveryCodeProblem): String = problem.name.lowercase()
@Test
fun `every validate row`() {
val rows = rows("validate")
assertEquals(47, rows.size, "the vector file changed size; check its README")
rows.forEach { row ->
val description = row.string("description")
val input = row.string("input")
when (val result = RecoveryCodeFormat.version(input)) {
is Checked.Ok -> {
assertTrue(row.getValue("valid").jsonPrimitive.boolean, "$description: accepted")
assertEquals(row.getValue("version").jsonPrimitive.int, result.value, description)
}
is Checked.Failed -> {
assertTrue(!row.getValue("valid").jsonPrimitive.boolean, "$description: refused as ${result.problem}")
assertEquals(row.string("error"), problemName(result.problem), description)
}
}
}
}
@Test
fun `every version 2 and 3 private key`() {
val keyed = rows("validate").filter { it.string("private_key").isNotEmpty() && it.getValue("version").jsonPrimitive.int >= 2 }
assertEquals(14, keyed.size)
keyed.forEach { row ->
val input = row.string("input")
// The same HMAC as RecoveryCode.rootKey, reached for a version 2 code too, which
// RecoveryCode itself will not hold.
val key = fr.acinq.bitcoin.crypto.Digest.sha256().hmac(
"muun:rc".encodeToByteArray(),
input.encodeToByteArray(),
64,
)
assertEquals(row.string("private_key"), key.toHexString(), row.string("description"))
if (row.getValue("version").jsonPrimitive.int == 3) {
val parsed = RecoveryCode.parse(input) as? RecoveryCode.Parse.Valid
?: fail("${row.string("description")}: did not parse")
assertEquals(row.string("private_key"), parsed.code.rootKey().toHex())
}
}
}
@Test
fun `every normalize row`() {
val rows = rows("normalize")
assertEquals(13, rows.size)
rows.forEach { row ->
val description = row.string("description")
when (val result = RecoveryCodeFormat.normalize(row.string("input"))) {
is Checked.Ok -> assertEquals(row.string("output"), result.value, description)
is Checked.Failed -> assertEquals(row.string("error"), problemName(result.problem), description)
}
}
}
@Test
fun `every locate row`() {
val rows = rows("locate")
assertEquals(17, rows.size)
rows.forEach { row ->
val description = row.string("description")
val typo = RecoveryCodeFormat.locateTypo(row.string("input"))
if (row.getValue("found").jsonPrimitive.boolean) {
typo ?: fail("$description: no typo found")
assertEquals(row.getValue("position").jsonPrimitive.int, typo.position, description)
assertEquals(row.string("corrected"), typo.corrected, description)
} else {
assertNull(typo, description)
}
}
}
/**
* The same rows through the public door: a found typo is a [RecoveryCode.Parse.Typo]
* carrying the corrected code, and never a [RecoveryCode.Parse.Valid].
*/
@Test
fun `parse reports each located typo as a suggestion`() {
rows("locate").filter { it.getValue("found").jsonPrimitive.boolean }.forEach { row ->
val parsed = RecoveryCode.parse(row.string("input"))
val typo = parsed as? RecoveryCode.Parse.Typo ?: fail("${row.string("description")}: parsed as $parsed")
assertEquals(row.string("corrected"), typo.suggested.canonical)
assertEquals(row.getValue("position").jsonPrimitive.int, typo.position)
}
}
private fun ByteArray.toHexString(): String = joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') }
}
@@ -0,0 +1,12 @@
# v3_vectors.json
The normative test vectors of Muun's recovery code format, copied byte for byte from
`recoverycode/testdata/v3_vectors.json` on the `recovery-code-v3-checksum` branch of
`kngako/libwallet`, at commit `7d58eb2e43e2d9ff97b437d8ecbaa248bf814869`.
sha256 `2bccb78ed09c37322f269d59b2a12bb4859750f2828517eaaaa0efbc5f096b41`
Generated there by an independent Python reference implementation
(`recoverycode/testdata/gen_vectors.py`). Do not edit this file; replace it from a later
commit of the spec and update the hash and commit above. `RecoveryCodeVectorsJvmTest` runs
every row. See docs/recovery-code-v3.md, Phase 1.
@@ -0,0 +1,583 @@
{
"validate": [
{
"description": "v1 legacy code",
"input": "R52Q-48Z3-25JR-S5JB-5SUS-HXHJ-RCMM-8YUA",
"valid": true,
"error": "",
"version": 1,
"private_key": "ade3fe99c608fd04484bce1ccf2889a5096f68f4b6b459e7f9ee9f0ada0a2782",
"salt": "FFFFFFFF"
},
{
"description": "v1 legacy code with real salt",
"input": "3V4N-R9EC-V3TQ-NRB3-Q7NY-9HXP-CSDC-B5BC",
"valid": true,
"error": "",
"version": 1,
"private_key": "fa3a914495092bf4ceec62570aa1aacba3574c1f860c1272e4a31761881f5737",
"salt": "63f701fda4fc0b0c"
},
{
"description": "v2 code",
"input": "LA2Q-48Z3-25JR-S5JB-5SUS-HXHJ-RCMM-8YUA",
"valid": true,
"error": "",
"version": 2,
"private_key": "0e1446153d4cafb073110739608fdd76b8712221476ec198cf35e1d74d274e83"
},
{
"description": "v2 random code 1",
"input": "LA79-AMRU-JBTP-FYS3-DLWR-53B7-W87X-3L7X",
"valid": true,
"error": "",
"version": 2,
"private_key": "e053f32c7de5e614a54ee84cbee56890a155d5bbf786ca7dc2a89c97ab5655ea"
},
{
"description": "v2 random code 2",
"input": "LA72-BAWL-92XV-FWCJ-KQYM-3JNN-ZK3V-4MA4",
"valid": true,
"error": "",
"version": 2,
"private_key": "0a1b66809fc26b063536d69b930c0d6bb12834e6b31535c646672f36f11c20aa"
},
{
"description": "v3 random code 1",
"input": "LB33-MXW2-RPRD-ZREJ-QRHW-RBW9-982X-HLSC-Z2U8",
"valid": true,
"error": "",
"version": 3,
"private_key": "bcb2551cd4ea5bf335ed9ff74cddfbddb2aa848afce13497e62e9f682bb02137"
},
{
"description": "v3 random code 2",
"input": "LBDD-UYP8-Z59U-FV4M-VZXR-HRV9-LAZA-FCMD-UB8Q",
"valid": true,
"error": "",
"version": 3,
"private_key": "950788cea9b20692c244849317668baa82130b1ebe091786b7cca66d241f2233"
},
{
"description": "v3 random code 3",
"input": "LB3K-7TNK-4QQ3-CJZJ-N9QR-S3ZW-BB53-UDVX-DQS9",
"valid": true,
"error": "",
"version": 3,
"private_key": "b19ccbeb76dfae8cc208815ccdffbfad5b588ff2c1141958608c29a8717585e1"
},
{
"description": "v3 random code 4",
"input": "LBF3-ZJSK-VMDA-QY9W-JJHB-MVBW-BAAV-SSUD-D9ME",
"valid": true,
"error": "",
"version": 3,
"private_key": "985945c8f73f580c7801a5adddc5a528a782d3fa6d7463a9ccaa453f8d71c260"
},
{
"description": "v3 random code 5",
"input": "LBB4-58X3-9BXL-HKWN-VNM5-4D4B-ZHRP-YF7H-UAXQ",
"valid": true,
"error": "",
"version": 3,
"private_key": "e777b94cf8ef2be72a63e58dfe108a57e0783b4cd0045e9076c40d01d4bc2849"
},
{
"description": "v3 random code 6",
"input": "LBT5-WM2Q-U57Y-PXQ7-SSQ2-79RM-VXA4-58YW-PQB2",
"valid": true,
"error": "",
"version": 3,
"private_key": "3757d91ac74e7652aa2094769366e867e2cca224a79bb48f5cd58bfe3e77148b"
},
{
"description": "v3 code with S1 = 0",
"input": "LBED-BA7W-NYNZ-3N8Y-8ZRJ-F2YJ-XFA2-SLUX-AA3N",
"valid": true,
"error": "",
"version": 3,
"private_key": "d4fdb8ebc3407648524097e042bf81f2d4ecb6ece974efa173a9be1e5aeae045"
},
{
"description": "v3 code with S1 = 886",
"input": "LB7F-PJJY-EA5T-PJ8N-DAT4-J7EK-9CU3-FUJX-9T5H",
"valid": true,
"error": "",
"version": 3,
"private_key": "e8d6362e2ac0af9e17b0a973bde3250745c6c9d556eefb8eb28d9c508b43aeeb"
},
{
"description": "v3 code with S2 = 0",
"input": "LBWL-TRCN-Z88J-TF7D-YF2X-8MWL-FY79-T5XM-KCAA",
"valid": true,
"error": "",
"version": 3,
"private_key": "88fa1ba200f08388584293341c659fd7a98ac1c4de5e35f6ade9c25353d5789e"
},
{
"description": "v3 code with S2 = 886",
"input": "LBNY-MXX5-LVLC-4JXU-ZS5M-PXAW-4NDE-VNZ3-7N9T",
"valid": true,
"error": "",
"version": 3,
"private_key": "406265b438d7866fc219485e78321ab9414f258567fce74a8fc5cc21e386c6ee"
},
{
"description": "v3 base code for error cases",
"input": "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"valid": true,
"error": "",
"version": 3,
"private_key": "74b36e622ce1e120de4e8fcd91be629498ffa196fc565da20a3676867693207b"
},
{
"description": "v3 single substitution in block 1",
"input": "LBRC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"valid": false,
"error": "checksum",
"version": 0,
"private_key": ""
},
{
"description": "v3 single substitution in block 2",
"input": "LBZC-MSTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"valid": false,
"error": "checksum",
"version": 0,
"private_key": ""
},
{
"description": "v3 single substitution in block 3",
"input": "LBZC-MYTK-39P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"valid": false,
"error": "checksum",
"version": 0,
"private_key": ""
},
{
"description": "v3 single substitution in block 4",
"input": "LBZC-MYTK-E9P3-3C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"valid": false,
"error": "checksum",
"version": 0,
"private_key": ""
},
{
"description": "v3 single substitution in block 5",
"input": "LBZC-MYTK-E9P3-7C7B-AHJK-KX79-22CY-WAY7-K7QZ",
"valid": false,
"error": "checksum",
"version": 0,
"private_key": ""
},
{
"description": "v3 single substitution in block 6",
"input": "LBZC-MYTK-E9P3-7C7B-AHJN-KX59-22CY-WAY7-K7QZ",
"valid": false,
"error": "checksum",
"version": 0,
"private_key": ""
},
{
"description": "v3 single substitution in block 7",
"input": "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22C5-WAY7-K7QZ",
"valid": false,
"error": "checksum",
"version": 0,
"private_key": ""
},
{
"description": "v3 single substitution in block 8",
"input": "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-W8Y7-K7QZ",
"valid": false,
"error": "checksum",
"version": 0,
"private_key": ""
},
{
"description": "v3 single substitution in block 9",
"input": "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-Z7QZ",
"valid": false,
"error": "checksum",
"version": 0,
"private_key": ""
},
{
"description": "v3 adjacent transposition",
"input": "LBCZ-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"valid": false,
"error": "checksum",
"version": 0,
"private_key": ""
},
{
"description": "v3 distant transposition",
"input": "LB7C-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAYZ-K7QZ",
"valid": false,
"error": "checksum",
"version": 0,
"private_key": ""
},
{
"description": "v3 transposition between body and checksum block",
"input": "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAYK-77QZ",
"valid": false,
"error": "checksum",
"version": 0,
"private_key": ""
},
{
"description": "v3 two substitutions",
"input": "LBZC-MRTK-E9P3-7C7B-AHJN-RX79-22CY-WAY7-K7QZ",
"valid": false,
"error": "checksum",
"version": 0,
"private_key": ""
},
{
"description": "v3 checksum value out of range (>= 887)",
"input": "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-99QZ",
"valid": false,
"error": "checksum",
"version": 0,
"private_key": ""
},
{
"description": "v3 checksum second value out of range (>= 887)",
"input": "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K799",
"valid": false,
"error": "checksum",
"version": 0,
"private_key": ""
},
{
"description": "v3 code missing block 9",
"input": "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7",
"valid": false,
"error": "length",
"version": 0,
"private_key": ""
},
{
"description": "v2 code with an extra block",
"input": "LATE-A7WQ-YRCC-LTS5-RW9R-W5WB-JUPZ-BU2E-ABCD",
"valid": false,
"error": "length",
"version": 0,
"private_key": ""
},
{
"description": "v2 code with version flipped to B",
"input": "LBTE-A7WQ-YRCC-LTS5-RW9R-W5WB-JUPZ-BU2E",
"valid": false,
"error": "length",
"version": 0,
"private_key": ""
},
{
"description": "v3 code with version flipped to A",
"input": "LAZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"valid": false,
"error": "length",
"version": 0,
"private_key": ""
},
{
"description": "unknown version C",
"input": "LCTE-A7WQ-YRCC-LTS5-RW9R-W5WB-JUPZ-BU2E",
"valid": false,
"error": "version",
"version": 0,
"private_key": ""
},
{
"description": "unknown version C with 9 blocks",
"input": "LCZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"valid": false,
"error": "version",
"version": 0,
"private_key": ""
},
{
"description": "version char not in alphabet",
"input": "L1TE-A7WQ-YRCC-LTS5-RW9R-W5WB-JUPZ-BU2E",
"valid": false,
"error": "version",
"version": 0,
"private_key": ""
},
{
"description": "v3 with misplaced dash",
"input": "LBZ-CMYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"valid": false,
"error": "characters",
"version": 0,
"private_key": ""
},
{
"description": "v3 with invalid character O",
"input": "LBZC-MOTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"valid": false,
"error": "characters",
"version": 0,
"private_key": ""
},
{
"description": "v3 lowercase is not canonical",
"input": "lbzc-mytk-e9p3-7c7b-ahjn-kx79-22cy-way7-k7qz",
"valid": false,
"error": "length",
"version": 0,
"private_key": ""
},
{
"description": "v3 without dashes",
"input": "LBZCMYTKE9P37C7BAHJNKX7922CYWAY7K7QZ",
"valid": false,
"error": "length",
"version": 0,
"private_key": ""
},
{
"description": "v2 invalid character",
"input": "LA2Q-48Z3-25JR-S51B-5SUS-HXHJ-RCMM-8YUA",
"valid": false,
"error": "characters",
"version": 0,
"private_key": ""
},
{
"description": "v2 invalid length",
"input": "LA2Q-48Z3-25JR-SB5S-USHX-HJRC-MM8YUA",
"valid": false,
"error": "length",
"version": 0,
"private_key": ""
},
{
"description": "v1 invalid character L",
"input": "R52Q-48Z3-25JR-S5JB-5SUS-HXHJ-RCMM-8YUL",
"valid": false,
"error": "characters",
"version": 0,
"private_key": ""
},
{
"description": "empty string",
"input": "",
"valid": false,
"error": "length",
"version": 0,
"private_key": ""
},
{
"description": "single L",
"input": "L",
"valid": false,
"error": "length",
"version": 0,
"private_key": ""
}
],
"normalize": [
{
"description": "canonical v3 unchanged",
"input": "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"output": "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"error": ""
},
{
"description": "v3 lowercase",
"input": "lbzc-mytk-e9p3-7c7b-ahjn-kx79-22cy-way7-k7qz",
"output": "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"error": ""
},
{
"description": "v3 spaces instead of dashes",
"input": "LBZC MYTK E9P3 7C7B AHJN KX79 22CY WAY7 K7QZ",
"output": "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"error": ""
},
{
"description": "v3 without separators",
"input": "LBZCMYTKE9P37C7BAHJNKX7922CYWAY7K7QZ",
"output": "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"error": ""
},
{
"description": "v3 surrounding and mixed whitespace",
"input": " LBZC\tMYTK\tE9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ \n",
"output": "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"error": ""
},
{
"description": "v2 lowercase without separators",
"input": "latea7wqyrcclts5rw9rw5wbjupzbu2e",
"output": "LATE-A7WQ-YRCC-LTS5-RW9R-W5WB-JUPZ-BU2E",
"error": ""
},
{
"description": "v1 lowercase",
"input": "r52q-48z3-25jr-s5jb-5sus-hxhj-rcmm-8yua",
"output": "R52Q-48Z3-25JR-S5JB-5SUS-HXHJ-RCMM-8YUA",
"error": ""
},
{
"description": "v3 keeps characters outside the alphabet",
"input": "lbzc-motk-e9p3-7c7b-ahjn-kx79-22cy-way7-k7qz",
"output": "LBZC-MOTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ",
"error": ""
},
{
"description": "v3 one symbol short",
"input": "LBZCMYTKE9P37C7BAHJNKX7922CYWAY7K7Q",
"output": "",
"error": "length"
},
{
"description": "v2 one symbol too many",
"input": "LATEA7WQYRCCLTS5RW9RW5WBJUPZBU2EA",
"output": "",
"error": "length"
},
{
"description": "unknown version",
"input": "LCZCMYTKE9P37C7BAHJNKX7922CYWAY7K7QZ",
"output": "",
"error": "version"
},
{
"description": "empty string",
"input": "",
"output": "",
"error": "length"
},
{
"description": "only separators",
"input": " - - ",
"output": "",
"error": "length"
}
],
"locate": [
{
"description": "valid code has no typo",
"input": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5",
"found": false,
"position": -1,
"corrected": ""
},
{
"description": "single substitution at symbol 2",
"input": "LBVP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5",
"found": true,
"position": 2,
"corrected": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5"
},
{
"description": "single substitution at symbol 9",
"input": "LBTP-WJRN-FFBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5",
"found": true,
"position": 9,
"corrected": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5"
},
{
"description": "single substitution at symbol 17",
"input": "LBTP-WJRN-FXBT-U8KT-ZP5P-AQN9-XK3J-K3CV-2TB5",
"found": true,
"position": 17,
"corrected": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5"
},
{
"description": "single substitution at symbol 31",
"input": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CL-2TB5",
"found": true,
"position": 31,
"corrected": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5"
},
{
"description": "single substitution at symbol 32",
"input": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-YTB5",
"found": true,
"position": 32,
"corrected": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5"
},
{
"description": "single substitution at symbol 33",
"input": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-25B5",
"found": true,
"position": 33,
"corrected": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5"
},
{
"description": "single substitution at symbol 34",
"input": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TU5",
"found": true,
"position": 34,
"corrected": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5"
},
{
"description": "single substitution at symbol 35",
"input": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TBQ",
"found": true,
"position": 35,
"corrected": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5"
},
{
"description": "version char typo (B -> C)",
"input": "LCTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5",
"found": true,
"position": 1,
"corrected": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5"
},
{
"description": "prefix typo (L -> M)",
"input": "MBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5",
"found": true,
"position": 0,
"corrected": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5"
},
{
"description": "character outside alphabet (O)",
"input": "LBTP-WJRN-FXBT-O8KT-Z45P-AQN9-XK3J-K3CV-2TB5",
"found": true,
"position": 12,
"corrected": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5"
},
{
"description": "lowercase input without dashes",
"input": "lbtpwjrnfxbtu8ktz45p3qn9xk3jk3cv2tb5",
"found": true,
"position": 20,
"corrected": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5"
},
{
"description": "two characters outside alphabet",
"input": "LBTO-WJRN-FXBT-U8KT-Z45P-IQN9-XK3J-K3CV-2TB5",
"found": false,
"position": -1,
"corrected": ""
},
{
"description": "wrong length",
"input": "LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV",
"found": false,
"position": -1,
"corrected": ""
},
{
"description": "adjacent transposition",
"input": "LBPT-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5",
"found": false,
"position": -1,
"corrected": ""
},
{
"description": "two substitutions",
"input": "LBTP-RJRN-FXBT-U8KT-Z45P-AQN9-XK33-K3CV-2TB5",
"found": false,
"position": -1,
"corrected": ""
}
]
}