Skip to content

Commit 7d1bf6d

Browse files
committed
gui: Require strong recovery commitment
1 parent 074793b commit 7d1bf6d

11 files changed

Lines changed: 165 additions & 37 deletions

File tree

‎docs/developer/api.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -640,10 +640,12 @@ fingerprint consistency, and network xpub/tpub versions, constructs only the
640640
fixed descriptor templates, and asks `getdescriptorinfo` to validate and expand
641641
their external/internal branches. The adapter then compares the exact eight
642642
active public descriptors against `listdescriptors`. It relocks wallets Core
643-
reports as encrypted. Master-fingerprint display is likewise delegated to Core:
644-
a stateless root P2PKH descriptor is normalized, `deriveaddresses` derives its
645-
address, and `validateaddress` returns the script hash whose first four bytes are
646-
the BIP32 fingerprint.
643+
reports as encrypted. Master-fingerprint and graphical recovery-commitment
644+
derivation are likewise delegated to Core. A stateless root P2PKH descriptor is
645+
normalized to its public root xpub. SHA-256 over the domain-separated canonical
646+
xpub supplies the 256-bit recovery commitment; `deriveaddresses` and
647+
`validateaddress` return the script hash whose first four bytes are the BIP32
648+
fingerprint. Neither operation opens or mutates a wallet.
647649

648650
The Core calls are fixed: `getnetworkinfo`, `getblockchaininfo`, `listwallets`,
649651
`getwalletinfo`, `listdescriptors`, `getdescriptorinfo`, `deriveaddresses`,

‎docs/security/invariants.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,10 @@ and evidence.
1212
gated by confirmation. Input cannot replace entropy or the original secret.
1313
4. Wallet setup uses the original ceremony result or a validated recovered seed.
1414
Graphical recovery derives public wallet identity first and requires the
15-
operator to confirm it against the separately stored wallet record before
16-
any recovered key material may mutate a Bitcoin Core wallet.
15+
operator to enter a separately stored SHA-256 commitment to the canonical
16+
root xpub before any recovered key material may mutate a Bitcoin Core wallet.
17+
The 32-bit BIP32 fingerprint is diagnostic metadata, never the authorization
18+
value for this transition.
1719
5. Correction shares one mass bound and deadline across target lengths. The
1820
public API fails closed on incomplete required work; CLI searches may return
1921
one primary-best-so-far eligible candidate at the deadline. Incomplete

‎docs/security/model.md‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,10 @@ The operator must:
6868
guarantee new physical entropy between calls.
6969
- A checksum, generation-padding hint, fingerprint, or correction candidate
7070
does not authenticate a backup or prove the operator's intent.
71+
- The graphical recovery commitment is a domain-separated SHA-256 digest of
72+
the canonical root xpub returned by Bitcoin Core. It is public metadata and
73+
authenticates only against the separately stored record; it is not a secret,
74+
a MAC, or proof that the record itself is trustworthy.
7175
- Creation feedback identifies correct groups but does not prove the recovery card was corrected.
7276
- A fresh unshared master seed exposes a public 20-bit BIP32 fingerprint in its
7377
default identifier; fingerprints are metadata, not secrets.
@@ -269,13 +273,16 @@ only while more than one answers. On screen a wallet is chosen by the position o
269273
its row, never by the text of its label, and Core's text is rendered without
270274
Pango markup, so a wallet name cannot hide or impersonate another.
271275

272-
Restore derives the recovered seed's master fingerprint through Bitcoin Core
273-
before destination selection and displays it with the backup identifier. The
274-
operator must explicitly confirm that fingerprint against the separately stored
275-
wallet record before the program lists, creates, unlocks, or imports into a
276-
destination wallet. A mismatch can therefore stop recovery without mutating a
277-
Bitcoin Core wallet. The fingerprint remains only a short diagnostic identifier;
278-
its authentication-strength limitation above still applies.
276+
Restore derives the recovered seed's canonical root xpub and master fingerprint
277+
through Bitcoin Core before destination selection. It computes the recovery
278+
commitment as `SHA256(domain_tag || root_xpub)`, where `domain_tag` is the
279+
ASCII text `codex32 recovery commitment` followed by one NUL byte. It asks the
280+
operator to enter the 256-bit value from the separately stored wallet
281+
record. The expected commitment is not displayed before comparison. Only a
282+
match permits the program to list, create, unlock, or import into a destination
283+
wallet, so a mismatch can stop recovery without mutating one. The fingerprint
284+
is still displayed as a short diagnostic identifier but is not used to authorize
285+
the transition.
279286

