Skip to content

Commit 7860bd8

Browse files
committed
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
1 parent 5623394 commit 7860bd8

14 files changed

Lines changed: 307 additions & 106 deletions

‎docs/security/model.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ signing setup belong to Bitcoin Core's maintained v32 workflow.
228228
| Control | Required behavior |
229229
|---|---|
230230
| 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. |
231-
| 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. |
231+
| 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. |
232232
| 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. |
233233
| 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. |
234234
| 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. |

‎docs/user/gui.md‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -160,13 +160,16 @@ wallet**, which would make a different backup. If the wallet was part-filled
160160
before it failed, it is no longer empty, so it will not be offered again: create
161161
another one, or ask Bitcoin Core for a fresh blank wallet.
162162

163-
When you restore, the window first asks you to type the master fingerprint from
164-
your wallet record. If it does not match, nothing is written to Bitcoin Core:
165-
check what you typed, and if it still does not match, these cards are not that
166-
wallet. If you have no record, **I have no wallet record** shows the master
167-
fingerprint and whether the backup identifier was made from the recovered seed,
168-
explains what that can and cannot prove, and restores only if you still choose
169-
to. Check the balance and history before you send money to that wallet.
163+
When you restore, the window asks you to type the master fingerprint from your
164+
wallet record before any card. If a card needs a repair and more than one fits,
165+
the one that makes that fingerprint is offered; compare it with the whole card
166+
as always. After the cards, the fingerprint is checked again. If it does not
167+
match, nothing is restored: check what you typed, and if it still does not
168+
match, these cards are from another wallet or a card was misread. If you have
169+
no record, **I have no wallet record** goes straight to the cards; afterwards
170+
the window shows the master fingerprint and whether the backup identifier was
171+
made from the recovered seed, explains what that can and cannot prove, and
172+
restores only if you still choose to. Check the balance and history before you send money to that wallet.
170173

171174
The same page asks for the approximate creation date from your wallet record.
172175
Bitcoin Core searches for the wallet's transactions from a day before that date,

‎docs/user/guide.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -236,10 +236,12 @@ its public wallet data with the separate wallet record.
236236
ms32 wallet --timestamp 0
237237
```
238238

239-
5. Type the master fingerprint from the wallet record. A mismatch stops before
240-
Bitcoin Core is changed. Press Enter with nothing typed only if there is no
241-
record; codex32 then shows the recovered fingerprint and what the backup
242-
identifier says, and asks before restoring.
239+
5. Type the master fingerprint from the wallet record, then enter the cards.
240+
If more than one correction fits a damaged card, the one that makes that
241+
fingerprint is offered; still compare it with the whole card. A mismatch
242+
after the cards restores nothing. Press Enter with nothing typed only if
243+
there is no record; after the cards, codex32 shows the recovered fingerprint
244+
and what the backup identifier says, and asks before restoring.
243245
6. Select and confirm that wallet. If it is locked, follow the displayed
244246
Bitcoin-Qt Console instructions; codex32 waits and continues automatically.
245247
It imports the private descriptors, verifies the public set, and relocks an

‎src/codex32/_bitcoin_core.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -234,8 +234,8 @@ def verify_identity(self, secret: MasterSeed, expected_fingerprint: bytes | None
234234
return
235235
if self.fingerprint(secret) != expected_fingerprint:
236236
raise FingerprintMismatch(
237-
"The recovered master fingerprint does not match the one from the wallet record. "
238-
"Bitcoin Core was not changed."
237+
"These cards do not make the master fingerprint from the wallet record. "
238+
"No wallet was created or restored."
239239
)
240240

241241
def check_history(self, timestamp: int | Literal["now"]) -> None:

‎src/codex32/_cli_input.py‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
parse_codex32,
2020
recover_secret,
2121
)
22-
from codex32.correction import CorrectionCandidate, CorrectionContext, _best
22+
from codex32.correction import CorrectionCandidate, CorrectionContext, _best, _record_match
2323
from codex32.errors import (
2424
CodexError,
2525
DuplicateShareIndex,
@@ -460,6 +460,7 @@ def _correction_candidates(
460460
deadline: float | None = None,
461461
capture_layers: list[tuple[int, int]] | None = None,
462462
fingerprint_match: Callable[[CorrectionCandidate], bool | None] | None = None,
463+
recorded: Callable[[CorrectionCandidate], bool | None] | None = None,
463464
) -> tuple[tuple[CorrectionCandidate, ...], bool, float | None, bool]:
464465
count = len(value.replace(" ", ""))
465466
targets, primary, reduced, _timed = _correction_plan(profile, byte_length, count, target)
@@ -480,7 +481,12 @@ def _correction_candidates(
480481
if allowed is not None:
481482
candidates = tuple(candidate for candidate in candidates if allowed(candidate))
482483
results = (
483-
_best(candidates, prefer_common=byte_length == "?", fingerprint_match=fingerprint_match)
484+
_best(
485+
candidates,
486+
prefer_common=byte_length == "?",
487+
fingerprint_match=fingerprint_match,
488+
recorded=recorded,
489+
)
484490
if complete
485491
else candidates
486492
if len(candidates) == 1 and not candidates[0].search_complete
@@ -516,8 +522,12 @@ def _suggestions(
516522
*,
517523
allowed: Callable[[CorrectionCandidate], bool] | None = None,
518524
fingerprint: Callable[[MasterSeed], bytes] | None = None,
525+
record: bytes | None = None,
519526
) -> tuple[CorrectionCandidate, ...]:
520527
fingerprint_match = _fingerprint_matcher(fingerprint)
528+
recorded = (
529+
_record_match(lambda seed: fingerprint(seed) == record, accepted) if fingerprint and record else None
530+
)
521531
erased = value
522532
if interpretation := _case_interpretation(value, prefix, profiles, allowed):
523533
candidate, value, erased, prefix = interpretation
@@ -551,6 +561,7 @@ def _suggestions(
551561
deadline=deadline,
552562
capture_layers=capture_layers,
553563
fingerprint_match=fingerprint_match,
564+
recorded=recorded,
554565
)[0]
555566
if candidates or erased == value:
556567
return candidates
@@ -565,6 +576,7 @@ def _suggestions(
565576
deadline=deadline,
566577
capture_layers=capture_layers,
567578
fingerprint_match=fingerprint_match,
579+
recorded=recorded,
568580
)[0]
569581

570582

@@ -696,6 +708,7 @@ def _interactive(
696708
profiles: tuple[Profile, ...] | None,
697709
initial_prefix: str,
698710
fingerprint: Callable[[MasterSeed], bytes] | None,
711+
record: bytes | None = None,
699712
) -> list[Artifact]:
700713
accepted: list[Artifact] = []
701714
prefix = initial_prefix
@@ -740,6 +753,7 @@ def allowed(candidate: CorrectionCandidate) -> bool:
740753
accepted,
741754
allowed=allowed,
742755
fingerprint=fingerprint,
756+
record=record,
743757
)
744758
)
745759
confirmation = (
@@ -794,6 +808,7 @@ def read_artifacts(
794808
profiles: tuple[Profile, ...] | None = None,
795809
initial_prefix: str = "",
796810
fingerprint: Callable[[MasterSeed], bytes] | None = None,
811+
record: bytes | None = None,
797812
) -> list[Artifact]:
798813
if not sys.stdin.isatty():
799814
return _redirected(
@@ -810,6 +825,7 @@ def read_artifacts(
810825
profiles=profiles,
811826
initial_prefix=initial_prefix,
812827
fingerprint=fingerprint,
828+
record=record,
813829
)
814830
_stderr("")
815831
return result

‎src/codex32/cli.py‎

Lines changed: 30 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -103,9 +103,13 @@ def _secret(artifacts: list[Artifact]) -> Secret:
103103
raise _UsageError(str(error)) from error
104104

105105

106-
def _master_seed(fingerprint: Callable[[MasterSeed], bytes] | None = None) -> MasterSeed:
106+
def _master_seed(
107+
fingerprint: Callable[[MasterSeed], bytes] | None = None, record: bytes | None = None
108+
) -> MasterSeed:
107109
if isinstance(
108-
value := _secret(_artifacts(profiles=(Profile.MS,), initial_prefix="MS1", fingerprint=fingerprint)),
110+
value := _secret(
111+
_artifacts(profiles=(Profile.MS,), initial_prefix="MS1", fingerprint=fingerprint, record=record)
112+
),
109113
MasterSeed,
110114
):
111115
return value
@@ -370,26 +374,29 @@ def _creation_start() -> int:
370374
_print(str(error), err=True)
371375

372376

373-
def _recorded_fingerprint(core: BitcoinCore, secret: MasterSeed) -> bytes | None:
374-
"""Take the master fingerprint from a recovery record until the library accepts it."""
375-
prompt = "Type the master fingerprint from your wallet record (Enter if none)"
377+
def _record() -> bytes | None:
378+
"""Take the master fingerprint from the wallet record, or None when there is no record."""
376379
while True:
377-
text = _text(prompt, optional=True)
378-
if not text:
379-
if _without_record(core, secret):
380-
return None
381-
continue
380+
text = _text("Type the master fingerprint from your wallet record (Enter if none)", optional=True)
382381
try:
383-
expected = parse_fingerprint(text)
382+
return parse_fingerprint(text) if text else None
384383
except ValueError as error:
385384
_print(str(error), err=True)
386-
continue
387-
try:
388-
core.verify_identity(secret, expected)
389-
except FingerprintMismatch as error:
390-
_print(str(error), err=True)
391-
continue
392-
return expected
385+
386+
387+
def _recorded_fingerprint(core: BitcoinCore, secret: MasterSeed, expected: bytes | None) -> bytes | None:
388+
"""Check the record typed before the cards, and ask again until the library accepts it."""
389+
while True:
390+
if expected is None:
391+
if _without_record(core, secret):
392+
return None
393+
else:
394+
try:
395+
core.verify_identity(secret, expected)
396+
return expected
397+
except FingerprintMismatch as error:
398+
_print(f"{error} Check what you typed against the record.", err=True)
399+
expected = _record()
393400

394401

395402
def _initialize_wallet(
@@ -401,13 +408,14 @@ def _initialize_wallet(
401408
fresh: bool = True,
402409
restore: bool = False,
403410
confirmed: bool = True,
411+
record: bytes | None = None,
404412
) -> int:
405413
assert isinstance(secret, MasterSeed)
406414
try:
407415
if confirmed:
408416
_print("Master-seed backup confirmed.\n", err=True)
409417
if restore:
410-
expected = _recorded_fingerprint(core, secret)
418+
expected = _recorded_fingerprint(core, secret, record)
411419
else:
412420
_show_fingerprint(core, secret, "Write it on the wallet record")
413421
expected = None
@@ -650,7 +658,8 @@ def _bitcoin_core(account: int, timestamp: int | Literal["now"]) -> int:
650658
raise _UsageError("Bitcoin Core wallet initialization requires an interactive terminal.")
651659
_print("Warning: This imports private descriptors that can spend funds.", err=True, danger=True)
652660
core = _connected_core()
653-
secret = _master_seed(core.fingerprint)
661+
record = _record() # Asked first, so a known fingerprint can settle competing card corrections.
662+
secret = _master_seed(core.fingerprint, record)
654663
return _initialize_wallet(
655664
core,
656665
secret,
@@ -659,6 +668,7 @@ def _bitcoin_core(account: int, timestamp: int | Literal["now"]) -> int:
659668
fresh=False,
660669
restore=True,
661670
confirmed=False,
671+
record=record,
662672
)
663673

664674

‎src/codex32/correction.py‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
Share,
4343
_checksum_for_encoded_length,
4444
parse_codex32,
45+
recover_secret,
4546
)
4647
from codex32.checksums import _CODEX32, _CODEX32_LONG, _Checksum
4748
from codex32.errors import CodexError, InvalidCorrectionInput
@@ -840,8 +841,14 @@ def _best(
840841
*,
841842
prefer_common: bool = False,
842843
fingerprint_match: Callable[[CorrectionCandidate], bool | None] | None = None,
844+
recorded: Callable[[CorrectionCandidate], bool | None] | None = None,
843845
) -> tuple[CorrectionCandidate, ...]:
844-
"""Apply CLI-only Hamming and CRC tie breakers plus an optional wallet hint."""
846+
"""Apply CLI-only Hamming and CRC tie breakers plus optional wallet hints.
847+
848+
A wallet-record match outranks everything: a wrong seed matches it 1 time in 2**32.
849+
"""
850+
if recorded is not None and (matching := [item for item in candidates if recorded(item) is True]):
851+
candidates = matching
845852
tied = list(_primary(candidates))
846853
if not tied:
847854
return ()
@@ -858,6 +865,23 @@ def _best(
858865
return tuple(sorted(tied, key=_candidate_order))
859866

860867

868+
def _record_match(
869+
recorded: Callable[[MasterSeed], bool], accepted: Sequence[Share | Secret] = ()
870+
) -> Callable[[CorrectionCandidate], bool | None]:
871+
"""Ask whether a candidate is the recorded wallet, once it completes a master seed."""
872+
873+
def matches(candidate: CorrectionCandidate) -> bool | None:
874+
artifact, shares = candidate.artifact, [*accepted, candidate.artifact]
875+
try:
876+
if isinstance(artifact, Share) and len(shares) == artifact.header.threshold:
877+
artifact = recover_secret([share for share in shares if isinstance(share, Share)])
878+
return recorded(artifact) if isinstance(artifact, MasterSeed) else None
879+
except CodexError:
880+
return None
881+
882+
return matches
883+
884+
861885
def _correct_complete(
862886
context: CorrectionContext, damaged_text: str, *, deadline: float | None = None
863887
) -> tuple[tuple[CorrectionCandidate, ...], bool]:

0 commit comments

Comments
 (0)