Skip to content
2 changes: 1 addition & 1 deletion docs/security/model.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
17 changes: 10 additions & 7 deletions docs/user/gui.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
10 changes: 6 additions & 4 deletions docs/user/guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/codex32/_bitcoin_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
20 changes: 18 additions & 2 deletions src/codex32/_cli_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -565,6 +576,7 @@ def _suggestions(
deadline=deadline,
capture_layers=capture_layers,
fingerprint_match=fingerprint_match,
recorded=recorded,
)[0]


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -740,6 +753,7 @@ def allowed(candidate: CorrectionCandidate) -> bool:
accepted,
allowed=allowed,
fingerprint=fingerprint,
record=record,
)
)
confirmation = (
Expand Down Expand Up @@ -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(
Expand All @@ -810,6 +825,7 @@ def read_artifacts(
profiles=profiles,
initial_prefix=initial_prefix,
fingerprint=fingerprint,
record=record,
)
_stderr("")
return result
50 changes: 30 additions & 20 deletions src/codex32/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -659,6 +668,7 @@ def _bitcoin_core(account: int, timestamp: int | Literal["now"]) -> int:
fresh=False,
restore=True,
confirmed=False,
record=record,
)


Expand Down
26 changes: 25 additions & 1 deletion src/codex32/correction.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Comment on lines +850 to +851

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply record-aware ranking before search pruning

When the repair matching the recorded fingerprint has a higher capture volume than another valid repair, this filter cannot select it: both upstream search paths have already discarded it. The CLI's _search_competitors prunes higher-volume layers and returns only _primary(...), and the GUI's correct() path through _search_many does the same. Consequently, the new promise that a record match outranks capture volume works only in the synthetic _best test, not in either actual recovery flow; users can still receive the wrong repair followed by an identity mismatch. Pass the record-aware ranking into discovery/pruning, rather than applying it only to the surviving primary candidates.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed. _search_competitors and the non-competitor path of _search_many both return only _primary(...), so a record match can only choose among the lowest-capture-volume repairs. ddca9ab corrects the _best docstring and the test name so they don't claim more than that.

What the change still does: it settles ties among those repairs, beating the Hamming, CRC and identifier hints, which are what currently produce "More than one repair is possible". Searching costlier layers when no primary repair matches would change the search's budget and timing. It would also cost two bitcoin-cli calls per candidate. I'm leaving that call to the maintainer and not widening this PR.


Generated by Claude Code

tied = list(_primary(candidates))
if not tied:
return ()
Expand All @@ -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]:
Expand Down
Loading
Loading