diff --git a/CLAUDE.md b/CLAUDE.md index 3b5769a5..a3947926 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -217,6 +217,9 @@ Bennu still has them, and a Bennu member can put one to a group Giza is in, so: - The wallet's kind numbers (`RetiredKinds`) stay Bennu's. Nothing new goes on them. - A recovery phrase is a key backup. `PhraseKeys` derives the npub and the profile id, and both are pinned in `ForkCompatibilityTest`. +- A recovery code's key is BIP39 entropy: `RecoveryCodeKeys.words` turns it into 24 words, + which derive through `PhraseKeys`, pinned in `RecoveryCodeKeysTest` + ([docs/recovery-code-v3.md](docs/recovery-code-v3.md)). `./gradlew check` runs `docs/scripts/wallet-audit.sh --check`, which fails on a retired kind in the app's code, a lightning-kmp import, a file named for a wallet's pieces, or sats in a string. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/recoverycode/RecoveryCodeKeys.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/recoverycode/RecoveryCodeKeys.kt new file mode 100644 index 00000000..dd68ab94 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/recoverycode/RecoveryCodeKeys.kt @@ -0,0 +1,24 @@ +package mobi.giza.compose.identity.recoverycode + +import fr.acinq.bitcoin.MnemonicCode +import fr.acinq.phoenix.utils.MnemonicLanguage + +/** + * What a recovery code derives: twenty-four words, and from them everything a phrase does. + * + * The code's root key is read as BIP39 entropy -- thirty-two bytes and their eight checksum + * bits are exactly twenty-four words -- and the words go to `PhraseKeys` as they stand: the + * empty passphrase, BIP32, NIP-06's path for the nostr key and `m/50'/0'` for the profile id. + * So a code is a 24-word phrase in another notation, its words typed into any NIP-06 client + * land on the npub Giza shows, and every path a phrase will ever have, a code has too. + * + * The words do not give the code back: the HMAC under [RecoveryCode.rootKey] runs one way. + * See docs/recovery-code-v3.md, "The one decision". `RecoveryCodeKeysTest` pins three codes + * to their words, npub and id, cross-checked against docs/scripts/recovery-code-keys.py. + */ +object RecoveryCodeKeys { + + /** The 24 words [code] is. */ + fun words(code: RecoveryCode): List = + MnemonicCode.toMnemonics(code.rootKey().toByteArray(), MnemonicLanguage.English.wordlist()) +} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/identity/recoverycode/RecoveryCodeKeysTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/identity/recoverycode/RecoveryCodeKeysTest.kt new file mode 100644 index 00000000..1538fe94 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/identity/recoverycode/RecoveryCodeKeysTest.kt @@ -0,0 +1,86 @@ +package mobi.giza.compose.identity.recoverycode + +import fr.acinq.bitcoin.MnemonicCode +import fr.acinq.phoenix.utils.MnemonicLanguage +import mobi.giza.compose.identity.PhraseKeys +import mobi.giza.compose.identity.StoredIdentity +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs + +/** + * Who a recovery code is. These values are permanent: a code's words, npub and profile id + * are the person, and a change here is a different person behind the same piece of paper. + * + * The codes are the spec's (v3_vectors.json: the base code for its error cases, and two of + * its random codes); the root keys are the spec's too. Everything after the root key is + * Giza's -- no other app turns a recovery code into a phrase -- so it was computed by an + * independent derivation, docs/scripts/recovery-code-keys.py, which shares no code with + * the app and reproduces NIP-06's own vector and `ForkCompatibilityTest`'s profile id. + */ +class RecoveryCodeKeysTest { + + private data class Pinned( + val code: String, + val rootKey: String, + val words: String, + val nostrSecret: String, + val npub: String, + val profileId: String, + ) + + private val pinned = listOf( + Pinned( + code = "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ", + rootKey = "74b36e622ce1e120de4e8fcd91be629498ffa196fc565da20a3676867693207b", + words = "input opinion obtain flush bulk motor junior spin snow mistake obvious circle morning speak fossil member frozen aware mirror unfair guess end limit honey", + nostrSecret = "9f1941e369a8d8a6a09297ed8e301a86bdfb41a7f7938ba0eb4b91e3e61930ed", + npub = "ece2bc031552ccd5062f6fb933f7e00187e6391df2b81fe0a83e697a7589b89f", + profileId = "afa04673cf64f3f40933f5ab74479cb58e3340b6", + ), + Pinned( + code = "LB33-MXW2-RPRD-ZREJ-QRHW-RBW9-982X-HLSC-Z2U8", + rootKey = "bcb2551cd4ea5bf335ed9ff74cddfbddb2aa848afce13497e62e9f682bb02137", + words = "royal naive elbow prefer pizza wet stumble recycle warrior group leave rocket click drastic cloud order cruel sand merry disagree live submit luggage twin", + nostrSecret = "0177ca48584dd3fe733ee5b484e16e3c0979291011e5d94caaf1452735847f02", + npub = "2873b2daf9474090d4cec5901730407b7460af4d05fb81bd9e4c37a9c7af7fbd", + profileId = "a67aacd81a80dcdb007cc3ce40df5ef9a7e467af", + ), + Pinned( + code = "LBDD-UYP8-Z59U-FV4M-VZXR-HRV9-LAZA-FCMD-UB8Q", + rootKey = "950788cea9b20692c244849317668baa82130b1ebe091786b7cca66d241f2233", + words = "never detail crisp fat call enact animal mountain narrow robot pepper fence cancel machine kit scorpion bleak cup veteran error spoil auto match gossip", + nostrSecret = "152e3a544de5076c5282b2305d6d2a86b57b9064e48088cbe0878214c75b3c7c", + npub = "2070ddc08f7eb62864da9adaf1f1aeba1bb2f6bda49c224dfde2c6d82ccd81f7", + profileId = "fccf643a975aa477a936690d56123e668dd2b1bf", + ), + ) + + private fun code(text: String): RecoveryCode = assertIs(RecoveryCode.parse(text)).code + + @Test + fun `a code's words, npub and profile id`() { + pinned.forEach { p -> + val code = code(p.code) + assertEquals(p.rootKey, code.rootKey().toHex(), p.code) + val words = RecoveryCodeKeys.words(code) + assertEquals(p.words, words.joinToString(" "), p.code) + assertEquals(p.nostrSecret, PhraseKeys.nostrPrivateKey(words).value.toHex(), p.code) + assertEquals(p.npub, StoredIdentity.nostrPublicKeyOf(words), p.code) + assertEquals(p.profileId, PhraseKeys.profileId(words).nodeIdHash, p.code) + } + } + + /** + * The words are a phrase, which is the whole point of the derivation: typed into any + * NIP-06 client, or into Giza's sign-in as words, they are the same person. + */ + @Test + fun `a code's words are a valid 24-word phrase`() { + repeat(10) { + val words = RecoveryCodeKeys.words(RecoveryCode.generate()) + assertEquals(24, words.size) + MnemonicCode.validate(mnemonics = words, wordlist = MnemonicLanguage.English.wordlist()) + } + } +} diff --git a/docs/scripts/recovery-code-keys.py b/docs/scripts/recovery-code-keys.py new file mode 100755 index 00000000..20a0889d --- /dev/null +++ b/docs/scripts/recovery-code-keys.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +""" +What a v3 recovery code derives in Giza, computed without Giza. + +An independent derivation for RecoveryCodeKeysTest's pinned vectors +(docs/recovery-code-v3.md, Phase 2): standard library only, sharing no code with the app, +so that a vector the app and this script agree on was not merely agreed with itself. + + code ─HMAC-SHA256("muun:rc")→ 32 bytes ─BIP39 entropy→ 24 words + ─PBKDF2-SHA512(2048, "mnemonic")→ seed ─BIP32→ m/44'/1237'/0'/0/0 the nostr key + → m/50'/0' hash160 = profile id + +Usage: + python3 -I docs/scripts/recovery-code-keys.py english.txt CODE [CODE ...] + +english.txt is BIP39's English wordlist (bitcoin/bips, bip-0039/english.txt, sha256 +2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda). The code must be +canonical: upper case, nine blocks, dashes in place -- the dashes are part of what is hashed. +""" +import hashlib +import hmac +import sys + +WORDLIST_SHA256 = "2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda" + +# secp256k1 +P = 2**256 - 2**32 - 977 +N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 +G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, + 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8) + + +def point_add(a, b): + if a is None: + return b + if b is None: + return a + if a[0] == b[0] and (a[1] + b[1]) % P == 0: + return None + if a == b: + lam = 3 * a[0] * a[0] * pow(2 * a[1], -1, P) % P + else: + lam = (b[1] - a[1]) * pow(b[0] - a[0], -1, P) % P + x = (lam * lam - a[0] - b[0]) % P + return x, (lam * (a[0] - x) - a[1]) % P + + +def point_mul(k): + result, addend = None, G + while k: + if k & 1: + result = point_add(result, addend) + addend = point_add(addend, addend) + k >>= 1 + return result + + +def compressed(k): + x, y = point_mul(k) + return bytes([2 + (y & 1)]) + x.to_bytes(32, "big") + + +def root_key(code): + return hmac.new(b"muun:rc", code.encode(), hashlib.sha256).digest() + + +def to_words(entropy, wordlist): + checksum_bits = len(entropy) * 8 // 32 + bits = int.from_bytes(entropy, "big") << checksum_bits + bits |= hashlib.sha256(entropy).digest()[0] >> (8 - checksum_bits) + count = (len(entropy) * 8 + checksum_bits) // 11 + return [wordlist[(bits >> (11 * (count - 1 - i))) & 0x7FF] for i in range(count)] + + +def to_seed(words): + return hashlib.pbkdf2_hmac("sha512", " ".join(words).encode(), b"mnemonic", 2048) + + +def derive(seed, path): + digest = hmac.new(b"Bitcoin seed", seed, hashlib.sha512).digest() + k, chain = int.from_bytes(digest[:32], "big"), digest[32:] + for index in path: + if index >= 2**31: + data = b"\x00" + k.to_bytes(32, "big") + index.to_bytes(4, "big") + else: + data = compressed(k) + index.to_bytes(4, "big") + digest = hmac.new(chain, data, hashlib.sha512).digest() + k, chain = (int.from_bytes(digest[:32], "big") + k) % N, digest[32:] + return k + + +H = 2**31 + + +def main(): + if len(sys.argv) < 3: + sys.exit(__doc__) + with open(sys.argv[1], "rb") as f: + raw = f.read() + if hashlib.sha256(raw).hexdigest() != WORDLIST_SHA256: + sys.exit("that is not BIP39's English wordlist") + wordlist = raw.decode().split() + for code in sys.argv[2:]: + entropy = root_key(code) + words = to_words(entropy, wordlist) + seed = to_seed(words) + nostr = derive(seed, [44 + H, 1237 + H, 0 + H, 0, 0]) + node = derive(seed, [50 + H, 0 + H]) + profile_id = hashlib.new("ripemd160", hashlib.sha256(compressed(node)).digest()).hexdigest() + print(code) + print(" root key ", entropy.hex()) + print(" words ", " ".join(words)) + print(" nostr key ", nostr.to_bytes(32, "big").hex()) + print(" nostr pub ", point_mul(nostr)[0].to_bytes(32, "big").hex()) + print(" profile id ", profile_id) + + +if __name__ == "__main__": + main()