From 82287fe9c51904bf3a072ac6d20f2863d325350d Mon Sep 17 00:00:00 2001 From: Ben Westgate Date: Wed, 4 Nov 2026 13:04:18 +0000 Subject: [PATCH] wallet: Let callers name the chain and wallet BitcoinCore.connect and initialize choose a network and a wallet by prompting in text. A frontend that already asked the operator had to answer those prompts by parsing them. Take the choice directly: connect(chain=...) uses that network or says it is gone, and raises ChainChoice listing the networks when several answer and nothing can prompt. initialize(wallet=...) uses that wallet without prompting and refuses one that is no longer empty. Claude-Session: https://claude.ai/code/session_018HrKoywz6PT9c91jvKou7Q --- src/codex32/_bitcoin_core.py | 32 ++++++++++++++++++------ tests/test_bitcoin_core.py | 47 ++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 7 deletions(-) diff --git a/src/codex32/_bitcoin_core.py b/src/codex32/_bitcoin_core.py index 84a73e1..b4867c5 100644 --- a/src/codex32/_bitcoin_core.py +++ b/src/codex32/_bitcoin_core.py @@ -22,6 +22,14 @@ class FingerprintMismatch(BitcoinCoreError): """The recovered seed is not the wallet the operator's record describes.""" +class ChainChoice(BitcoinCoreError): + """Several networks answer and nothing can prompt; pass one of `chains` to `connect`.""" + + def __init__(self, chains: tuple[str, ...]) -> None: + super().__init__("More than one local Bitcoin Core network is running.") + self.chains = chains + + _CHAINS = ( ("main", "mainnet"), ("test", "testnet3"), @@ -81,6 +89,8 @@ def connect( cls, ask: Callable[[str], str] | None = None, tell: Callable[[str], None] | None = None, + *, + chain: str | None = None, ) -> BitcoinCore: executable = shutil.which("bitcoin-cli") if executable is None: @@ -89,8 +99,8 @@ def connect( "enabled. An unsynced regtest or signet node is enough for practice." ) choices: list[BitcoinCore] = [] - for chain, _label in _CHAINS: - client = cls(executable, chain, 0) + for candidate, _label in _CHAINS: + client = cls(executable, candidate, 0) try: network = client._rpc("getnetworkinfo", timeout=5) blockchain = client._rpc("getblockchaininfo", timeout=5) @@ -98,18 +108,20 @@ def connect( continue version = network.get("version") if isinstance(network, dict) else None reported = blockchain.get("chain") if isinstance(blockchain, dict) else None - if isinstance(version, bool) or not isinstance(version, int) or reported != chain: + if isinstance(version, bool) or not isinstance(version, int) or reported != candidate: continue if version >= 320000: - choices.append(cls(executable, chain, version)) + choices.append(cls(executable, candidate, version)) if not choices: raise BitcoinCoreError( "No local Bitcoin Core 32 or newer RPC server found.\nStart Bitcoin Core " "with local RPC enabled.\nFor signet practice: bitcoin-qt -signet -server" ) + if chain is not None and not (choices := [choice for choice in choices if choice.chain == chain]): + raise BitcoinCoreError("Bitcoin Core is no longer running on that network.") if len(choices) > 1: if ask is None or tell is None: - raise BitcoinCoreError("More than one local Bitcoin Core network is running.") + raise ChainChoice(tuple(choice.chain for choice in choices)) tell("Local Bitcoin Core networks:") for number, choice in enumerate(choices, 1): tell(f" {number}. {dict(_CHAINS)[choice.chain]}") @@ -354,8 +366,12 @@ def initialize( expected_fingerprint: bytes | None, account: int = 0, timestamp: int | Literal["now"] = "now", + wallet: str | None = None, ) -> str: - """Validate input and identity before selecting or changing a wallet.""" + """Validate input and identity before selecting or changing a wallet. + + A named `wallet` is used without prompting, and must still be an empty one. + """ if not isinstance(secret, MasterSeed): raise TypeError("wallet operations accept only MasterSeed") if type(account) is not int or account != 0: @@ -364,8 +380,10 @@ def initialize( raise ValueError("timestamp must be a nonnegative integer or 'now'") self.verify_identity(secret, expected_fingerprint) while True: - name = self._select(ask, tell) + name = self._select(ask, tell) if wallet is None else wallet state = self._target(name) + if state is None and wallet is not None: + raise BitcoinCoreError("That wallet is no longer an empty one codex32 can fill.") if state is None: tell("That wallet is no longer eligible. Choose again.") continue diff --git a/tests/test_bitcoin_core.py b/tests/test_bitcoin_core.py index 5b80189..302d6f2 100644 --- a/tests/test_bitcoin_core.py +++ b/tests/test_bitcoin_core.py @@ -12,6 +12,7 @@ from codex32._bitcoin_core import ( BitcoinCore, BitcoinCoreError, + ChainChoice, FingerprintMismatch, identifier_note, identifier_origin, @@ -156,6 +157,27 @@ def run(command: list[str], **_options: object) -> subprocess.CompletedProcess[s ] +def test_preflight_takes_a_chosen_chain_or_lists_them_without_prompting( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def run(command: list[str], **_options: object) -> subprocess.CompletedProcess[str]: + chain = command[1].removeprefix("-chain=") + if chain not in ("main", "signet"): + return subprocess.CompletedProcess(command, 1, "", "") + response = {"version": 320000} if command[-1] == "getnetworkinfo" else {"chain": chain} + return subprocess.CompletedProcess(command, 0, json.dumps(response), "") + + monkeypatch.setattr("codex32._bitcoin_core.shutil.which", lambda _name: "/reviewed/bitcoin-cli") + monkeypatch.setattr(subprocess, "run", run) + + assert BitcoinCore.connect(chain="signet").chain == "signet" + with pytest.raises(ChainChoice) as offered: + BitcoinCore.connect() + assert offered.value.chains == ("main", "signet") + with pytest.raises(BitcoinCoreError, match="no longer running on that network"): + BitcoinCore.connect(chain="regtest") + + def test_preflight_rejection_is_helpful_without_echoing_core_output( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -743,6 +765,31 @@ def test_unencrypted_wallet_imports_without_a_lock_call(monkeypatch: pytest.Monk assert not any(arguments == ("walletlock",) for arguments, _wallet, _stdin in rpc.calls) +def test_a_named_wallet_is_used_without_prompting(monkeypatch: pytest.MonkeyPatch) -> None: + rpc = _ImportRPC(encrypted=False, locked=False) + monkeypatch.setattr( + BitcoinCore, + "_rpc", + lambda client, *args, wallet=None, stdin=None, timeout=120: rpc( + client, *args, wallet=wallet, stdin=stdin, timeout=timeout + ), + ) + + def never(_prompt: str) -> str: + raise AssertionError("a named wallet needs no prompt") + + client = BitcoinCore("bitcoin-cli", "main", 300000) + name = client.initialize( + _SEED, never, lambda _message: None, expected_fingerprint=_FINGERPRINT, wallet="signer" + ) + assert name == "signer" + monkeypatch.setattr(BitcoinCore, "_target", lambda _client, _name: None) + with pytest.raises(BitcoinCoreError, match="no longer an empty one"): + client.initialize( + _SEED, never, lambda _message: None, expected_fingerprint=_FINGERPRINT, wallet="gone" + ) + + def test_immediate_revalidation_stops_before_private_import_and_relocks( monkeypatch: pytest.MonkeyPatch, ) -> None: