Skip to content

Commit befead5

Browse files
committed
create: Stretch typed keystrokes with scrypt
People type far fewer unpredictable bits than they think, so when both generators fail and Core's wallet file leaks, raw typed keys can be guessed quickly. Each draw now runs the typed text through scrypt at OWASP's minimum (N=2^17, r=8, p=1, 128 MiB, maxmem capped at 256 MiB) before hashing it in, salted with a domain tag and the draw's first xprv and OS bytes. It adds no entropy, but every guess now costs one scrypt. Draws without typed keys skip scrypt and are unchanged. A 3-of-5 creation makes 9 draws, so about 10 seconds in all. Claude-Session: https://claude.ai/code/session_01T233rKgZqE5wzDm3EVTHL1
1 parent fc64ea2 commit befead5

4 files changed

Lines changed: 36 additions & 11 deletions

File tree

‎docs/developer/api.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -662,9 +662,11 @@ guesses of a share. The OS bytes stop a leaked file's xpubs from capping each
662662
key at about 128-bit security, Bitcoin's own ECDLP bound, so a working OS
663663
generator alone keeps full strength and a broken one leaves Core's. If the OS
664664
generator is broken and the file leaks, the passphrase is weak too, and only
665-
RAM keeps the file safe, unless `--keystrokes` was used: the typed text is
666-
hashed in last and never reaches the wallet, so that case then rests on how
667-
unpredictable the typing was. Each draw removes its wallet even when it fails
665+
RAM keeps the file safe, unless `--keystrokes` was used: the typed text never
666+
reaches the wallet and is hashed in last, after scrypt (N=2^17, r=8, p=1,
667+
128 MiB, about a second per draw) salted with the draw's first xprv and OS
668+
bytes. That case then rests on how unpredictable the typing was, and each
669+
guess at it costs one scrypt. Each draw removes its wallet even when it fails
668670
or is interrupted by Ctrl-C, SIGHUP, or SIGTERM, so callers have nothing to
669671
close. If the wallet can't be removed, creation stops before the next card.
670672
These extra calls are `createwallet`, `walletpassphrase`, `gethdkeys`, and

‎docs/user/guide.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ easier.
126126
Add `--keystrokes` to type some random keys before the cards are made. They
127127
are not shown, are mixed into every card's randomness, and are never saved, so
128128
they help only if this computer's random generator is broken and Core's
129-
temporary wallet file leaks.
129+
temporary wallet file leaks. Each card then takes about a second longer.
130130

131131
Already have a complete codex32 `ms` secret? Run `ms32 create --existing` to
132132
write and confirm its recovery card and initialize a Bitcoin Core wallet.

‎src/codex32/_bitcoin_core.py‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -468,7 +468,7 @@ def __call__(self, length: int) -> bytes:
468468
def _draw(self, length: int) -> bytes:
469469
wallet = self._wallet()
470470
self._core._rpc("walletpassphrase", wallet=wallet, stdin=f"{self._passphrase}\n60\n")
471-
data = b""
471+
data = stretched = b""
472472
try:
473473
while len(data) < length:
474474
added = self._core._rpc("addhdkey", wallet=wallet)
@@ -483,7 +483,15 @@ def _draw(self, length: int) -> bytes:
483483
# Hashing keeps the plaintext xpub in the wallet file from checking guesses of a share. The
484484
# OS bytes keep that xpub from capping the key near 128 bits while the OS generator works,
485485
# and typed keys, which never reach the wallet, cover a broken OS generator and a leaked file.
486-
data += hashlib.sha256(xprvs[0].encode() + secrets.token_bytes(32) + self._typed).digest()
486+
key, os_bytes = xprvs[0].encode(), secrets.token_bytes(32)
487+
if self._typed and not stretched:
488+
# Typed keys hold fewer bits than they seem, so each guess costs OWASP's minimum scrypt
489+
# (128 MiB, about a second), salted once per draw.
490+
salt = b"codex32 keystrokes\0" + key + os_bytes
491+
stretched = hashlib.scrypt(
492+
self._typed, salt=salt, n=2**17, r=8, p=1, maxmem=2**28, dklen=32
493+
)
494+
data += hashlib.sha256(key + os_bytes + stretched).digest()
487495
finally:
488496
self._core._rpc("walletlock", wallet=wallet)
489497
return data[:length]

‎tests/test_bitcoin_core.py‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -903,25 +903,40 @@ def __call__(self, *arguments: str, wallet: str | None = None, stdin: str | None
903903
return keys if method == "gethdkeys" else None
904904

905905

906+
@pytest.mark.parametrize("typed", ("", "qwer tyui"))
906907
def test_core_entropy_hashes_fresh_keys_from_a_wallet_removed_after_each_draw(
907-
monkeypatch: pytest.MonkeyPatch,
908+
monkeypatch: pytest.MonkeyPatch, typed: str
908909
) -> None:
909-
rpc, told = _EntropyRPC(), list[str]()
910+
rpc, told, stretched = _EntropyRPC(), list[str](), list[bytes]()
910911
monkeypatch.setattr(BitcoinCore, "_rpc", rpc)
911-
entropy = CoreEntropy(BitcoinCore("bitcoin-cli", "main", 320000), told.append, typed="qwer tyui")
912+
entropy = CoreEntropy(BitcoinCore("bitcoin-cli", "main", 320000), told.append, typed=typed)
912913

913914
drawn = list[bytes]() # every OS draw stays random; macOS volume names use them too
914915
monkeypatch.setattr(
915916
"codex32._bitcoin_core.secrets.token_bytes",
916917
lambda length: drawn.append(os.urandom(length)) or drawn[-1],
917918
)
919+
scrypt = hashlib.scrypt
920+
monkeypatch.setattr(
921+
hashlib,
922+
"scrypt",
923+
lambda *args, **options: stretched.append(scrypt(*args, **options)) or stretched[-1],
924+
)
918925
data = entropy(40), entropy(4)
919926
mixed = [value for value in drawn if len(value) == 32]
927+
928+
def stretch(key: bytes, os_bytes: bytes) -> bytes:
929+
salt = b"codex32 keystrokes\0" + key + os_bytes
930+
return scrypt(typed.encode(), salt=salt, n=2**17, r=8, p=1, maxmem=2**28, dklen=32) if typed else b""
931+
932+
# Typed keys are stretched once per draw, salted by its first key; without them nothing is stretched.
933+
first, last = stretch(b"xprv1", mixed[0]), stretch(b"xprv3", mixed[2])
920934
digests = [
921-
hashlib.sha256(f"xprv{number}".encode() + os_bytes + b"qwer tyui").digest()
922-
for number, os_bytes in zip((1, 2, 3), mixed)
935+
hashlib.sha256(f"xprv{number}".encode() + os_bytes + extra).digest()
936+
for number, os_bytes, extra in zip((1, 2, 3), mixed, (first, first, last))
923937
]
924938
assert len(mixed) == 3 and data == (digests[0] + digests[1][:8], digests[2][:4])
939+
assert stretched == ([first, last] if typed else [])
925940
draw = ["createwallet", "walletpassphrase", "addhdkey", "gethdkeys"]
926941
methods = [arguments[arguments[0] == "-named"] for arguments, _wallet, _stdin in rpc.calls]
927942
assert methods == [

0 commit comments

Comments
 (0)