280287
The program draws no entropy, opens no socket, starts no process of its own, and
281288
writes no file: no settings, no recent list, no log, and no clipboard write of

‎docs/user/gui.md‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,10 @@ the seed. It protects the wallet on this computer.
7777

7878
Finally, copy the wallet details onto your
7979
[wallet record](wallet-verification-record.html) and keep it apart from every
80-
card. The window shows exactly the fields that record asks for.
80+
card. The window shows exactly the fields that record asks for, including a
81+
long recovery commitment. That commitment is public, but it must stay separate
82+
from the cards because the restore screen uses it to reject the wrong recovered
83+
seed before Bitcoin Core is changed.
8184

8285
A card never contains **B**, **I**, **O** or **1**: those four are left out of
8386
the alphabet precisely because handwriting confuses them with 8, J, L and 0. If
@@ -142,11 +145,17 @@ wallet**, which would make a different backup. If the wallet was part-filled
142145
before it failed, it is no longer empty, so it will not be offered again: create
143146
another one, or ask Bitcoin Core for a fresh blank wallet.
144147

145-
When you restore, the window asks you to **check** the wallet details against
146-
your record rather than copy them onto it. That comparison — the master
147-
fingerprint above all — is the only thing that proves the cards you just typed
148-
belong to that wallet. It shows no creation date on that screen, because the
149-
real one is already on your record and today's would replace it.
148+
When you restore, the window first asks you to type the recovery commitment from
149+
the separate wallet record. It deliberately does not show the value it expects.
150+
If the value does not match, it does not list, create, unlock, or fill a Bitcoin
151+
Core wallet. Do not substitute the shorter master fingerprint. Older wallet
152+
records without a recovery commitment need to be updated before relying on this
153+
pre-import check.
154+
155+
After a successful restore, the window asks you to check the remaining wallet
156+
details against the record rather than copy them onto it. It shows no creation
157+
date on that screen, because the real one is already on your record and today's
158+
would replace it.
150159

151160
The window always uses account 0, which is what it writes onto your wallet
152161
record. If you are restoring a wallet whose record shows a different account

‎docs/user/guide.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,8 +169,8 @@ wallet should be trusted until initialization completes.
169169
### 4. Complete the record and store the cards
170170

171171
Copy the displayed backup identifier, wallet name, Bitcoin Core version,
172-
master fingerprint, derivation standards, and account number to the wallet
173-
record. Add the approximate
172+
master fingerprint, recovery commitment, derivation standards, and account
173+
number to the wallet record. Add the approximate
174174
creation / earliest-use date. Do not put a descriptor timestamp on a recovery
175175
card; Core's public descriptor export preserves its stored timestamps.
176176

‎docs/user/wallet-verification-record.html‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ <h2>Wallet identity</h2>
3333
<div class="field">Bitcoin Core version:</div>
3434
<div class="field">Approximate creation / earliest-use date:</div>
3535
<div class="field">Master fingerprint:</div>
36+
<div class="field wide">Recovery commitment:</div>
3637
<div class="field">Derivation standards:</div>
3738
<div class="field">Account number:</div>
3839
<div class="field wide">Descriptor or policy archive location:</div>
@@ -56,6 +57,7 @@ <h2>Initial wallet setup</h2>
5657

5758
<h2>Later wallet verification for recovery</h2>
5859
<p><span class="check"></span> Followed the documented Bitcoin Core recovery workflow.</p>
60+
<p><span class="check"></span> Entered the recovery commitment before any recovered keys were imported.</p>
5961
<p><span class="check"></span> Matched the expected master fingerprint.</p>
6062
<p><span class="check"></span> Matched account, complete policy, history, and balance.</p>
6163
<p><span class="check"></span> If available, a trusted person reviewed the wallet setup and recovery plan.</p>
@@ -67,8 +69,9 @@ <h2>Private restoration record</h2>
6769
<div class="field wide">Offline device and destination wallet notes:</div>
6870
</div>
6971
<p class="small">
70-
This record cannot authenticate a replaced backup by itself. Treat it as privacy-sensitive:
71-
it can reveal wallet structure, balances, and transaction history even though it cannot spend.
72+
The recovery commitment binds a recovered single-key seed to this separately stored record.
73+
It does not authenticate a multisig policy, descriptor archive, history, or balance. Treat this
74+
record as privacy-sensitive even though it cannot spend.
7275
</p>
7376
</body>
7477
</html>

‎src/codex32/_bitcoin_core.py‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import hashlib
34
import json
45
import re
56
import shutil
@@ -29,6 +30,7 @@ class BitcoinCoreError(Exception):
2930
_ORIGIN = re.compile(r"\[(?P<fingerprint>[0-9a-f]{8})(?P<path>(?:/[0-9]+[h']?)*)\]")
3031
_PRIVATE_MARKERS = ("xprv", "tprv")
3132
_PURPOSES = (44, 49, 84, 86)
33+
_RECOVERY_COMMITMENT_DOMAIN = b"codex32 recovery commitment\0"
3234

3335

3436
@dataclass(frozen=True)
@@ -126,10 +128,20 @@ def _normalized_descriptor(self, descriptor: str) -> str:
126128
raise BitcoinCoreError("Bitcoin Core did not return the expected public descriptor.")
127129
return normalized
128130

129-
def fingerprint_seed(self, seed: bytes) -> bytes:
130-
"""Return the BIP32 master fingerprint using Bitcoin Core out of process."""
131+
def recovery_identity_seed(self, seed: bytes) -> tuple[bytes, bytes]:
132+
"""Return the BIP32 fingerprint and a SHA-256 commitment to the root xpub."""
131133
xprv = _master_xprv_from_seed(seed, testnet=self.chain != "main")
132134
descriptor = self._normalized_descriptor(f"pkh({xprv})")
135+
if not descriptor.startswith("pkh(") or ")#" not in descriptor:
136+
raise BitcoinCoreError("Bitcoin Core did not return the expected root public descriptor.")
137+
root_xpub, separator, checksum = descriptor[4:].partition(")#")
138+
prefix = "xpub" if self.chain == "main" else "tpub"
139+
if separator != ")#" or not checksum or not root_xpub.startswith(prefix):
140+
raise BitcoinCoreError("Bitcoin Core did not return the expected root public key.")
141+
try:
142+
commitment = hashlib.sha256(_RECOVERY_COMMITMENT_DOMAIN + root_xpub.encode("ascii")).digest()
143+
except UnicodeEncodeError as error:
144+
raise BitcoinCoreError("Bitcoin Core returned an invalid root public key.") from error
133145
addresses = self._rpc("deriveaddresses", stdin=descriptor + "\n")
134146
if not isinstance(addresses, list) or len(addresses) != 1 or not isinstance(addresses[0], str):
135147
raise BitcoinCoreError("Bitcoin Core did not derive the expected master-key address.")
@@ -143,16 +155,26 @@ def fingerprint_seed(self, seed: bytes) -> bytes:
143155
):
144156
raise BitcoinCoreError("Bitcoin Core did not return the expected master-key script.")
145157
try:
146-
return bytes.fromhex(script[6:14])
158+
return bytes.fromhex(script[6:14]), commitment
147159
except ValueError as error:
148160
raise BitcoinCoreError("Bitcoin Core returned an invalid master-key script.") from error
149161

162+
def fingerprint_seed(self, seed: bytes) -> bytes:
163+
"""Return the BIP32 master fingerprint using Bitcoin Core out of process."""
164+
return self.recovery_identity_seed(seed)[0]
165+
150166
def fingerprint(self, secret: MasterSeed) -> bytes:
151167
"""Return the BIP32 master fingerprint for a validated master seed."""
152168
if not isinstance(secret, MasterSeed):
153169
raise TypeError("wallet operations accept only MasterSeed")
154170
return self.fingerprint_seed(secret.seed_bytes)
155171

172+
def recovery_identity(self, secret: MasterSeed) -> tuple[bytes, bytes]:
173+
"""Return public recovery identity for a validated master seed."""
174+
if not isinstance(secret, MasterSeed):
175+
raise TypeError("wallet operations accept only MasterSeed")
176+
return self.recovery_identity_seed(secret.seed_bytes)
177+
156178
def _root_xpub(self, wallet: str) -> str:
157179
result = self._rpc("gethdkeys", wallet=wallet)
158180
if not isinstance(result, list) or len(result) != 1 or not isinstance(result[0], dict):

