Skip to content

Commit 06ff2d3

Browse files
committed
create: Draw randomness only from Bitcoin Core
ms32 create took seed, share, identifier and index randomness from Python secrets, which is os.urandom unchanged. Bitcoin Core's GetStrongRandBytes also mixes in RDRAND/RDSEED where available, timestamps and accumulated state, so it survives a weak OS generator. generation.py now draws every byte by calling a caller-supplied entropy(length); CreationCeremony requires it. The CLI passes CoreEntropy: a blank temporary wallet in RAM (/dev/shm on Linux, an hdiutil RAM disk on macOS, else the temp folder with a warning), encrypted from birth with a 256-bit passphrase sent only on stdin. Each draw unlocks it, adds one addhdkey key per 32 bytes, takes the SHA-256 of the xprv, and relocks. Hashing keeps the xpub, stored unencrypted, from checking guesses of a share. Creation unloads and deletes the wallet on every exit, including SIGHUP and SIGTERM. Draws stay sequential, each after the previous card is confirmed. There is no fallback: if Core cannot supply randomness, create stops. Security: changes share generation; needs review. The passphrase comes from secrets. Where no RAM folder exists the encrypted wallet is briefly on disk. Validation: ruff, mypy, 914 tests with and without -O, and tools/bitcoin_core_regtest.py on Bitcoin Core 32.0rc3. Claude-Session: https://claude.ai/code/session_01T233rKgZqE5wzDm3EVTHL1
1 parent e418548 commit 06ff2d3

13 files changed

Lines changed: 408 additions & 87 deletions

File tree

‎docs/developer/api.md‎

Lines changed: 35 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ generic parse-length failure.
3737
| checksum and CRC arithmetic | `checksums.py` | official vectors, `test_crc.py` |
3838
| optional application rules and S types | `profiles/ms32.py`, `cl32.py`, `bip39.py` | profile and BIP39 tests |
3939
| immutable base artifacts and interpolation | `bip93.py` | BIP93 vectors, `test_sharing.py` |
40-
| entropy, masks, identifiers, output indices | `generation.py` | `test_generation.py` |
40+
| entropy, masks, identifiers, output indices | `generation.py`, `CoreEntropy` | `test_generation.py`, `test_bitcoin_core.py` |
4141
| shared GF(32) arithmetic | `gf32.py` | sharing vectors and correction corpus |
4242
| fixed BCH and worksheet correction | `correction.py` | `test_correction_bch.py` |
4343
| structural alignment and admission | `indel.py` | `test_correction_indel.py`, `test_correction_capture.py` |
@@ -67,7 +67,9 @@ generic parse-length failure.
6767
`.text` attribute.
6868
- Sharing interpolates payload and checksum together, explicitly constructs the
6969
target header, and reparses the result.
70-
- `generation.py` is the only entropy owner; it generates and shares only `ms`.
70+
- `generation.py` is the only entropy owner; it draws every byte from its
71+
caller's `entropy` source (Bitcoin Core in the CLI) and generates and shares
72+
only `ms`.
7173
- Correction never edits the HRP or separator and reparses every candidate.
7274
- `_bip32.py` stops at HMAC-SHA512 root derivation, scalar validity, and root
7375
xprv/tprv Base58Check serialization. It performs no child derivation or
@@ -152,8 +154,10 @@ accepts only `ms` artifacts.
152154

153155
## Secret generation
154156

