From cfb4272e397afef5cccd2011c5e9ec6149553557 Mon Sep 17 00:00:00 2001 From: Ben Westgate Date: Wed, 4 Nov 2026 14:27:25 +0000 Subject: [PATCH 1/6] wallet: Date a new wallet by this computer's clock Bitcoin Core resolves an import timestamp of "now" to its tip's median time. On an offline signer that never synced, that is the genesis block, so every new wallet was born in 2009, and the watch-only copy Bails exports from it asks the online node to rescan from genesis, which a pruned node cannot do. A new wallet now takes this computer's clock, a day early like a recorded creation date, so a clock running up to a day fast cannot skip its first payments. Restores keep the recorded date. On a Core 32.1 regtest signer at genesis, the descriptors were dated 1296688602 (genesis) before and the clock less a day after; the signer still found a payment from blocks it synced later. Claude-Session: https://claude.ai/code/session_01N8jLK61uohaW6W7Y8AHnMb --- src/codex32/_bitcoin_core.py | 6 +++++- tests/test_bitcoin_core.py | 4 +++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/codex32/_bitcoin_core.py b/src/codex32/_bitcoin_core.py index b2689ea5..99525610 100644 --- a/src/codex32/_bitcoin_core.py +++ b/src/codex32/_bitcoin_core.py @@ -449,12 +449,16 @@ def initialize( continue # Checked last, after any wait above: a pruning node keeps pruning while it waits. self.check_history(timestamp) + # Core's "now" is its tip's time: the genesis block's on an offline signer that never + # synced, and watch-only exports carry it. A new wallet takes this computer's clock, + # a day early like a record's date, so a fast clock cannot skip its first payments. + start = max(0, int(time.time()) - 86400) if timestamp == "now" else timestamp records = core_descriptors( secret, account=account, testnet=self.chain != "main", private=True, - timestamp=timestamp, + timestamp=start, ) imported = self._rpc( "importdescriptors", diff --git a/tests/test_bitcoin_core.py b/tests/test_bitcoin_core.py index f0ecee7e..557f7962 100644 --- a/tests/test_bitcoin_core.py +++ b/tests/test_bitcoin_core.py @@ -391,6 +391,7 @@ def test_encrypted_import_retries_without_a_passphrase_verifies_and_relocks( "_rpc", lambda client, *args, wallet=None, stdin=None: rpc(client, *args, wallet=wallet, stdin=stdin), ) + monkeypatch.setattr("codex32._bitcoin_core.time.time", lambda: 1_700_000_000.5) client = BitcoinCore("bitcoin-cli", "main", 300000) messages: list[str] = [] delays: list[int] = [] @@ -411,7 +412,8 @@ def unlock(seconds: int) -> None: assert arguments == ("importdescriptors",) and wallet == "signer" assert private_stdin is not None and private_stdin.endswith("\n") records = json.loads(private_stdin) - assert len(records) == 4 and all(record["timestamp"] == "now" for record in records) + # A new wallet's "now" is this computer's clock less a day, not Core's tip (genesis offline). + assert len(records) == 4 and all(record["timestamp"] == 1_700_000_000 - 86400 for record in records) assert all("xprv" in record["desc"] for record in records) assert all("xprv" not in " ".join((*args, selected or "")) for args, selected, _data in rpc.calls) assert sum(args[:2] == ("-named", "derivehdkey") for args, _wallet, _stdin in rpc.calls) == 4 From ae9d360a74020b00e5d0dcf0703fa7e9fce6de50 Mon Sep 17 00:00:00 2001 From: Ben Westgate Date: Wed, 4 Nov 2026 18:05:16 +0000 Subject: [PATCH 2/6] wallet: Keep the new-wallet timestamp within the size budget Claude-Session: https://claude.ai/code/session_01N8jLK61uohaW6W7Y8AHnMb --- src/codex32/_bitcoin_core.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/codex32/_bitcoin_core.py b/src/codex32/_bitcoin_core.py index 99525610..b1eae17c 100644 --- a/src/codex32/_bitcoin_core.py +++ b/src/codex32/_bitcoin_core.py @@ -452,13 +452,12 @@ def initialize( # Core's "now" is its tip's time: the genesis block's on an offline signer that never # synced, and watch-only exports carry it. A new wallet takes this computer's clock, # a day early like a record's date, so a fast clock cannot skip its first payments. - start = max(0, int(time.time()) - 86400) if timestamp == "now" else timestamp records = core_descriptors( secret, account=account, testnet=self.chain != "main", private=True, - timestamp=start, + timestamp=max(0, int(time.time()) - 86400) if timestamp == "now" else timestamp, ) imported = self._rpc( "importdescriptors", From 1c7c5e3ff7478cc5ffafed5c6964d70f7db5253a Mon Sep 17 00:00:00 2001 From: Ben Westgate Date: Tue, 10 Nov 2026 22:12:19 +0000 Subject: [PATCH 3/6] gui: Show wallet record values large and dark The backup identifier and master fingerprint were small, dim row subtitles, hard to copy onto the wallet record. Rows that show values now use libadwaita's property style with the card-group text style, and the fingerprint is uppercase, as the CLI prints it. Claude-Session: https://claude.ai/code/session_01N8jLK8HGLaWJq2AJGmxPVe --- src/codex32_gui/pages.py | 4 +++- src/codex32_gui/style.py | 2 +- src/codex32_gui/wallet_setup.py | 4 ++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/codex32_gui/pages.py b/src/codex32_gui/pages.py index 6ed80813..a99f3a36 100644 --- a/src/codex32_gui/pages.py +++ b/src/codex32_gui/pages.py @@ -217,7 +217,9 @@ def _blank(flow: Gtk.FlowBox) -> None: def _rows(title: str, values: Sequence[tuple[str, str]]) -> Adw.PreferencesGroup: group = Adw.PreferencesGroup(title=title) for label, value in values: - group.add(Adw.ActionRow(title=label, subtitle=value, subtitle_selectable=True, use_markup=False)) + row = Adw.ActionRow(title=label, subtitle=value, subtitle_selectable=True, use_markup=False) + row.add_css_class("property") # libadwaita's style for a value: subtitle at full strength. + group.add(row) return group diff --git a/src/codex32_gui/style.py b/src/codex32_gui/style.py index 2bc7879b..4855421f 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, .property .subtitle { 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: From 6bcbfa042406403b5e66f25528330d872599d827 Mon Sep 17 00:00:00 2001 From: Ben Westgate Date: Tue, 10 Nov 2026 17:32:36 -0600 Subject: [PATCH 4/6] gui: Grow the window so no page needs scrolling (#223) Every page now asks the window to grow, never past the screen's height, whenever its content is taller than the space it has: on arrival, when a section opens, and when a message gets longer. A window the operator shrinks grows back to fit. The scroller stays as the last resort on a screen too short for the page. Name-and-value rows (wallet identity, wallet record, new card) are one line each, value on the right, so the finished page fits the default 880x620 window and reads straight down against the paper record. The GUI size budget rises by the 13 lines this takes. Claude-Session: https://claude.ai/code/session_01N8jLK9eptxLjUcNnMk1VGr --- src/codex32_gui/pages.py | 18 +++++++++++++++--- src/codex32_gui/style.py | 5 +++++ tests/test_gui_boundaries.py | 2 +- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/codex32_gui/pages.py b/src/codex32_gui/pages.py index 6ed80813..4dbccb95 100644 --- a/src/codex32_gui/pages.py +++ b/src/codex32_gui/pages.py @@ -12,7 +12,7 @@ from dataclasses import dataclass from typing import Literal -from gi.repository import Adw, Gio, GLib, Gtk +from gi.repository import Adw, Gio, GLib, Gtk, Pango from codex32 import ( ConfirmationResult, @@ -111,6 +111,7 @@ def _page( ) -> Adw.NavigationPage: scroller = Gtk.ScrolledWindow(hscrollbar_policy=Gtk.PolicyType.NEVER, vexpand=True) scroller.set_child(Adw.Clamp(maximum_size=700, child=content, margin_start=18, margin_end=18)) + scroller.get_vadjustment().connect("changed", lambda shown: _grow(scroller, shown)) bars = Adw.ToolbarView() bars.add_top_bar(Adw.HeaderBar()) bars.set_content(scroller) @@ -121,6 +122,15 @@ def _page( return page +def _grow(scroller: Gtk.ScrolledWindow, shown: Gtk.Adjustment) -> None: + """Make the window taller, never past the screen, until the page needs no scrolling.""" + window, short = scroller.get_root(), shown.get_upper() - shown.get_page_size() + if short > 0 and isinstance(window, Gtk.Window) and (surface := window.get_surface()) is not None: + width, height = window.get_default_size() + screen = window.get_display().get_monitor_at_surface(surface).get_geometry().height + window.set_default_size(width, min(height + int(short) + 1, screen)) + + def _column(*children: Gtk.Widget) -> Gtk.Box: box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=14, margin_top=18, margin_bottom=18) for child in children: @@ -215,9 +225,11 @@ def _blank(flow: Gtk.FlowBox) -> None: def _rows(title: str, values: Sequence[tuple[str, str]]) -> Adw.PreferencesGroup: - group = Adw.PreferencesGroup(title=title) + group = Adw.PreferencesGroup(title=title, css_classes=["compact"]) for label, value in values: - group.add(Adw.ActionRow(title=label, subtitle=value, subtitle_selectable=True, use_markup=False)) + row = Adw.ActionRow(title=label, use_markup=False) + row.add_suffix(Gtk.Label(label=value, selectable=True, wrap=True, wrap_mode=Pango.WrapMode.WORD_CHAR)) + group.add(row) return group diff --git a/src/codex32_gui/style.py b/src/codex32_gui/style.py index 2bc7879b..6c3cbca2 100644 --- a/src/codex32_gui/style.py +++ b/src/codex32_gui/style.py @@ -27,6 +27,11 @@ border-radius: 12px; padding: 14px; } +.compact row > box.header { + min-height: 0; + padding-top: 0; + padding-bottom: 0; +} .reading { font-size: 0.9rem; } diff --git a/tests/test_gui_boundaries.py b/tests/test_gui_boundaries.py index 1d73c9c7..e2ada80c 100644 --- a/tests/test_gui_boundaries.py +++ b/tests/test_gui_boundaries.py @@ -33,7 +33,7 @@ } ) CORE_ADAPTER = "codex32._bitcoin_core" -BUDGET = 2050 +BUDGET = 2063 def _package() -> Path: From 7860bd86b85019732ed1fbb0558256adca905e12 Mon Sep 17 00:00:00 2001 From: Ben Westgate Date: Tue, 17 Nov 2026 21:05:36 +0000 Subject: [PATCH 5/6] wallet: Ask for the wallet record before the cards Restore now takes the master fingerprint from the wallet record before any card, in the CLI (`ms32 wallet`) and the GUI. While the cards are entered, a correction whose recovered seed makes that fingerprint outranks every other candidate and tie-breaker: a wrong seed matches 32 bits only 1 time in 2**32. Shares are judged only by the card that completes the seed. The operator still compares every suggestion with the whole card, and the library checks the fingerprint again after recovery, before any wallet is touched. "I have no wallet record" still works: it goes to the cards and then to the same no-record warning as before. GUI: the record page comes first and can go Back. "Stop" is gone; after a mismatch, "Start again" appears with advice. Wording follows Ben: "codex32 checks this before it restores your wallet in Bitcoin Core", and the library mismatch now says no wallet was created or restored. Budgets: library 5,025 -> 5,068, GUI 2,063 -> 2,100. Claude-Session: https://claude.ai/code/session_01N8jLK8HGLaWJq2AJGmxPVe --- docs/security/model.md | 2 +- docs/user/gui.md | 17 +++-- docs/user/guide.md | 10 +-- src/codex32/_bitcoin_core.py | 4 +- src/codex32/_cli_input.py | 20 +++++- src/codex32/cli.py | 50 ++++++++------ src/codex32/correction.py | 26 ++++++- src/codex32_gui/pages.py | 119 +++++++++++++++++++++------------ src/codex32_gui/reading.py | 21 ++++-- tests/test_bitcoin_core.py | 2 +- tests/test_cli.py | 68 +++++++++++++++---- tests/test_correction_indel.py | 45 ++++++++++++- tests/test_gui_boundaries.py | 14 ++-- tests/test_gui_reading.py | 15 +++++ 14 files changed, 307 insertions(+), 106 deletions(-) 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..7e2150d3 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 outranks everything: a wrong seed matches it 1 time in 2**32. + """ + 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/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..0887ddec 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_capture_volume_and_every_tie_breaker() -> 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) From ddca9ab55c93207abcfc03c695918f1d3ff63e4d Mon Sep 17 00:00:00 2001 From: Ben Westgate Date: Tue, 17 Nov 2026 21:09:29 +0000 Subject: [PATCH 6/6] correction: Say the record ranks only the search's best repairs Both search paths return only their lowest capture volume, so a record match cannot reach a costlier repair (Codex review on #221). Claude-Session: https://claude.ai/code/session_01N8jLK8HGLaWJq2AJGmxPVe --- src/codex32/correction.py | 2 +- tests/test_correction_indel.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/codex32/correction.py b/src/codex32/correction.py index 7e2150d3..b7b10e50 100644 --- a/src/codex32/correction.py +++ b/src/codex32/correction.py @@ -845,7 +845,7 @@ def _best( ) -> tuple[CorrectionCandidate, ...]: """Apply CLI-only Hamming and CRC tie breakers plus optional wallet hints. - A wallet-record match outranks everything: a wrong seed matches it 1 time in 2**32. + 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 diff --git a/tests/test_correction_indel.py b/tests/test_correction_indel.py index 0887ddec..b0bbf3a1 100644 --- a/tests/test_correction_indel.py +++ b/tests/test_correction_indel.py @@ -429,7 +429,7 @@ 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_capture_volume_and_every_tie_breaker() -> None: +def test_a_wallet_record_match_outranks_every_other_ranking_in_best() -> None: def fingerprint(secret: MasterSeed) -> bytes: return fingerprint_seed(secret.seed_bytes)