‎src/codex32_gui/pages.py‎

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ class Record:
9191
wallet: str
9292
version: str
9393
fingerprint: str
94+
commitment: str
9495
account: int
9596

9697

@@ -924,11 +925,13 @@ def _record(
924925
core: BitcoinCore, secret: MasterSeed, name: str, timestamp: Timestamp, passphrase: str = ""
925926
) -> Record:
926927
final = wallet_setup.fill(core, secret, name, passphrase, timestamp=timestamp)
928+
fingerprint, commitment = wallet_setup.identity(core, secret)
927929
return Record(
928930
secret.header.identifier.upper(),
929931
final,
930932
wallet_setup.version_text(core),
931-
wallet_setup.fingerprint(core, secret),
933+
fingerprint,
934+
commitment,
932935
0,
933936
)
934937

@@ -938,38 +941,52 @@ def _restore_identity_page(
938941
core: BitcoinCore,
939942
secret: MasterSeed,
940943
fingerprint: str,
944+
commitment: str,
941945
) -> Adw.NavigationPage:
942-
"""Require the wallet record to match before any recovered key is imported."""
946+
"""Require a separately stored strong commitment before importing recovered keys."""
947+
entered = Adw.EntryRow(title="Recovery commitment from wallet record")
948+
group = Adw.PreferencesGroup()
949+
group.add(entered)
950+
status = _note("")
943951

944952
def continue_restore() -> None:
953+
if not wallet_setup.commitment_matches(commitment, entered.get_text()):
954+
_say(status, "That commitment does not match this recovered wallet. Stop here.", "error")
955+
return
956+
_empty(entered)
945957
_wallets(view, core, secret, 0, restoring=True)
946958

