Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 25 additions & 7 deletions src/codex32/_bitcoin_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -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:
Expand All @@ -89,27 +99,29 @@ 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)
except BitcoinCoreError:
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]}")
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand Down
47 changes: 47 additions & 0 deletions tests/test_bitcoin_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from codex32._bitcoin_core import (
BitcoinCore,
BitcoinCoreError,
ChainChoice,
FingerprintMismatch,
identifier_note,
identifier_origin,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
Loading