diff --git a/docs/security/model.md b/docs/security/model.md index 6b005829..e809c6c2 100644 --- a/docs/security/model.md +++ b/docs/security/model.md @@ -228,7 +228,7 @@ signing setup belong to Bitcoin Core's maintained v32 workflow. | Control | Required behavior | |---|---| | Preflight | Before entropy or recovery input, explicit chain arguments probe the five standard local networks for Bitcoin Core 32 or newer. One response is selected automatically; multiple responses require operator selection. | -| Recovery identity | Restore authenticates a recovered seed before any wallet is listed. Core derives the recovered fingerprint statelessly, and a mismatch raises `FingerprintMismatch` before any wallet RPC. The restore prompt does not show the recovered value, so the operator compares by typing the fingerprint from the wallet record. Without a record, the operator is shown the recovered fingerprint, whether the backup identifier was derived from the seed (the codex32 fingerprint rule, Bails' RIPEMD-160 rule, or its mid-2023 alpha's SHA-256 rule), and a warning, and then chooses. Fresh creation (`ms32 create` or GUI setup) does not authenticate against a pre-existing wallet: it shows the newly created seed's fingerprint and requires the operator to acknowledge recording it. These checks catch mistakes such as wrong or mixed cards; anyone able to replace a threshold of cards could already read them. | +| Recovery identity | Restore authenticates a recovered seed before any wallet is listed. Core derives the recovered fingerprint statelessly, and a mismatch raises `FingerprintMismatch` before any wallet RPC. The restore prompt does not show the recovered value, so the operator compares by typing the fingerprint from the wallet record. It is typed before the cards, so card correction can prefer a candidate whose recovered seed makes that fingerprint (a wrong seed matches 1 time in 2^32); the operator still compares every suggestion with the whole card, and the identity check runs again after recovery. Without a record, the operator is shown the recovered fingerprint, whether the backup identifier was derived from the seed (the codex32 fingerprint rule, Bails' RIPEMD-160 rule, or its mid-2023 alpha's SHA-256 rule), and a warning, and then chooses. Fresh creation (`ms32 create` or GUI setup) does not authenticate against a pre-existing wallet: it shows the newly created seed's fingerprint and requires the operator to acknowledge recording it. These checks catch mistakes such as wrong or mixed cards; anyone able to replace a threshold of cards could already read them. | | Process boundary | codex32 invokes the reviewed `bitcoin-cli` from `PATH` as a child without a shell, direct RPC socket, wallet database, or wallet-creation operation. Every call uses loopback and the selected chain. | | Destination | Only an empty descriptor wallet with private keys enabled, no external signer, transactions, descriptors, keypool entries, or active scan is eligible. One eligible wallet is offered directly; multiple wallets are selected by number. New wallets are detected by polling, and rejection returns to every eligible wallet. The escaped name is confirmed exactly. | | Seed source | The original ceremony result or validated recovered master seed supplies root-xprv private descriptors for Core's reported chain. After import, Core v32's wallet HD-key RPCs derive the requested BIP44, BIP49, BIP84, and BIP86 account xpubs. | diff --git a/docs/user/gui.md b/docs/user/gui.md index 9971940a..10dc66cc 100644 --- a/docs/user/gui.md +++ b/docs/user/gui.md @@ -160,13 +160,16 @@ wallet**, which would make a different backup. If the wallet was part-filled before it failed, it is no longer empty, so it will not be offered again: create another one, or ask Bitcoin Core for a fresh blank wallet. -When you restore, the window first asks you to type the master fingerprint from -your wallet record. If it does not match, nothing is written to Bitcoin Core: -check what you typed, and if it still does not match, these cards are not that -wallet. If you have no record, **I have no wallet record** shows the master -fingerprint and whether the backup identifier was made from the recovered seed, -explains what that can and cannot prove, and restores only if you still choose -to. Check the balance and history before you send money to that wallet. +When you restore, the window asks you to type the master fingerprint from your +wallet record before any card. If a card needs a repair and more than one fits, +the one that makes that fingerprint is offered; compare it with the whole card +as always. After the cards, the fingerprint is checked again. If it does not +match, nothing is restored: check what you typed, and if it still does not +match, these cards are from another wallet or a card was misread. If you have +no record, **I have no wallet record** goes straight to the cards; afterwards +the window shows the master fingerprint and whether the backup identifier was +made from the recovered seed, explains what that can and cannot prove, and +restores only if you still choose to. Check the balance and history before you send money to that wallet. The same page asks for the approximate creation date from your wallet record. Bitcoin Core searches for the wallet's transactions from a day before that date, diff --git a/docs/user/guide.md b/docs/user/guide.md index a9da4992..7d660b4a 100644 --- a/docs/user/guide.md +++ b/docs/user/guide.md @@ -236,10 +236,12 @@ its public wallet data with the separate wallet record. ms32 wallet --timestamp 0 ``` -5. Type the master fingerprint from the wallet record. A mismatch stops before - Bitcoin Core is changed. Press Enter with nothing typed only if there is no - record; codex32 then shows the recovered fingerprint and what the backup - identifier says, and asks before restoring. +5. Type the master fingerprint from the wallet record, then enter the cards. + If more than one correction fits a damaged card, the one that makes that + fingerprint is offered; still compare it with the whole card. A mismatch + after the cards restores nothing. Press Enter with nothing typed only if + there is no record; after the cards, codex32 shows the recovered fingerprint + and what the backup identifier says, and asks before restoring. 6. Select and confirm that wallet. If it is locked, follow the displayed Bitcoin-Qt Console instructions; codex32 waits and continues automatically. It imports the private descriptors, verifies the public set, and relocks an diff --git a/src/codex32/_bitcoin_core.py b/src/codex32/_bitcoin_core.py index b1eae17c..180e5ff3 100644 --- a/src/codex32/_bitcoin_core.py +++ b/src/codex32/_bitcoin_core.py @@ -234,8 +234,8 @@ def verify_identity(self, secret: MasterSeed, expected_fingerprint: bytes | None return if self.fingerprint(secret) != expected_fingerprint: raise FingerprintMismatch( - "The recovered master fingerprint does not match the one from the wallet record. " - "Bitcoin Core was not changed." + "These cards do not make the master fingerprint from the wallet record. " + "No wallet was created or restored." ) def check_history(self, timestamp: int | Literal["now"]) -> None: diff --git a/src/codex32/_cli_input.py b/src/codex32/_cli_input.py index c6e65dec..5bcd1449 100644 --- a/src/codex32/_cli_input.py +++ b/src/codex32/_cli_input.py @@ -19,7 +19,7 @@ parse_codex32, recover_secret, ) -from codex32.correction import CorrectionCandidate, CorrectionContext, _best +from codex32.correction import CorrectionCandidate, CorrectionContext, _best, _record_match from codex32.errors import ( CodexError, DuplicateShareIndex, @@ -460,6 +460,7 @@ def _correction_candidates( deadline: float | None = None, capture_layers: list[tuple[int, int]] | None = None, fingerprint_match: Callable[[CorrectionCandidate], bool | None] | None = None, + recorded: Callable[[CorrectionCandidate], bool | None] | None = None, ) -> tuple[tuple[CorrectionCandidate, ...], bool, float | None, bool]: count = len(value.replace(" ", "")) targets, primary, reduced, _timed = _correction_plan(profile, byte_length, count, target) @@ -480,7 +481,12 @@ def _correction_candidates( if allowed is not None: candidates = tuple(candidate for candidate in candidates if allowed(candidate)) results = ( - _best(candidates, prefer_common=byte_length == "?", fingerprint_match=fingerprint_match) + _best( + candidates, + prefer_common=byte_length == "?", + fingerprint_match=fingerprint_match, + recorded=recorded, + ) if complete else candidates if len(candidates) == 1 and not candidates[0].search_complete @@ -516,8 +522,12 @@ def _suggestions( *, allowed: Callable[[CorrectionCandidate], bool] | None = None, fingerprint: Callable[[MasterSeed], bytes] | None = None, + record: bytes | None = None, ) -> tuple[CorrectionCandidate, ...]: fingerprint_match = _fingerprint_matcher(fingerprint) + recorded = ( + _record_match(lambda seed: fingerprint(seed) == record, accepted) if fingerprint and record else None + ) erased = value if interpretation := _case_interpretation(value, prefix, profiles, allowed): candidate, value, erased, prefix = interpretation @@ -551,6 +561,7 @@ def _suggestions( deadline=deadline, capture_layers=capture_layers, fingerprint_match=fingerprint_match, + recorded=recorded, )[0] if candidates or erased == value: return candidates @@ -565,6 +576,7 @@ def _suggestions( deadline=deadline, capture_layers=capture_layers, fingerprint_match=fingerprint_match, + recorded=recorded, )[0] @@ -696,6 +708,7 @@ def _interactive( profiles: tuple[Profile, ...] | None, initial_prefix: str, fingerprint: Callable[[MasterSeed], bytes] | None, + record: bytes | None = None, ) -> list[Artifact]: accepted: list[Artifact] = [] prefix = initial_prefix @@ -740,6 +753,7 @@ def allowed(candidate: CorrectionCandidate) -> bool: accepted, allowed=allowed, fingerprint=fingerprint, + record=record, ) ) confirmation = ( @@ -794,6 +808,7 @@ def read_artifacts( profiles: tuple[Profile, ...] | None = None, initial_prefix: str = "", fingerprint: Callable[[MasterSeed], bytes] | None = None, + record: bytes | None = None, ) -> list[Artifact]: if not sys.stdin.isatty(): return _redirected( @@ -810,6 +825,7 @@ def read_artifacts( profiles=profiles, initial_prefix=initial_prefix, fingerprint=fingerprint, + record=record, ) _stderr("") return result diff --git a/src/codex32/cli.py b/src/codex32/cli.py index 7214cc9b..ba59deef 100644 --- a/src/codex32/cli.py +++ b/src/codex32/cli.py @@ -103,9 +103,13 @@ def _secret(artifacts: list[Artifact]) -> Secret: raise _UsageError(str(error)) from error -def _master_seed(fingerprint: Callable[[MasterSeed], bytes] | None = None) -> MasterSeed: +def _master_seed( + fingerprint: Callable[[MasterSeed], bytes] | None = None, record: bytes | None = None +) -> MasterSeed: if isinstance( - value := _secret(_artifacts(profiles=(Profile.MS,), initial_prefix="MS1", fingerprint=fingerprint)), + value := _secret( + _artifacts(profiles=(Profile.MS,), initial_prefix="MS1", fingerprint=fingerprint, record=record) + ), MasterSeed, ): return value @@ -370,26 +374,29 @@ def _creation_start() -> int: _print(str(error), err=True) -def _recorded_fingerprint(core: BitcoinCore, secret: MasterSeed) -> bytes | None: - """Take the master fingerprint from a recovery record until the library accepts it.""" - prompt = "Type the master fingerprint from your wallet record (Enter if none)" +def _record() -> bytes | None: + """Take the master fingerprint from the wallet record, or None when there is no record.""" while True: - text = _text(prompt, optional=True) - if not text: - if _without_record(core, secret): - return None - continue + text = _text("Type the master fingerprint from your wallet record (Enter if none)", optional=True) try: - expected = parse_fingerprint(text) + return parse_fingerprint(text) if text else None except ValueError as error: _print(str(error), err=True) - continue - try: - core.verify_identity(secret, expected) - except FingerprintMismatch as error: - _print(str(error), err=True) - continue - return expected + + +def _recorded_fingerprint(core: BitcoinCore, secret: MasterSeed, expected: bytes | None) -> bytes | None: + """Check the record typed before the cards, and ask again until the library accepts it.""" + while True: + if expected is None: + if _without_record(core, secret): + return None + else: + try: + core.verify_identity(secret, expected) + return expected + except FingerprintMismatch as error: + _print(f"{error} Check what you typed against the record.", err=True) + expected = _record() def _initialize_wallet( @@ -401,13 +408,14 @@ def _initialize_wallet( fresh: bool = True, restore: bool = False, confirmed: bool = True, + record: bytes | None = None, ) -> int: assert isinstance(secret, MasterSeed) try: if confirmed: _print("Master-seed backup confirmed.\n", err=True) if restore: - expected = _recorded_fingerprint(core, secret) + expected = _recorded_fingerprint(core, secret, record) else: _show_fingerprint(core, secret, "Write it on the wallet record") expected = None @@ -650,7 +658,8 @@ def _bitcoin_core(account: int, timestamp: int | Literal["now"]) -> int: raise _UsageError("Bitcoin Core wallet initialization requires an interactive terminal.") _print("Warning: This imports private descriptors that can spend funds.", err=True, danger=True) core = _connected_core() - secret = _master_seed(core.fingerprint) + record = _record() # Asked first, so a known fingerprint can settle competing card corrections. + secret = _master_seed(core.fingerprint, record) return _initialize_wallet( core, secret, @@ -659,6 +668,7 @@ def _bitcoin_core(account: int, timestamp: int | Literal["now"]) -> int: fresh=False, restore=True, confirmed=False, + record=record, ) diff --git a/src/codex32/correction.py b/src/codex32/correction.py index 4a1a5616..b7b10e50 100644 --- a/src/codex32/correction.py +++ b/src/codex32/correction.py @@ -42,6 +42,7 @@ Share, _checksum_for_encoded_length, parse_codex32, + recover_secret, ) from codex32.checksums import _CODEX32, _CODEX32_LONG, _Checksum from codex32.errors import CodexError, InvalidCorrectionInput @@ -840,8 +841,14 @@ def _best( *, prefer_common: bool = False, fingerprint_match: Callable[[CorrectionCandidate], bool | None] | None = None, + recorded: Callable[[CorrectionCandidate], bool | None] | None = None, ) -> tuple[CorrectionCandidate, ...]: - """Apply CLI-only Hamming and CRC tie breakers plus an optional wallet hint.""" + """Apply CLI-only Hamming and CRC tie breakers plus optional wallet hints. + + A wallet-record match (wrong seeds match 1 in 2**32) outranks them among the lowest-volume repairs. + """ + if recorded is not None and (matching := [item for item in candidates if recorded(item) is True]): + candidates = matching tied = list(_primary(candidates)) if not tied: return () @@ -858,6 +865,23 @@ def _best( return tuple(sorted(tied, key=_candidate_order)) +def _record_match( + recorded: Callable[[MasterSeed], bool], accepted: Sequence[Share | Secret] = () +) -> Callable[[CorrectionCandidate], bool | None]: + """Ask whether a candidate is the recorded wallet, once it completes a master seed.""" + + def matches(candidate: CorrectionCandidate) -> bool | None: + artifact, shares = candidate.artifact, [*accepted, candidate.artifact] + try: + if isinstance(artifact, Share) and len(shares) == artifact.header.threshold: + artifact = recover_secret([share for share in shares if isinstance(share, Share)]) + return recorded(artifact) if isinstance(artifact, MasterSeed) else None + except CodexError: + return None + + return matches + + def _correct_complete( context: CorrectionContext, damaged_text: str, *, deadline: float | None = None ) -> tuple[tuple[CorrectionCandidate, ...], bool]: diff --git a/src/codex32_gui/pages.py b/src/codex32_gui/pages.py index 4dbccb95..380fc372 100644 --- a/src/codex32_gui/pages.py +++ b/src/codex32_gui/pages.py @@ -1072,13 +1072,13 @@ def follow(identity: tuple[str, str]) -> Adw.NavigationPage: def _fingerprint_page( view: Adw.NavigationView, core: BitcoinCore, - secret: MasterSeed, + secret: MasterSeed | None, timestamp: Timestamp, *, restoring: bool = False, problem: str = "", ) -> Adw.NavigationPage: - """Take the master fingerprint from the wallet record. The library refuses a mismatch.""" + """Take the master fingerprint from the wallet record: before the cards when restoring.""" entered = Adw.EntryRow(title="Master fingerprint from your wallet record") dated = Adw.EntryRow(title="Approximate creation date from the record, as YYYY-MM-DD") group = Adw.PreferencesGroup() @@ -1093,31 +1093,23 @@ def go() -> None: except ValueError as error: _say(status, str(error), "error") return - page = _working(view, "Wallet record", "Checking the wallet record…") - - def job() -> str: - try: - wallet_setup.verify(core, secret, expected, start) - except wallet_setup.BitcoinCoreError as error: - return str(error) - return "" - - def follow(mismatch: str) -> Adw.NavigationPage | None: - if mismatch: - return _fingerprint_page(view, core, secret, timestamp, restoring=restoring, problem=mismatch) - _wallets(view, core, secret, start, expected, restoring=restoring) - return None + if secret is None: + view.push(_restore_cards(view, core, expected, start)) + else: + _check_record(view, core, secret, expected, start, restoring=restoring) - work.run(view, page, job, _then(view, page, follow, CARDS_SAFE)) + def without() -> None: + if secret is None: + view.push(_restore_cards(view, core, None, 0)) + else: + _identity(view, core, secret, restoring=True) - buttons = [_button("Stop", lambda: view.replace([home(view)]))] + buttons = [_button("Start again", lambda: view.replace([home(view)]))] if problem or not restoring else [] if restoring: - buttons.append( - _button("I have no wallet record", lambda: _identity(view, core, secret, restoring=True)) - ) - elif problem: + buttons.append(_button("I have no wallet record", without)) + elif problem and secret is not None: buttons.append(_button("Show it again", lambda: _identity(view, core, secret))) - buttons.append(_button("Check and continue", go, style="suggested-action")) + buttons.append(_button("Continue", go, style="suggested-action")) content = _column( _title( "Type the master fingerprint", "Copy it from the wallet record you keep apart from the cards." @@ -1125,13 +1117,44 @@ def follow(mismatch: str) -> Adw.NavigationPage | None: group, status, _note( - "If it does not match, stop: these cards are not that wallet. Bitcoin Core has not been changed." - if restoring - else "This checks that your wallet record is right while it can still be fixed.", - "warning" if restoring else "", + "This checks that your wallet record is right while it can still be fixed." + if not restoring + else "Check what you typed against the record. If it matches, these cards are from another " + "wallet, or a card was misread: start again and re-enter the cards." + if problem + else "codex32 checks this before it restores your wallet in Bitcoin Core.", + "warning" if problem else "", ), ) - return _page("Wallet record", content, actions=_actions(*buttons), can_pop=False) + return _page("Wallet record", content, actions=_actions(*buttons), can_pop=secret is None) + + +def _check_record( + view: Adw.NavigationView, + core: BitcoinCore, + secret: MasterSeed, + expected: bytes, + start: Timestamp, + *, + restoring: bool, +) -> None: + """Refuse a mismatch in the library, then let the operator choose the wallet.""" + page = _working(view, "Wallet record", "Checking the wallet record…") + + def job() -> str: + try: + wallet_setup.verify(core, secret, expected, start) + except wallet_setup.BitcoinCoreError as error: + return str(error) + return "" + + def follow(mismatch: str) -> Adw.NavigationPage | None: + if mismatch: + return _fingerprint_page(view, core, secret, start, restoring=restoring, problem=mismatch) + _wallets(view, core, secret, start, expected, restoring=restoring) + return None + + work.run(view, page, job, _then(view, page, follow, CARDS_SAFE)) def _import( @@ -1229,6 +1252,7 @@ def _collect( wanted: int | None = None, reserved: tuple[str, ...] = (), repaired: bool = False, + record: Callable[[MasterSeed], bool] | None = None, then: Callable[[tuple[Artifact, ...], bool], None], ) -> Adw.NavigationPage: """Take one card, and keep taking them until the backup has enough.""" @@ -1281,6 +1305,7 @@ def accept(artifact: Artifact, guessed: bool = False) -> None: wanted=wanted, reserved=reserved, repaired=repaired or guessed, + record=record, then=then, ), ) @@ -1308,7 +1333,7 @@ def following() -> Adw.NavigationPage: gated = result.low_checksum_discrimination view.push(_guess_gate_page(view, following) if gated else following()) - work.run(view, spinner, lambda: reading.repair(observed, length, excluded), deliver) + work.run(view, spinner, lambda: reading.repair(observed, length, excluded, accepted, record), deliver) field.connect("changed", update) progress = [] @@ -1605,22 +1630,28 @@ def _share_done_page(view: Adw.NavigationView, share: Share) -> Adw.NavigationPa ) -def _restore(view: Adw.NavigationView, core: BitcoinCore, secret: Secret) -> None: - if not isinstance(secret, MasterSeed): - _failure(view, "Only a Bitcoin master-seed backup can restore a wallet.") - return - _replace(view, _fingerprint_page(view, core, secret, 0, restoring=True)) +def _restore_cards( + view: Adw.NavigationView, core: BitcoinCore, expected: bytes | None, start: Timestamp +) -> Adw.NavigationPage: + """Take the cards; a recorded fingerprint settles competing repairs, then is checked again.""" + def restore(secret: Secret) -> None: + if not isinstance(secret, MasterSeed): + _failure(view, "Only a Bitcoin master-seed backup can restore a wallet.") + elif expected is None: + _identity(view, core, secret, restoring=True) + else: + _check_record(view, core, secret, expected, start, restoring=True) -def _start_restore(view: Adw.NavigationView) -> None: - _connect( + return _collect( view, - None, - lambda core: _collect( - view, - title="Restore my wallet", - heading="Enter your cards", - body="Type what each card says. Nothing is saved and nothing leaves this computer.", - then=lambda found, _guessed: _recover(view, found, lambda secret: _restore(view, core, secret)), - ), + title="Restore my wallet", + heading="Enter your cards", + body="Type what each card says. Nothing is saved and nothing leaves this computer.", + record=(lambda seed: core.fingerprint(seed) == expected) if expected else None, + then=lambda found, _guessed: _recover(view, found, restore), ) + + +def _start_restore(view: Adw.NavigationView) -> None: + _connect(view, None, lambda core: _fingerprint_page(view, core, None, 0, restoring=True)) diff --git a/src/codex32_gui/reading.py b/src/codex32_gui/reading.py index e8e1cf3d..c9fa321b 100644 --- a/src/codex32_gui/reading.py +++ b/src/codex32_gui/reading.py @@ -2,12 +2,14 @@ from __future__ import annotations +from collections.abc import Callable from dataclasses import dataclass from codex32 import ( CorrectionCandidate, CorrectionContext, Header, + MasterSeed, Profile, Secret, Share, @@ -15,7 +17,7 @@ parse_codex32, ) from codex32.bech32 import CHARSET -from codex32.correction import _best +from codex32.correction import _best, _record_match from codex32.errors import CodexError, InvalidShareIndex from codex32.profiles.ms32 import TEXT_LENGTHS @@ -138,15 +140,24 @@ def read(text: str, *, accepted: tuple[str, ...] = (), length: int | None = None return Reading(artifact.text, artifact, "Every character checks out.", "success", expected, 0) -def repair(text: str, length: int | None, excluded: tuple[str, ...] = ()) -> CorrectionCandidate | str: +def repair( + text: str, + length: int | None, + excluded: tuple[str, ...] = (), + accepted: tuple[Share | Secret, ...] = (), + record: Callable[[MasterSeed], bool] | None = None, +) -> CorrectionCandidate | str: """Ask the library for one repair, and offer nothing at all when it is unsure. - `_best` is the command line's own tie-breaker, minus its Bitcoin Core - fingerprint hint, which would make repairing a card need a running node. + `_best` is the command line's own tie-breaker, minus its backup-identifier + hint; `record` says whether a seed is the wallet record's, typed before a restore. Anything still tied afterwards is reported as ambiguous rather than shown. """ + recorded = _record_match(record, accepted) if record else None try: - found = _best(correct(CorrectionContext(Profile.MS, length, PREFIX, excluded), text)) + found = _best( + correct(CorrectionContext(Profile.MS, length, PREFIX, excluded), text), recorded=recorded + ) except CodexError as error: return str(error) if not found: diff --git a/src/codex32_gui/style.py b/src/codex32_gui/style.py index 6c3cbca2..4fa1dd25 100644 --- a/src/codex32_gui/style.py +++ b/src/codex32_gui/style.py @@ -11,7 +11,7 @@ font-size: 1.1rem; letter-spacing: 0.06em; } -.card-group { +.card-group, .compact .suffixes > label { font-family: monospace; font-size: 1.35rem; font-weight: bold; diff --git a/src/codex32_gui/wallet_setup.py b/src/codex32_gui/wallet_setup.py index b8e540d6..09bf2936 100644 --- a/src/codex32_gui/wallet_setup.py +++ b/src/codex32_gui/wallet_setup.py @@ -147,13 +147,13 @@ def network(core: BitcoinCore) -> str: def fingerprint(core: BitcoinCore, secret: MasterSeed) -> str: """Return the BIP32 master fingerprint, derived by Bitcoin Core out of process.""" - return core.fingerprint(secret).hex() + return core.fingerprint(secret).hex().upper() def identity(core: BitcoinCore, secret: MasterSeed) -> tuple[str, str]: """Return the recovered fingerprint and what the backup identifier says about the seed.""" fingerprint = core.fingerprint(secret) - return fingerprint.hex(), identifier_note(identifier_origin(secret, fingerprint)) + return fingerprint.hex().upper(), identifier_note(identifier_origin(secret, fingerprint)) def verify(core: BitcoinCore, secret: MasterSeed, expected: bytes | None, start: Timestamp) -> None: diff --git a/tests/test_bitcoin_core.py b/tests/test_bitcoin_core.py index 557f7962..4261a0b7 100644 --- a/tests/test_bitcoin_core.py +++ b/tests/test_bitcoin_core.py @@ -784,7 +784,7 @@ def test_identity_mismatch_stops_before_any_wallet_call(monkeypatch: pytest.Monk lambda client, *args, wallet=None, stdin=None: rpc(client, *args, wallet=wallet, stdin=stdin), ) - with pytest.raises(FingerprintMismatch, match="Bitcoin Core was not changed"): + with pytest.raises(FingerprintMismatch, match="No wallet was created or restored"): BitcoinCore("bitcoin-cli", "main", 300000).initialize( _SEED, lambda _prompt: "yes", diff --git a/tests/test_cli.py b/tests/test_cli.py index 24319580..c1a64831 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -132,13 +132,17 @@ def _offline_core(monkeypatch): _RECORDED_FINGERPRINT = importlib.import_module("codex32.cli")._recorded_fingerprint +_RECORD = importlib.import_module("codex32.cli")._record _SHOW_FINGERPRINT = importlib.import_module("codex32.cli")._show_fingerprint @pytest.fixture(autouse=True) def _matching_record(monkeypatch): """Keep unrelated CLI tests independent of wallet-record interaction.""" - monkeypatch.setattr("codex32.cli._recorded_fingerprint", lambda core, secret: core.fingerprint(secret)) + monkeypatch.setattr("codex32.cli._record", lambda: None) + monkeypatch.setattr( + "codex32.cli._recorded_fingerprint", lambda core, secret, _record: core.fingerprint(secret) + ) monkeypatch.setattr("codex32.cli._show_fingerprint", lambda _core, _secret, _action: None) @@ -1967,7 +1971,7 @@ def test_wallet_private_warning_precedes_recovery_input( ) -> None: cli_module = importlib.import_module("codex32.cli") - def stop_before_input(_fingerprint=None) -> MasterSeed: + def stop_before_input(_fingerprint=None, _record=None) -> MasterSeed: assert "Warning: This imports private descriptors that can spend funds." in capsys.readouterr().err raise cli_module._UsageError("stopped") @@ -1978,6 +1982,44 @@ def stop_before_input(_fingerprint=None) -> MasterSeed: assert ms_main(["wallet"]) == 2 +def test_wallet_asks_for_the_record_before_any_card(monkeypatch: pytest.MonkeyPatch) -> None: + cli_module = importlib.import_module("codex32.cli") + order: list[object] = [] + monkeypatch.setattr(cli_module, "_record", lambda: order.append("record") or b"\x01\x02\x03\x04") + + def cards(_fingerprint=None, record=None) -> MasterSeed: + order.append(("cards", record)) + raise cli_module._UsageError("stopped") + + monkeypatch.setattr(cli_module, "_master_seed", cards) + monkeypatch.setattr(cli_module.BitcoinCore, "connect", lambda *_args: _FakeBitcoinCore()) + monkeypatch.setattr(cli_module.sys, "stdin", _TTYInput()) + + assert ms_main(["wallet"]) == 2 + assert order == ["record", ("cards", b"\x01\x02\x03\x04")] + + +def test_card_suggestions_rank_by_the_record_typed_first() -> None: + from codex32._cli_input import _suggestions + + core, secret = _FakeBitcoinCore(), parse_codex32(VECTOR_1["secret_s"]) + assert isinstance(secret, MasterSeed) + damaged = secret.text[:-1] + ("q" if secret.text[-1] != "q" else "p") + recorded: list[bool | None] = [] + spy = importlib.import_module("codex32._cli_input")._record_match + + def matcher(*args: object) -> object: + match = spy(*args) + return lambda candidate: recorded.append(match(candidate)) or recorded[-1] + + with patch("codex32._cli_input._record_match", matcher): + found = _suggestions( + damaged, "", None, [], fingerprint=core.fingerprint, record=core.fingerprint(secret) + ) + assert [candidate.artifact.text for candidate in found] == [secret.text] + assert True in recorded + + def test_wallet_cli_rejects_non_ms_profiles() -> None: for command in ( ("xprv",), @@ -2042,7 +2084,7 @@ def test_production_size_budgets_are_enforced() -> None: for path in package.rglob("*.py") } - assert sum(counts.values()) < 5025, counts + assert sum(counts.values()) < 5068, counts @pytest.mark.parametrize( @@ -2831,12 +2873,13 @@ def test_restore_record_prompt_retries_until_the_library_accepts( assert isinstance(secret, MasterSeed) right = core.fingerprint(secret) wrong = bytes([right[0] ^ 1]) + right[1:] - prompts = _record_answers(monkeypatch, "not hex", wrong.hex(), right.hex().upper()) + monkeypatch.setattr("codex32.cli._record", _RECORD) + prompts = _record_answers(monkeypatch, "not hex", right.hex().upper()) - assert _RECORDED_FINGERPRINT(core, secret) == right - assert prompts == ["Type the master fingerprint from your wallet record (Enter if none)"] * 3 + assert _RECORDED_FINGERPRINT(core, secret, wrong) == right + assert prompts == ["Type the master fingerprint from your wallet record (Enter if none)"] * 2 errors = capsys.readouterr().err - assert "8 characters" in errors and "does not match" in errors + assert "8 characters" in errors and "do not make" in errors and "Check what you typed" in errors assert right.hex() not in errors.lower() @@ -2847,16 +2890,17 @@ def test_restore_without_a_record_shows_what_the_cards_say_and_asks( assert isinstance(secret, MasterSeed) fingerprint = core.fingerprint(secret) - prompts = _record_answers(monkeypatch, "", "n", "", "y") - assert _RECORDED_FINGERPRINT(core, secret) is None - assert prompts[1] == prompts[3] == "Restore without a wallet record? [y/N]" + monkeypatch.setattr("codex32.cli._record", _RECORD) + prompts = _record_answers(monkeypatch, "n", "", "y") + assert _RECORDED_FINGERPRINT(core, secret, None) is None + assert prompts[0] == prompts[2] == "Restore without a wallet record? [y/N]" shown = capsys.readouterr().err assert shown.count(f"Master fingerprint: {fingerprint.hex().upper()}") == 2 assert "was not made from this seed" in shown and "nothing can prove" in shown derived = MasterSeed.from_seed(secret.seed_bytes, identifier=_fingerprint_identifier(fingerprint)) - _record_answers(monkeypatch, "", "yes") - assert _RECORDED_FINGERPRINT(core, derived) is None + _record_answers(monkeypatch, "yes") + assert _RECORDED_FINGERPRINT(core, derived, None) is None assert "matches this seed (codex32 rule)" in capsys.readouterr().err diff --git a/tests/test_correction_indel.py b/tests/test_correction_indel.py index 9dcb99ac..b0bbf3a1 100644 --- a/tests/test_correction_indel.py +++ b/tests/test_correction_indel.py @@ -6,13 +6,20 @@ from unittest.mock import patch import pytest -from data.bip93_vectors import VECTOR_1, VECTOR_5 +from data.bip93_vectors import VECTOR_1, VECTOR_2, VECTOR_5 from data.sharing_vectors import SHARING_VECTORS from test_bip39 import BIP39_12W_ZERO, BIP39_24W_ZERO -from codex32 import CorrectionContext, MasterSeed, Profile, correct +from codex32 import CorrectionContext, MasterSeed, Profile, correct, parse_codex32 from codex32._cli_input import _correction_plan, _fingerprint_matcher -from codex32.correction import CorrectionCandidate, _best, _capture_volume, _erasure_state, _primary +from codex32.correction import ( + CorrectionCandidate, + _best, + _capture_volume, + _erasure_state, + _primary, + _record_match, +) from codex32.generation import _fingerprint_identifier from codex32.indel import ( _CHARACTER_CLASSES, @@ -422,6 +429,38 @@ def test_cli_tie_breaks_follow_hamming_crc_then_fingerprint() -> None: assert _best((high_hamming, crc, fingerprint_match), fingerprint_match=matcher) == (fingerprint_match,) +def test_a_wallet_record_match_outranks_every_other_ranking_in_best() -> None: + def fingerprint(secret: MasterSeed) -> bytes: + return fingerprint_seed(secret.seed_bytes) + + right = MasterSeed.from_seed(bytes(range(16)), identifier="test") + near = CorrectionCandidate( + MasterSeed.from_seed(bytes(range(1, 17)), identifier="test"), (), 9, 0, 1, True + ) + far = CorrectionCandidate(right, (), 12, 0, 5, False) + + assert _best( + (near, far), recorded=_record_match(lambda seed: fingerprint(seed) == fingerprint(right)) + ) == (far,) + # A record nothing matches leaves the ordinary ranking alone. + assert _best((near, far), recorded=_record_match(lambda seed: fingerprint(seed) == bytes(4))) == (near,) + + +def test_a_wallet_record_match_judges_a_share_only_when_it_completes_the_seed() -> None: + first, last = (parse_codex32(VECTOR_2[name]) for name in ("share_A", "share_C")) + secret = parse_codex32(VECTOR_2["secret_S"]) + assert isinstance(secret, MasterSeed) + expected = fingerprint_seed(secret.seed_bytes) + candidate = CorrectionCandidate(last, (), 10, 0, 2, None) + + def recorded(seed: MasterSeed) -> bool: + return fingerprint_seed(seed.seed_bytes) == expected + + assert _record_match(recorded, (first,))(candidate) is True + assert _record_match(lambda _seed: False, (first,))(candidate) is False + assert _record_match(recorded)(candidate) is None + + def test_lower_primary_volume_always_wins_cli_ties() -> None: source = MasterSeed.from_seed(bytes(range(16)), identifier="test") better_volume = CorrectionCandidate(source, (), 9, 0, 5, False) diff --git a/tests/test_gui_boundaries.py b/tests/test_gui_boundaries.py index e2ada80c..8933ce86 100644 --- a/tests/test_gui_boundaries.py +++ b/tests/test_gui_boundaries.py @@ -33,7 +33,7 @@ } ) CORE_ADAPTER = "codex32._bitcoin_core" -BUDGET = 2063 +BUDGET = 2100 def _package() -> Path: @@ -132,9 +132,15 @@ def test_the_gui_keeps_its_own_size_budget() -> None: def test_every_restore_way_to_a_wallet_passes_the_identity_choice() -> None: tree = ast.parse((_package() / "pages.py").read_text()) - assert _callers(tree, "_wallets") == {"_fingerprint_page", "_identity", "_wallet_page"} - assert _callers(tree, "_fingerprint_page") == {"_identity", "_restore", "_fingerprint_page"} - assert _callers(tree, "_identity") == {"_unshared_page", "_card_confirmed", "_fingerprint_page"} + assert _callers(tree, "_wallets") == {"_check_record", "_identity", "_wallet_page"} + assert _callers(tree, "_check_record") == {"_fingerprint_page", "_restore_cards"} + assert _callers(tree, "_fingerprint_page") == {"_identity", "_start_restore", "_check_record"} + assert _callers(tree, "_identity") == { + "_unshared_page", + "_card_confirmed", + "_fingerprint_page", + "_restore_cards", + } def test_restore_verifies_identity_before_creating_a_destination_wallet() -> None: diff --git a/tests/test_gui_reading.py b/tests/test_gui_reading.py index 1641922f..beac067f 100644 --- a/tests/test_gui_reading.py +++ b/tests/test_gui_reading.py @@ -119,6 +119,21 @@ def test_one_repair_is_offered_for_one_damaged_character() -> None: assert not found.low_checksum_discrimination +def test_the_last_card_is_repaired_against_the_wallet_record_typed_first() -> None: + from codex32 import CorrectionCandidate, MasterSeed, parse_codex32 + + first, secret = parse_codex32(SHARE_A), parse_codex32(VECTOR_2["secret_S"]) + asked: list[MasterSeed] = [] + + def record(seed: MasterSeed) -> bool: + asked.append(seed) + return seed == secret + + found = repair(SHARE_C[:-1] + "M", 48, ("a",), (first,), record) + assert isinstance(found, CorrectionCandidate) and found.artifact.text == SHARE_C + assert [seed.text for seed in asked] == [secret.text] + + def test_a_card_that_fits_no_repair_says_so_instead_of_guessing() -> None: assert isinstance(repair(PREFIX + "Q" * 45, None), str)