947959
content = _column(
948960
_title(
949961
"Check the wallet before restoring it",
950-
"Compare this master fingerprint with the wallet record you stored separately from the cards.",
962+
"Type the recovery commitment from the wallet record stored separately from the cards.",
951963
),
952964
_rows(
953-
"Recovered wallet identity",
965+
"Diagnostic identity",
954966
(
955967
("Backup identifier", secret.header.identifier.upper()),
956968
("Master fingerprint", fingerprint),
957969
),
958970
),
971+
group,
972+
status,
959973
_note(
960-
"If the fingerprint does not match your wallet record, stop. Bitcoin Core has not been changed.",
974+
"The expected commitment is deliberately not shown here. If your record has no recovery "
975+
"commitment, stop; do not substitute the master fingerprint. Bitcoin Core has not been changed.",
961976
"warning",
962977
),
963978
)
964-
return _page(
979+
page = _page(
965980
"Verify wallet",
966981
content,
967982
actions=_actions(
968983
_button("Stop", lambda: view.replace([home(view)])),
969-
_button("Matches my record", continue_restore, style="suggested-action"),
984+
_button("Verify and continue", continue_restore, style="suggested-action"),
970985
),
971986
can_pop=False,
972987
)
988+
_forget_when_gone(view, page, lambda: _empty(entered))
989+
return page
973990

974991

975992
def _verify_restore(view: Adw.NavigationView, core: BitcoinCore, secret: MasterSeed) -> None:
@@ -978,11 +995,11 @@ def _verify_restore(view: Adw.NavigationView, core: BitcoinCore, secret: MasterS
978995
work.run(
979996
view,
980997
page,
981-
lambda: wallet_setup.fingerprint(core, secret),
998+
lambda: wallet_setup.identity(core, secret),
982999
_then(
9831000
view,
9841001
page,
985-
lambda fingerprint: _restore_identity_page(view, core, secret, fingerprint),
1002+
lambda identity: _restore_identity_page(view, core, secret, *identity),
9861003
CARDS_SAFE,
9871004
),
9881005
)
@@ -1026,6 +1043,7 @@ def _finished_page(view: Adw.NavigationView, record: Record, restoring: bool = F
10261043
("Bitcoin Core version", record.version),
10271044
*dated,
10281045
("Master fingerprint", record.fingerprint),
1046+
("Recovery commitment", record.commitment),
10291047
("Derivation standards", "BIP 44, 49, 84 and 86"),
10301048
("Account number", str(record.account)),
10311049
),

‎src/codex32_gui/wallet_setup.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,14 @@
3232
"BitcoinCoreError",
3333
"Offer",
3434
"Wallet",
35+
"commitment_matches",
3536
"connect",
3637
"create",
3738
"eligible",
3839
"fill",
3940
"fingerprint",
4041
"fingerprint_provider",
42+
"identity",
4143
"initialize",
4244
"network",
4345
"relock",
@@ -140,6 +142,20 @@ def fingerprint(core: BitcoinCore, secret: MasterSeed) -> str:
140142
return core.fingerprint(secret).hex()
141143

142144

145+
def identity(core: BitcoinCore, secret: MasterSeed) -> tuple[str, str]:
146+
"""Return the short fingerprint and strong public recovery commitment."""
147+
fingerprint_bytes, commitment = core.recovery_identity(secret)
148+
text = commitment.hex().upper()
149+
return fingerprint_bytes.hex(), " ".join(text[start : start + 4] for start in range(0, len(text), 4))
150+
151+
152+
def commitment_matches(expected: str, entered: str) -> bool:
153+
"""Compare a copied recovery commitment, ignoring only whitespace and case."""
154+
expected_text = "".join(expected.split()).upper()
155+
entered_text = "".join(entered.split()).upper()
156+
return len(entered_text) == 64 and entered_text == expected_text
157+
158+
143159
def fingerprint_provider(core: BitcoinCore) -> Callable[[bytes], bytes]:
144160
"""Hand the library the same out-of-process derivation for a raw seed."""
145161
return core.fingerprint_seed

‎tests/test_bitcoin_core.py‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -425,7 +425,7 @@ def fail(
425425
assert any(arguments == ("walletlock",) for arguments, _wallet, _stdin in rpc.calls)
426426

427427

428-
def test_fingerprint_uses_stateless_core_address_derivation(monkeypatch: pytest.MonkeyPatch) -> None:
428+
def test_recovery_identity_uses_stateless_public_derivation(monkeypatch: pytest.MonkeyPatch) -> None:
429429
calls: list[tuple[tuple[str, ...], str | None]] = []
430430

431431
def rpc(
@@ -446,14 +446,44 @@ def rpc(
446446

447447
monkeypatch.setattr(BitcoinCore, "_rpc", rpc)
448448

449-
assert BitcoinCore("bitcoin-cli", "main", 320000).fingerprint(_SEED) == bytes.fromhex("3f3521a6")
449+
identity = BitcoinCore("bitcoin-cli", "main", 320000).recovery_identity(_SEED)
450+
assert identity == (
451+
bytes.fromhex("3f3521a6"),
452+
bytes.fromhex("db007d748326b0be6c27e2dada55a4116cc6c286cd76d11671b2f6af8fb8ae9f"),
453+
)
450454
assert calls == [
451455
(("getdescriptorinfo",), None),
452456
(("deriveaddresses",), None),
453457
(("validateaddress", "1synthetic"), None),
454458
]
455459

456460

461+
def test_fingerprint_keeps_the_short_legacy_view(monkeypatch: pytest.MonkeyPatch) -> None:
462+
monkeypatch.setattr(
463+
BitcoinCore,
464+
"recovery_identity_seed",
465+
lambda _self, _seed: (bytes.fromhex("3f3521a6"), bytes(32)),
466+
)
467+
assert BitcoinCore("bitcoin-cli", "main", 320000).fingerprint(_SEED) == bytes.fromhex("3f3521a6")
468+
469+
470+
@pytest.mark.parametrize(
471+
"descriptor",
472+
(
473+
"wpkh(xpub-root)#checksum",
474+
"pkh(tpub-root)#checksum",
475+
"pkh(not-a-public-key)#checksum",
476+
"pkh(xpub-root)",
477+
),
478+
)
479+
def test_recovery_identity_rejects_unexpected_root_public_descriptor(
480+
descriptor: str, monkeypatch: pytest.MonkeyPatch
481+
) -> None:
482+
monkeypatch.setattr(BitcoinCore, "_normalized_descriptor", lambda _self, _descriptor: descriptor)
483+
with pytest.raises(BitcoinCoreError, match="root public"):
484+
BitcoinCore("bitcoin-cli", "main", 320000).recovery_identity(_SEED)
485+
486+
457487
@pytest.mark.parametrize("change", ("missing", "extra"))
458488
def test_exact_public_descriptor_verification_rejects_missing_or_extra_records(
459489
change: str,

0 commit comments

Comments
 (0)