155-
`generation.py` is the only module that draws entropy. It generates and
156-
splits BIP93 master seeds only.
157+
`generation.py` is the only module that draws entropy, always by calling the
158+
caller's `entropy(length)`, which must return exactly `length` bytes. The CLI
159+
passes [Bitcoin Core's](#bitcoin-core-randomness). It generates and splits
160+
BIP93 master seeds only.
157161

158162
Fresh unshared seeds default to 16 bytes and use the first 20 bits of their
159163
BIP32 fingerprint as public identifier metadata. Fresh shared sets use four
@@ -169,17 +173,18 @@ boundary; there is no legacy decoder.
169173
The one-shot function creates only unshared secrets:
170174

171175
```python
172-
generate_master_seed(seed_bytes=None, *, byte_length=None, identifier=None, fingerprint=None)
176+
generate_master_seed(seed_bytes=None, *, byte_length=None, identifier=None, fingerprint=None, entropy=None)
173177
```
174178

175179
A fresh seed with no `identifier` needs `fingerprint`: a callable that takes
176180
the seed bytes and returns their four-byte BIP32 master fingerprint. This
177181
package has no secp256k1 arithmetic, so the CLI asks Bitcoin Core. Without
178-
either argument, fresh generation raises `ValueError`.
182+
either argument, fresh generation raises `ValueError`, as does any draw without
183+
`entropy`.
179184

180185
Shared creation uses `CreationCeremony.master_seed(...)` or
181-
`CreationCeremony.from_secret(...)`. Exactly one of `share_count` and `indices`
182-
is required. `next_share()` returns one pending share, `confirm(text)` must
186+
`CreationCeremony.from_secret(...)`; both require `entropy`. Exactly one of
187+
`share_count` and `indices` is required. `next_share()` returns one pending share, `confirm(text)` must
183188
accept its independently re-entered string, and `finish()` returns the secret
184189
only after every requested share is confirmed. There is no public one-shot
185190
sharing or `split_secret` function. Fresh and existing Bitcoin CLI creation
@@ -206,10 +211,10 @@ The ceremony follows the two BIP93 constructions:
206211
- a fresh set draws `k` independent complete u5 masks;
207212
- an existing S uses S plus `k-1` independent complete u5 masks.
208213

209-
Each direct share uses a separate `secrets.token_bytes` request and cannot be
210-
followed by another draw until its string is confirmed. The pause gives the OS an
211-
opportunity to mix fresh noise; Python cannot guarantee that new physical
212-
entropy arrives between calls. User input is never treated as entropy. Each
214+
Each direct share uses a separate `entropy` request and cannot be followed by
215+
another draw until its string is confirmed. The pause gives the source an
216+
opportunity to mix fresh noise; nothing guarantees that new physical entropy
217+
arrives between calls. User input is never treated as entropy. Each
213218
byte is mapped with `value & 31`, which maps exactly eight byte values to each
214219
u5 value.
215220

@@ -258,9 +263,9 @@ remain fixed. That padding rule is not BIP93 validity: parsed S strings may use
258263
any application-valid discarded bits, which re-sharing preserves exactly. CRC
259264
never applies to shares.
260265

261-
Explicit output indices preserve caller order. A share count uses
262-
`SystemRandom.sample` over the 31 ordinary indices and preserves sample order.
263-
There is no entropy injection, sorting, caller-supplied partial-basis
266+
Explicit output indices preserve caller order. A share count picks
267+
from the 31 ordinary indices by rejection sampling of `entropy` bytes, in draw
268+
order. There is no sorting, caller-supplied partial-basis
264269
completion, or BIP39 generation. Ceremonies reject copying and serialization;
265270
the CLI does not resume an interrupted ceremony.
266271

@@ -641,6 +646,21 @@ The Core calls are fixed: `getnetworkinfo`, `getblockchaininfo`, `listwallets`,
641646
Bitcoin Core alone creates wallets, selects encryption, handles
642647
passphrases, stores keys, and provides normal wallet behavior.
643648

649+
### Bitcoin Core randomness
650+
651+
`ms32 create` draws every random byte from `CoreEntropy`, so it stops if Core
652+
cannot supply them. Core's `GetStrongRandBytes` mixes the OS generator with
653+
RDRAND/RDSEED where available, timestamps, and accumulated state. The first
654+
draw creates a blank temporary wallet in RAM: `/dev/shm` on Linux, a RAM disk
655+
from `hdiutil` on macOS, otherwise the temp folder on disk with a warning. It
656+
is encrypted from birth with a 256-bit `secrets` passphrase sent only on stdin.
657+
Each draw unlocks it, runs `addhdkey` once per 32 bytes, takes the SHA-256 of
658+
the xprv from `gethdkeys private=true`, and relocks. Hashing stops the xpub,
659+
which the wallet file stores unencrypted, from checking guesses of a share.
660+
Creation unloads and deletes the wallet on success, error, Ctrl-C, SIGHUP, or
661+
SIGTERM. These extra calls are `createwallet`, `walletpassphrase`, `gethdkeys`,
662+
and `unloadwallet`.
663+
644664
The wallet CLI is one leaf command:
645665

646666
```text

‎docs/security/invariants.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,9 @@ and evidence.
88
HRPs remain opaque and never gain invented application semantics.
99
2. APIs accept only immutable validated artifacts. Outputs are reparsed;
1010
recovery and derivation reject sets with mismatched normalized HRPs or shapes.
11-
3. Shared creation uses a separate OS-CSPRNG call for each random initial share,
12-
gated by confirmation. Input cannot replace entropy or the original secret.
11+
3. Shared creation uses a separate Bitcoin Core draw for each random initial
12+
share, gated by confirmation, with no fallback. Input cannot replace entropy
13+
or the original secret.
1314
4. Wallet setup uses the original ceremony result or a validated recovered seed.
1415
Restore authenticates the recovered seed before any wallet is listed,
1516
unlocked, or imported into: normally with the master fingerprint typed from
@@ -36,8 +37,9 @@ and evidence.
3637
operator confirms an eligible descriptor wallet by exact name.
3738
8. Wallet state is revalidated before handing Core the master key. Core must
3839
accept that key and create every requested account-0 wallet descriptor.
39-
9. codex32 has no passphrase channel. An unlocked encrypted signer is relocked
40-
and verified on every exit path.
40+
9. codex32 never handles the operator's wallet passphrase. An unlocked encrypted
41+
signer is relocked and verified on every exit path; the temporary randomness
42+
wallet is relocked after each draw.
4143
10. External text, Core output, public wallet data, and PSBTs are untrusted.
4244
11. Only Bitcoin Core descriptor wallets sign with codex32-derived keys.
4345
Sensitive operations use only codex32 or Core on malware-free computers

‎docs/security/model.md‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ fingerprints, and wallet history cannot spend funds but remain privacy-sensitive
2626
| Package API | Recovery, derivation, sharing, and wallet operations accept validated artifacts, not unchecked text. |
2727
| Python process | Secret objects remain in process memory; normal output must not reveal them unintentionally. |
2828
| Operator and paper | The operator controls transcription, physical recovery cards, wallet records, and acceptance of correction suggestions. |
29-
| Entropy and root keys | The operating-system cryptographically secure random-number generator (OS-CSPRNG) and Python stdlib HMAC/SHA-512 primitives are trusted. codex32 performs only BIP32 root validation and root xprv/tprv serialization in process. |
29+
| Entropy and root keys | Bitcoin Core's random generator, which mixes in the operating-system cryptographically secure random-number generator (OS-CSPRNG), supplies every random byte of `ms32 create`. Python stdlib HMAC/SHA-512 primitives are trusted. codex32 performs only BIP32 root validation and root xprv/tprv serialization in process. |
3030
| Bitcoin Core | The selected `bitcoin-cli`, its configuration, the selected local Core instance, and the destination computer are trusted for fingerprints, hardened/public-key derivation, and wallet initialization. |
3131

3232
## Operator assumptions
@@ -64,8 +64,11 @@ The operator must:
6464
implementation. Elliptic-curve public-key derivation used for fingerprints,
6565
xpubs, and public descriptors is delegated to the separately running Bitcoin
6666
Core process.
67-
- Separate OS-CSPRNG calls provide opportunities to mix fresh noise but cannot
67+
- Separate Core draws provide opportunities to mix fresh noise but cannot
6868
guarantee new physical entropy between calls.
69+
- The temporary randomness wallet's passphrase comes from the OS-CSPRNG. Where
70+
no RAM folder exists, as on Windows, the encrypted wallet briefly sits on
71+
disk. Swap, RAM disks and tmpfs can page memory, including secrets, to disk.
6972
- A checksum, generation-padding hint, fingerprint, or correction candidate
7073
does not authenticate a backup or prove the operator's intent.
7174
- Creation feedback identifies correct groups but does not prove the recovery card was corrected.
@@ -116,7 +119,7 @@ complete explicit `ms1` string.
116119
## Creation, sharing, and recovery controls
117120

118121
Fresh shared creation generates *k* random initial shares. Each uses a separate
119-
full-payload OS-CSPRNG request. The current share string must be re-entered
122+
full-payload request to Bitcoin Core. The current share string must be re-entered
120123
exactly, ignoring case and whitespace, before the next request. Confirmation
121124
text is never reparsed as the source secret and contributes no entropy. Existing
122125
complete Bitcoin master seeds are confirmed unchanged and initialize the wallet
@@ -132,8 +135,8 @@ Progressive group-level correctness feedback is explicitly accepted and does not
132135

133136
Confirmation shows that the operator can produce the correct recovery string during setup. It cannot prove that the physical backup was corrected rather than reconstructed using confirmation feedback.
134137

135-
The API accepts neither caller-provided entropy nor padding values, partial
136-
bases, or resumable ceremony state. Fresh creation rejects final-share
138+
The API draws randomness only from its caller's `entropy` source and accepts no
139+
padding values, partial bases, or resumable ceremony state. Fresh creation rejects final-share
137140
candidates whose generation padding is invalid. Master-seed creation also
138141
rejects candidates that cannot form a valid BIP32 root. This check uses only
139142
stdlib HMAC-SHA512 plus the secp256k1 scalar-order bound; it performs no point
@@ -234,10 +237,10 @@ signing setup belong to Bitcoin Core's maintained v32 workflow.
234237
|---|---|
235238
| 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. |
236239
| Recovery identity | `ms32 wallet` and `ms32 create --existing` authenticate 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 `ms32 create` has no pre-existing wallet to authenticate: 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. |
237-
| 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. |
240+
| Process boundary | codex32 invokes the reviewed `bitcoin-cli` from `PATH` as a child without a shell, direct RPC socket, or wallet database; its only wallet creation is the temporary randomness wallet. Every call uses loopback and the selected chain. |
238241
| 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. |
239242
| Seed source | The original ceremony result or validated recovered master seed supplies a root xprv for Core's reported chain. Core v32 creates BIP44, BIP49, BIP84, and BIP86 account-0 descriptors from that key. |
240-
| Secret channel | The master xprv is sent only through the child's standard input. A timestamped rescan obtains one private descriptor from Core's captured stdout and returns it through stdin; neither value is printed or passed in arguments or diagnostics. codex32 has no passphrase channel and suppresses raw Core errors. |
243+
| Secret channel | The master xprv is sent only through the child's standard input. A timestamped rescan obtains one private descriptor from Core's captured stdout and returns it through stdin; neither value is printed or passed in arguments or diagnostics. codex32 never handles the operator's wallet passphrase and suppresses raw Core errors. |
241244
| Revalidation | Every destination property is checked again immediately before adding the key. `addhdkey` must accept it and `createwalletdescriptor` must return two public descriptors for each requested address type. Numeric recovery timestamps trigger Core's time-based rescan (genesis for `0`), with no guessed block height. Core is trusted to derive and store the wallet policy. |
242245
| Relocking | Once Core reports an encrypted private-key wallet unlocked, a `finally`-protected obligation requests `walletlock` and verifies the locked state after success, failure, state change, or interruption. |
243246

‎docs/user/guide.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,11 @@ Before running `create` for a real wallet, have your blank cards, a pen, and
7373
wallet record ready, and choose separate trusted places for shared cards.
7474
If you want to try the process first, use the signet practice setup below.
7575

76-
Run Bitcoin Core before starting. If practical, disconnect the computer from
77-
external networks while recovery text is on screen. codex32 talks only to the
76+
Run Bitcoin Core before starting: `create` takes all its randomness from Core.
77+
While you make cards, Core holds a temporary encrypted wallet in RAM (macOS
78+
shows a small `codex32-` disk); it is deleted before wallet setup. If
79+
practical, disconnect the computer from external networks while recovery text
80+
is on screen. codex32 talks only to the
7881
local Core instance at `127.0.0.1` during setup.
7982

8083
For graphical practice on signet, start Bitcoin-Qt with:
@@ -156,7 +159,7 @@ the selected encrypted wallet is locked, open **Window > Console** in
156159
Bitcoin-Qt, select the named wallet, and enter
157160
`walletpassphrase "YOUR PASSPHRASE" 5`. codex32 waits and continues
158161
automatically. It imports account 0, verifies the public descriptors Core
159-
accepted, and relocks the wallet. It does not create wallets or choose
162+
accepted, and relocks the wallet. It does not create your wallet or choose its
160163
encryption.
161164

162165
You are done with this step when the terminal says:

0 commit comments

Comments
 (0)