diff --git a/src/codex32/_bitcoin_core.py b/src/codex32/_bitcoin_core.py index b2689ea5..b1eae17c 100644 --- a/src/codex32/_bitcoin_core.py +++ b/src/codex32/_bitcoin_core.py @@ -449,12 +449,15 @@ def initialize( continue # Checked last, after any wait above: a pruning node keeps pruning while it waits. self.check_history(timestamp) + # Core's "now" is its tip's time: the genesis block's on an offline signer that never + # synced, and watch-only exports carry it. A new wallet takes this computer's clock, + # a day early like a record's date, so a fast clock cannot skip its first payments. records = core_descriptors( secret, account=account, testnet=self.chain != "main", private=True, - timestamp=timestamp, + timestamp=max(0, int(time.time()) - 86400) if timestamp == "now" else timestamp, ) imported = self._rpc( "importdescriptors", diff --git a/src/codex32_gui/pages.py b/src/codex32_gui/pages.py index 6ed80813..756b0442 100644 --- a/src/codex32_gui/pages.py +++ b/src/codex32_gui/pages.py @@ -12,7 +12,7 @@ from dataclasses import dataclass from typing import Literal -from gi.repository import Adw, Gio, GLib, Gtk +from gi.repository import Adw, Gio, GLib, Gtk, Pango from codex32 import ( ConfirmationResult, @@ -81,6 +81,9 @@ "date was too late. Let Core finish syncing, then check your balance and past payments." ), ) +FRESH_LIST = ( + "Your cards are unharmed. This list is fresh from Bitcoin Core: a wallet that now holds keys is gone." +) CARDS_SAFE = ( "Your cards are unharmed and still recover this wallet. Nothing was written onto them and " "nothing about them changed. When Bitcoin Core is ready, choose \u201cRestore my wallet\u201d " @@ -111,6 +114,7 @@ def _page( ) -> Adw.NavigationPage: scroller = Gtk.ScrolledWindow(hscrollbar_policy=Gtk.PolicyType.NEVER, vexpand=True) scroller.set_child(Adw.Clamp(maximum_size=700, child=content, margin_start=18, margin_end=18)) + scroller.get_vadjustment().connect("changed", lambda shown: _grow(scroller, shown)) bars = Adw.ToolbarView() bars.add_top_bar(Adw.HeaderBar()) bars.set_content(scroller) @@ -121,6 +125,15 @@ def _page( return page +def _grow(scroller: Gtk.ScrolledWindow, shown: Gtk.Adjustment) -> None: + """Make the window taller, never past the screen, until the page needs no scrolling.""" + window, short = scroller.get_root(), shown.get_upper() - shown.get_page_size() + if short > 0 and isinstance(window, Gtk.Window) and (surface := window.get_surface()) is not None: + width, height = window.get_default_size() + screen = window.get_display().get_monitor_at_surface(surface).get_geometry().height + window.set_default_size(width, min(height + int(short) + 1, screen)) + + def _column(*children: Gtk.Widget) -> Gtk.Box: box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=14, margin_top=18, margin_bottom=18) for child in children: @@ -215,9 +228,11 @@ def _blank(flow: Gtk.FlowBox) -> None: def _rows(title: str, values: Sequence[tuple[str, str]]) -> Adw.PreferencesGroup: - group = Adw.PreferencesGroup(title=title) + group = Adw.PreferencesGroup(title=title, css_classes=["compact"]) for label, value in values: - group.add(Adw.ActionRow(title=label, subtitle=value, subtitle_selectable=True, use_markup=False)) + row = Adw.ActionRow(title=label, use_markup=False) + row.add_suffix(Gtk.Label(label=value, selectable=True, wrap=True, wrap_mode=Pango.WrapMode.WORD_CHAR)) + group.add(row) return group @@ -277,6 +292,10 @@ def _working(view: Adw.NavigationView, title: str, message: str) -> Adw.Navigati spinner = Gtk.Spinner(halign=Gtk.Align.CENTER, width_request=32, height_request=32) spinner.start() page = _page(title, _column(spinner, _title(message)), can_pop=False) + # The page that asked: a worker started by another worker inherits its asker, + # so a failure never goes back to a spinner. + shown = view.get_visible_page() + page.asker = getattr(shown, "asker", shown) view.push(page) return page @@ -286,12 +305,13 @@ def _then[Result]( page: Adw.NavigationPage, follow: Callable[[Result], Adw.NavigationPage | None], advice: str = "", + again: Callable[[Exception], None] | None = None, ) -> Callable[[Result | Exception], None]: - """Turn a worker result into the next page, the failure page, or a step of its own.""" + """Turn a worker result into the next page, a step of its own, or `again`, else the failure page.""" def deliver(outcome: Result | Exception) -> None: if isinstance(outcome, Exception): - _failure(view, outcome, advice) + (again or (lambda error: _failure(view, error, advice)))(outcome) return following = follow(outcome) if following is not None: @@ -300,6 +320,18 @@ def deliver(outcome: Result | Exception) -> None: return deliver +def _alert(view: Adw.NavigationView, text: str) -> None: + dialog = Adw.AlertDialog(heading="That did not work", body=text) + dialog.add_response("close", "Close") + dialog.present(view) + + +def _back(view: Adw.NavigationView, page: Adw.NavigationPage, error: Exception) -> None: + """Go back to the page that asked, which still holds the seed, after a step that changed nothing.""" + view.pop_to_page(page.asker) + _alert(view, str(error)) + + def _describe(artifact: Artifact) -> str: header = artifact.header name = header.identifier.upper() @@ -773,18 +805,20 @@ def _wallets( expected: bytes | None, *, restoring: bool = False, + problem: str = "", ) -> None: page = _working(view, "Bitcoin Core", "Asking Bitcoin Core which wallets are empty…") + + def follow(found: tuple[wallet_setup.Wallet, ...]) -> Adw.NavigationPage: + if problem: + _alert(view, f"{problem}\n\n{FRESH_LIST}") + return _wallet_page(view, core, secret, found, timestamp, expected, restoring) + work.run( view, page, lambda: wallet_setup.eligible(core), - _then( - view, - page, - lambda found: _wallet_page(view, core, secret, found, timestamp, expected, restoring), - CARDS_SAFE, - ), + _then(view, page, follow, CARDS_SAFE, lambda error: _back(view, page, error)), ) @@ -813,7 +847,7 @@ def go() -> None: if chosen.locked: view.push(_unlock_page(view, core, secret, chosen, timestamp, expected, restoring)) return - _import(view, core, secret, chosen.name, "", timestamp, expected, restoring) + _import(view, core, secret, chosen, "", timestamp, expected, restoring) content = _column( _title( @@ -882,7 +916,13 @@ def job() -> tuple[Record, tuple[str, ...]]: page, job, _then( - view, page, lambda result: _finished_page(view, result[0], restoring, result[1]), CARDS_SAFE + view, + page, + lambda result: _finished_page(view, result[0], restoring, result[1]), + CARDS_SAFE, + lambda error: _wallets( + view, core, secret, timestamp, expected, restoring=restoring, problem=str(error) + ), ), ) @@ -933,64 +973,43 @@ def _unlock_page( expected: bytes | None, restoring: bool = False, ) -> Adw.NavigationPage: - """Unlock one already encrypted wallet, or step aside and let Bitcoin Core do it.""" + """Take the passphrase here, or carry on by itself once the wallet is unlocked in Bitcoin Core.""" field = Adw.PasswordEntryRow(title="Wallet passphrase") group = Adw.PreferencesGroup() group.add(field) - manual = Adw.ExpanderRow( - title="I would rather unlock it in Bitcoin Core myself", - subtitle="Then codex32 never sees the passphrase, exactly as the command line works.", + hint = _note( + f"Or unlock it in Bitcoin Core: in Window \u25b8 Console, select {wallet.name} and type " + f'walletpassphrase "YOUR PASSPHRASE" {wallet_setup.UNLOCK_SECONDS}. codex32 carries on by itself.' ) - manual.add_row( - Adw.ActionRow( - title="In Bitcoin Core, open Window ▸ Console", - subtitle=( - f"Select the wallet {wallet.name}, then type: " - f'walletpassphrase "YOUR PASSPHRASE" {wallet_setup.UNLOCK_SECONDS}' - ), - subtitle_selectable=True, - use_markup=False, - ) - ) - group.add(manual) + hint.set_selectable(True) - def check() -> None: - page = _working(view, "Bitcoin Core", "Checking whether the wallet is unlocked…") + stop = [lambda: None] - def job() -> Record: - wallet_setup.require_unlocked(core, wallet.name) - return _record(core, secret, wallet.name, timestamp, expected) + def go(passphrase: str) -> None: + stop[0]() # Any attempt, typed or noticed, ends the watch; only a refusal starts another. + _import(view, core, secret, wallet, passphrase, timestamp, expected, restoring) - work.run( - view, - page, - job, - _then(view, page, lambda record: _finished_page(view, record, restoring), CARDS_SAFE), - ) - - def go() -> None: - _import(view, core, secret, wallet.name, field.get_text(), timestamp, expected, restoring) + def shown(_page: Adw.NavigationPage) -> None: + _empty(field) + stop[0]() + stop[0] = work.watch(view, page, lambda: wallet_setup.unlocked(core, wallet.name), lambda: go("")) + field.connect("entry-activated", lambda _row: go(field.get_text())) content = _column( _title( - f"The wallet \u201c{wallet.name}\u201d is locked", + f"Unlock \u201c{wallet.name}\u201d", "Bitcoin Core needs its passphrase before your keys can be written into it.", ), group, - _note( - "Your passphrase goes straight to Bitcoin Core on standard input and nowhere else. It is " - "never saved, never written to a file, and never shown in the list of running programs. " - "codex32 locks the wallet again as soon as it has finished." - ), + hint, ) page = _page( "Unlock", content, - actions=_actions( - _button("I unlocked it myself", check), - _button("Unlock and finish", go, style="suggested-action"), - ), + actions=_actions(_button("Unlock", lambda: go(field.get_text()), style="suggested-action")), ) + # A refused passphrase brings the operator back here to type it again. + page.connect("showing", shown) _forget_when_gone(view, page, lambda: _empty(field)) return page @@ -1002,8 +1021,11 @@ def _record( timestamp: Timestamp, expected: bytes | None, passphrase: str = "", + encrypted: bool = False, ) -> Record: - final = wallet_setup.fill(core, secret, name, passphrase, expected=expected, timestamp=timestamp) + final = wallet_setup.fill( + core, secret, name, passphrase, expected=expected, timestamp=timestamp, encrypted=encrypted + ) return Record( secret.header.identifier.upper(), final, @@ -1096,7 +1118,9 @@ def follow(mismatch: str) -> Adw.NavigationPage | None: _wallets(view, core, secret, start, expected, restoring=restoring) return None - work.run(view, page, job, _then(view, page, follow, CARDS_SAFE)) + work.run( + view, page, job, _then(view, page, follow, CARDS_SAFE, lambda error: _back(view, page, error)) + ) buttons = [_button("Stop", lambda: view.replace([home(view)]))] if restoring: @@ -1126,18 +1150,27 @@ def _import( view: Adw.NavigationView, core: BitcoinCore, secret: MasterSeed, - name: str, + wallet: wallet_setup.Wallet, passphrase: str, timestamp: Timestamp, expected: bytes | None, restoring: bool = False, ) -> None: - page = _working(view, "Bitcoin Core", f"Writing your keys into {name}…") + page = _working(view, "Bitcoin Core", f"Writing your keys into {wallet.name}…") + + def again(error: Exception) -> None: + # Only a refused passphrase is known to have changed nothing. Anything else may + # have written to Bitcoin Core, so ask it afresh which wallets are still empty. + if isinstance(error, wallet_setup.Refused): + _back(view, page, error) + return + _wallets(view, core, secret, timestamp, expected, restoring=restoring, problem=str(error)) + work.run( view, page, - lambda: _record(core, secret, name, timestamp, expected, passphrase), - _then(view, page, lambda record: _finished_page(view, record, restoring), CARDS_SAFE), + lambda: _record(core, secret, wallet.name, timestamp, expected, passphrase, wallet.encrypted), + _then(view, page, lambda record: _finished_page(view, record, restoring), CARDS_SAFE, again), ) diff --git a/src/codex32_gui/style.py b/src/codex32_gui/style.py index 2bc7879b..6c3cbca2 100644 --- a/src/codex32_gui/style.py +++ b/src/codex32_gui/style.py @@ -27,6 +27,11 @@ border-radius: 12px; padding: 14px; } +.compact row > box.header { + min-height: 0; + padding-top: 0; + padding-bottom: 0; +} .reading { font-size: 0.9rem; } diff --git a/src/codex32_gui/wallet_setup.py b/src/codex32_gui/wallet_setup.py index b8e540d6..f92a0cf1 100644 --- a/src/codex32_gui/wallet_setup.py +++ b/src/codex32_gui/wallet_setup.py @@ -37,6 +37,7 @@ "BitcoinCoreError", "FingerprintMismatch", "Offer", + "Refused", "Wallet", "connect", "create", @@ -50,8 +51,8 @@ "parse_creation_date", "parse_fingerprint", "relock", - "require_unlocked", "unlock", + "unlocked", "verify", "version_text", ] @@ -116,6 +117,10 @@ def ask(self, prompt: str) -> str: raise Offer(tuple(dict.fromkeys(self._listed))) +class Refused(BitcoinCoreError): + """Bitcoin Core turned the passphrase down, so nothing was written and it may be typed again.""" + + @dataclass(frozen=True, slots=True) class Wallet: """One Bitcoin Core wallet that codex32 is willing to fill.""" @@ -267,7 +272,7 @@ def unlock(core: BitcoinCore, name: str, passphrase: str) -> None: except UnicodeEncodeError: raise BitcoinCoreError(_UNSENDABLE) from None except BitcoinCoreError as error: - raise BitcoinCoreError(_REFUSED) from error + raise Refused(_REFUSED) from error open_now = False try: state = core._target(name) @@ -282,11 +287,9 @@ def unlock(core: BitcoinCore, name: str, passphrase: str) -> None: ) -def require_unlocked(core: BitcoinCore, name: str) -> None: - """Confirm the operator unlocked the wallet in Bitcoin Core themselves.""" - state = [item for item in eligible(core) if item.name == name] - if not state or state[0].locked: - raise BitcoinCoreError("That wallet is still locked in Bitcoin Core.") +def unlocked(core: BitcoinCore, name: str) -> bool: + """Report whether the operator has unlocked this still empty wallet in Bitcoin Core.""" + return core._target(name) == (True, False) # Encrypted, and no longer locked. def initialize( @@ -314,19 +317,21 @@ def fill( expected: bytes | None, account: int = 0, timestamp: int | Literal["now"] = "now", + encrypted: bool = False, ) -> str: - """Unlock, import, and lock again, whatever happens in between. - - `BitcoinCore.initialize` relocks from its own `finally`, but it arms that - obligation only after it has chosen the wallet, so a refusal raised before - then would leave a wallet this program unlocked open. The obligation here - covers the whole sequence; locking an already locked wallet is harmless. - """ - if not passphrase: - return initialize(core, secret, name, expected=expected, account=account, timestamp=timestamp) - verify(core, secret, expected, timestamp) - unlock(core, name, passphrase) + """Unlock, import, and lock an encrypted wallet again, whatever happens in between.""" + # `BitcoinCore.initialize` relocks from its own `finally`, but it arms that + # obligation only after it has checked the seed and chosen the wallet, so a + # refusal raised before then would leave an unlocked wallet open: one this + # program unlocked, or one the operator unlocked in Bitcoin Core's window. + # The obligation here covers the whole sequence for both; locking an already + # locked wallet is harmless. + if passphrase: + verify(core, secret, expected, timestamp) try: + if passphrase: + unlock(core, name, passphrase) return initialize(core, secret, name, expected=expected, account=account, timestamp=timestamp) finally: - relock(core, name) + if passphrase or encrypted: + relock(core, name) diff --git a/src/codex32_gui/work.py b/src/codex32_gui/work.py index 3bcfa947..6ec1350a 100644 --- a/src/codex32_gui/work.py +++ b/src/codex32_gui/work.py @@ -2,6 +2,7 @@ from __future__ import annotations +import contextlib import threading from collections.abc import Callable @@ -74,6 +75,46 @@ def deliver(outcome: Result | Exception) -> bool: threading.Thread(target=worker).start() +def watch( + view: Adw.NavigationView, page: Adw.NavigationPage, ready: Callable[[], bool], then: Callable[[], None] +) -> Callable[[], None]: + """Ask `ready` off the main loop every two seconds while `page` is in front; once it says yes, `then`.""" + # Returns the function that stops it for good. + # This is how the command line waits for something done in Bitcoin Core's own + # window, so the operator never has to come back and say it is done. It goes on + # once at most, and the latch is set before `then` runs, so whatever `then` + # leads to, success or failure, never starts it again unasked. + stopped = threading.Event() + + def check() -> None: + found = False + with contextlib.suppress(BitcoinCoreError, OSError, ValueError, TypeError): + found = ready() + GLib.idle_add(arrive, found) + + def arrive(found: bool) -> bool: + if stopped.is_set() or not showing(view, page): + return False + if found and view.get_visible_page() is page and not _running: + stopped.set() + then() + else: + GLib.timeout_add_seconds(2, ask) + return False + + def ask() -> bool: + if stopped.is_set(): + return False + if view.get_visible_page() is page and not _running: + # One question at a time: the next is only scheduled once this one is answered. + threading.Thread(target=check, daemon=True).start() + return False + return showing(view, page) + + GLib.timeout_add_seconds(2, ask) + return stopped.set + + def _busy[Result]( view: Adw.NavigationView, page: Adw.NavigationPage, diff --git a/tests/test_bitcoin_core.py b/tests/test_bitcoin_core.py index f0ecee7e..557f7962 100644 --- a/tests/test_bitcoin_core.py +++ b/tests/test_bitcoin_core.py @@ -391,6 +391,7 @@ def test_encrypted_import_retries_without_a_passphrase_verifies_and_relocks( "_rpc", lambda client, *args, wallet=None, stdin=None: rpc(client, *args, wallet=wallet, stdin=stdin), ) + monkeypatch.setattr("codex32._bitcoin_core.time.time", lambda: 1_700_000_000.5) client = BitcoinCore("bitcoin-cli", "main", 300000) messages: list[str] = [] delays: list[int] = [] @@ -411,7 +412,8 @@ def unlock(seconds: int) -> None: assert arguments == ("importdescriptors",) and wallet == "signer" assert private_stdin is not None and private_stdin.endswith("\n") records = json.loads(private_stdin) - assert len(records) == 4 and all(record["timestamp"] == "now" for record in records) + # A new wallet's "now" is this computer's clock less a day, not Core's tip (genesis offline). + assert len(records) == 4 and all(record["timestamp"] == 1_700_000_000 - 86400 for record in records) assert all("xprv" in record["desc"] for record in records) assert all("xprv" not in " ".join((*args, selected or "")) for args, selected, _data in rpc.calls) assert sum(args[:2] == ("-named", "derivehdkey") for args, _wallet, _stdin in rpc.calls) == 4 diff --git a/tests/test_gui_boundaries.py b/tests/test_gui_boundaries.py index 1d73c9c7..95b07358 100644 --- a/tests/test_gui_boundaries.py +++ b/tests/test_gui_boundaries.py @@ -33,7 +33,7 @@ } ) CORE_ADAPTER = "codex32._bitcoin_core" -BUDGET = 2050 +BUDGET = 2100 def _package() -> Path: @@ -132,7 +132,14 @@ def test_the_gui_keeps_its_own_size_budget() -> None: def test_every_restore_way_to_a_wallet_passes_the_identity_choice() -> None: tree = ast.parse((_package() / "pages.py").read_text()) - assert _callers(tree, "_wallets") == {"_fingerprint_page", "_identity", "_wallet_page"} + # The wallet steps go back to the list after a failed write, handing on the `expected` they were given. + assert _callers(tree, "_wallets") == { + "_fingerprint_page", + "_identity", + "_wallet_page", + "_new_wallet_page", + "_import", + } assert _callers(tree, "_fingerprint_page") == {"_identity", "_restore", "_fingerprint_page"} assert _callers(tree, "_identity") == {"_unshared_page", "_card_confirmed", "_fingerprint_page"} diff --git a/tests/test_gui_unlock_flow.py b/tests/test_gui_unlock_flow.py new file mode 100644 index 00000000..ba0fc842 --- /dev/null +++ b/tests/test_gui_unlock_flow.py @@ -0,0 +1,197 @@ +"""The unlock and retry flow in a real GTK window, against a stand-in for bitcoin-cli. + +Skipped unless libadwaita 1.5 or later and a display are available. Headless: +`xvfb-run -a python -m pytest tests/test_gui_unlock_flow.py`. +""" + +from __future__ import annotations + +import subprocess +import time +from collections.abc import Callable, Iterator +from typing import Any + +import pytest + +gi = pytest.importorskip("gi") +try: + gi.require_version("Adw", "1") + from gi.repository import Adw, Gdk, GLib, Gtk +except (ImportError, ValueError): + pytest.skip("libadwaita is not installed", allow_module_level=True) +if (Adw.get_major_version(), Adw.get_minor_version()) < (1, 5) or Gdk.Display.get_default() is None: + pytest.skip("needs libadwaita 1.5 and a display", allow_module_level=True) + +from test_gui_wallet_setup import _SEED, _Core, _Wallet + +from codex32._bitcoin_core import BitcoinCore, BitcoinCoreError +from codex32_gui import pages, wallet_setup + +RIGHT = "right horse" + + +class _Flow: + def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: + self.fake = _Core({"cold": _Wallet(True, True)}) + self.imports: list[str] = [] + self.fail_import = False + self.fail_lock = False + original = _Core._reply + + def reply(core: _Core, method: str, arguments: list[str], name: str | None) -> str: + if method == "walletpassphrase" and arguments[0] != RIGHT: + raise BitcoinCoreError("incorrect passphrase") + if method == "walletlock" and self.fail_lock: + raise BitcoinCoreError("The local Bitcoin Core command did not complete.") + return original(core, method, arguments, name) + + def initialize(_core: BitcoinCore, _secret: object, name: str, **_keywords: object) -> str: + self.imports.append(name) + if self.fake.wallets[name].locked: + raise BitcoinCoreError("Bitcoin Core is waiting for something to be done in its own window.") + if self.fail_import: + raise BitcoinCoreError("Bitcoin Core did not import every private descriptor.") + return name + + monkeypatch.setattr(_Core, "_reply", reply) + monkeypatch.setattr(subprocess, "run", lambda command, **keywords: self.fake.run(command, **keywords)) + monkeypatch.setattr(wallet_setup, "initialize", initialize) + monkeypatch.setattr(wallet_setup, "fingerprint", lambda _core, _secret: "00000000") + self.core = BitcoinCore("bitcoin-cli", "regtest", 320000) + self.view = Adw.NavigationView() + self.window = Adw.Window(content=self.view, default_width=880, default_height=620) + self.view.push(pages.home(self.view)) + self.window.present() + + def pump(self, seconds: float) -> None: + context, end = GLib.MainContext.default(), time.monotonic() + seconds + while time.monotonic() < end: + while context.pending(): + context.iteration(False) + time.sleep(0.01) + + def until(self, done: Callable[[], bool], seconds: float = 8.0) -> None: + end = time.monotonic() + seconds + while not done() and time.monotonic() < end: + self.pump(0.05) + + def unlock_page(self) -> Adw.NavigationPage: + found = wallet_setup.eligible(self.core) + self.view.push(pages._wallet_page(self.view, self.core, _SEED, found, "now", None, False)) + page = pages._unlock_page(self.view, self.core, _SEED, found[0], "now", None) + self.view.push(page) + self.pump(0.3) + return page + + def submit(self, page: Adw.NavigationPage, passphrase: str) -> None: + _find(page, Adw.PasswordEntryRow).set_text(passphrase) + _find(page, Gtk.Button, "Unlock").emit("clicked") + + @property + def title(self) -> str: + return str(self.view.get_visible_page().get_title()) + + @property + def alert(self) -> str: + dialog = self.window.get_visible_dialog() + return "" if dialog is None else str(dialog.get_body()) + + +def _widgets(root: Any) -> Iterator[Any]: + child = root.get_first_child() + while child is not None: + yield child + yield from _widgets(child) + child = child.get_next_sibling() + + +def _find(root: Any, kind: type, label: str | None = None) -> Any: + return next( + w for w in _widgets(root) if isinstance(w, kind) and (label is None or w.get_label() == label) + ) + + +@pytest.fixture +def flow(monkeypatch: pytest.MonkeyPatch) -> Iterator[_Flow]: + made = _Flow(monkeypatch) + yield made + made.window.destroy() + + +def test_a_mistyped_passphrase_is_typed_again_on_the_same_page(flow: _Flow) -> None: + page = flow.unlock_page() + flow.submit(page, "wrong horse") + flow.until(lambda: bool(flow.alert)) + assert flow.view.get_visible_page() is page + assert "did not accept" in flow.alert + assert _find(page, Adw.PasswordEntryRow).get_text() == "" + assert flow.imports == [] and flow.fake.wallets["cold"].locked + flow.window.get_visible_dialog().close() + flow.submit(page, RIGHT) + flow.until(lambda: flow.title == "Finished") + flow.pump(5) + assert flow.title == "Finished" + assert flow.imports == ["cold"] and flow.fake.wallets["cold"].locked + + +def test_an_unlock_in_bitcoin_core_is_noticed_once_and_locked_again(flow: _Flow) -> None: + flow.unlock_page() + flow.pump(2.5) + assert flow.imports == [] + flow.fake.wallets["cold"].locked = False + flow.until(lambda: flow.title == "Finished") + flow.pump(5) + assert flow.title == "Finished" + assert flow.imports == ["cold"] and flow.fake.wallets["cold"].locked + + +def test_a_failed_import_shows_a_fresh_list_and_is_never_retried_unasked(flow: _Flow) -> None: + flow.unlock_page() + flow.fail_import = True + flow.fake.wallets["cold"].locked = False + flow.until(lambda: bool(flow.alert)) + assert flow.title == "Wallet" + assert "did not import" in flow.alert and "fresh from Bitcoin Core" in flow.alert + assert flow.fake.wallets["cold"].locked + flow.window.get_visible_dialog().close() + flow.fake.wallets["cold"].locked = False + flow.pump(6) + assert flow.imports == ["cold"] + + +def test_typing_while_bitcoin_core_is_unlocked_imports_once(flow: _Flow) -> None: + page = flow.unlock_page() + flow.pump(1) + flow.fake.wallets["cold"].locked = False + flow.submit(page, RIGHT) + flow.until(lambda: flow.title == "Finished") + flow.pump(5) + assert flow.imports == ["cold"] + + +def test_a_failed_relock_is_said(flow: _Flow) -> None: + page = flow.unlock_page() + flow.fail_lock = True + flow.submit(page, RIGHT) + flow.until(lambda: bool(flow.alert)) + assert "Confirm in Bitcoin Core that the wallet is locked" in flow.alert + + +def test_a_worker_started_by_a_worker_goes_back_to_the_page_with_the_seed( + flow: _Flow, monkeypatch: pytest.MonkeyPatch +) -> None: + def broken(_core: BitcoinCore) -> tuple[wallet_setup.Wallet, ...]: + raise BitcoinCoreError("The local Bitcoin Core command did not complete.") + + monkeypatch.setattr(wallet_setup, "verify", lambda *_arguments: None) + monkeypatch.setattr(wallet_setup, "eligible", broken) + page = pages._fingerprint_page(flow.view, flow.core, _SEED, 0, restoring=True) + flow.view.push(page) + flow.pump(0.3) + fingerprint, date = (w for w in _widgets(page) if isinstance(w, Adw.EntryRow)) + fingerprint.set_text("00000000") + date.set_text("2024-01-01") + _find(page, Gtk.Button, "Check and continue").emit("clicked") + flow.until(lambda: bool(flow.alert)) + assert flow.view.get_visible_page() is page + assert "did not complete" in flow.alert diff --git a/tests/test_gui_wallet_setup.py b/tests/test_gui_wallet_setup.py index fcda8da9..339d8b2a 100644 --- a/tests/test_gui_wallet_setup.py +++ b/tests/test_gui_wallet_setup.py @@ -361,3 +361,58 @@ def test_the_chain_the_operator_chose_is_the_one_that_is_used( def test_the_version_is_reported_the_way_bitcoin_core_reports_it() -> None: assert wallet_setup.version_text(BitcoinCore("bitcoin-cli", "main", 320100)) == "32.1.0" + + +def test_an_unlock_done_in_bitcoin_core_is_noticed(monkeypatch: pytest.MonkeyPatch) -> None: + core, fake = _client(monkeypatch, {"fresh": _Wallet(True, True)}) + assert not wallet_setup.unlocked(core, "fresh") + fake.wallets["fresh"].locked = False + assert wallet_setup.unlocked(core, "fresh") + + +def test_an_unlock_done_in_bitcoin_core_is_locked_again_after_an_early_refusal( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The library arms its own relock only after checking the seed, so `fill` must cover what comes first.""" + core, fake = _client(monkeypatch, {"fresh": _Wallet(True, False)}) + + def mismatch(*_arguments: object, **_keywords: object) -> str: + raise FingerprintMismatch("wrong wallet") + + monkeypatch.setattr(wallet_setup, "initialize", mismatch) + with pytest.raises(FingerprintMismatch, match="wrong wallet"): + wallet_setup.fill(core, _SEED, "fresh", "", expected=b"expected", encrypted=True) + assert not fake.called("walletpassphrase") + assert fake.wallets["fresh"].locked + + +def test_an_unlock_done_in_bitcoin_core_survives_the_wallet_being_closed( + monkeypatch: pytest.MonkeyPatch, +) -> None: + core, fake = _client(monkeypatch, {"fresh": _Wallet(True, False)}) + + def unload(*_arguments: object, **_keywords: object) -> str: + del fake.wallets["fresh"] + raise BitcoinCoreError("fresh was closed.") + + monkeypatch.setattr(wallet_setup, "initialize", unload) + with pytest.raises(BitcoinCoreError, match="was closed"): + wallet_setup.fill(core, _SEED, "fresh", "", expected=None, encrypted=True) + + +def test_a_refused_passphrase_is_told_apart_and_writes_nothing(monkeypatch: pytest.MonkeyPatch) -> None: + core, fake = _client(monkeypatch, {"fresh": _Wallet(True, True)}) + original = _Core._reply + + def refuse(self: _Core, method: str, arguments: list[str], name: str | None) -> str: + if method == "walletpassphrase": + raise BitcoinCoreError("incorrect passphrase") + return original(self, method, arguments, name) + + monkeypatch.setattr(_Core, "_reply", refuse) + monkeypatch.setattr( + wallet_setup, "initialize", lambda *_a, **_k: pytest.fail("nothing may be written after a refusal") + ) + with pytest.raises(wallet_setup.Refused): + wallet_setup.fill(core, _SEED, "fresh", PASSPHRASE, expected=None) + assert fake.wallets["fresh"].locked diff --git a/tests/test_gui_watch.py b/tests/test_gui_watch.py new file mode 100644 index 00000000..747c0451 --- /dev/null +++ b/tests/test_gui_watch.py @@ -0,0 +1,164 @@ +"""`work.watch`, the GUI's stand-in for the command line's wait on Bitcoin Core, driven by a fake main loop.""" + +from __future__ import annotations + +import importlib.util +import sys +import types +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import pytest + +import codex32_gui + + +class _Loop: + """Holds what GLib would run later, so a test decides exactly when each callback runs.""" + + def __init__(self) -> None: + self.queued: list[tuple[Callable[..., bool], tuple[Any, ...]]] = [] + + def timeout_add_seconds(self, _seconds: int, callback: Callable[..., bool], *args: Any) -> int: + self.queued.append((callback, args)) + return len(self.queued) + + def idle_add(self, callback: Callable[..., bool], *args: Any) -> int: + return self.timeout_add_seconds(0, callback, *args) + + def run(self, rounds: int = 20) -> None: + for _ in range(rounds): + due, self.queued = self.queued, [] + for callback, args in due: + if callback(*args): + self.queued.append((callback, args)) + + +class _Stack: + def __init__(self, pages: list[object]) -> None: + self.pages = pages + + def get_n_items(self) -> int: + return len(self.pages) + + def get_item(self, position: int) -> object: + return self.pages[position] + + +class _View: + def __init__(self, *pages: object) -> None: + self.pages = list(pages) + + def get_visible_page(self) -> object: + return self.pages[-1] + + def get_navigation_stack(self) -> _Stack: + return _Stack(self.pages) + + +class _Inline: + """Runs a thread's target at once, so the order of events is the test's.""" + + def __init__(self, target: Callable[[], None], daemon: bool = False) -> None: + self.target = target + + def start(self) -> None: + self.target() + + +@pytest.fixture +def work(monkeypatch: pytest.MonkeyPatch) -> tuple[types.ModuleType, _Loop]: + loop = _Loop() + repository = types.ModuleType("gi.repository") + repository.GLib = loop # type: ignore[attr-defined] + repository.Adw = types.SimpleNamespace() # type: ignore[attr-defined] + gi = types.ModuleType("gi") + gi.repository = repository # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "gi", gi) + monkeypatch.setitem(sys.modules, "gi.repository", repository) + path = Path(codex32_gui.__file__).parent / "work.py" + spec = importlib.util.spec_from_file_location("codex32_gui._work_under_test", path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + monkeypatch.setattr(module.threading, "Thread", _Inline) + return module, loop + + +def test_it_waits_while_the_wallet_is_locked_and_goes_on_once(work: tuple[types.ModuleType, _Loop]) -> None: + module, loop = work + page, view, state, went = object(), _View(), {"open": False}, [] + view.pages = ["home", page] + module.watch(view, page, lambda: state["open"], lambda: went.append(1)) + loop.run() + assert went == [] + state["open"] = True + loop.run() + assert went == [1] + view.pages.append("working") # `then` moved on; it comes back here after a failure + loop.run() + view.pages.pop() + loop.run() + assert went == [1], "a finished or failed attempt must never start another one unasked" + assert loop.queued == [] + + +def test_a_typed_attempt_stops_it_for_good(work: tuple[types.ModuleType, _Loop]) -> None: + module, loop = work + page, view, went = object(), _View(), [] + view.pages = ["home", page] + stop = module.watch(view, page, lambda: True, lambda: went.append(1)) + stop() + loop.run() + assert went == [] + assert loop.queued == [] + + +def test_an_answer_that_arrives_after_a_typed_attempt_is_dropped( + work: tuple[types.ModuleType, _Loop], +) -> None: + module, loop = work + page, view, went = object(), _View(), [] + view.pages = ["home", page] + stop: list[Callable[[], None]] = [] + + def ready() -> bool: + stop[0]() # the operator presses Unlock while Bitcoin Core is being asked + return True + + stop.append(module.watch(view, page, ready, lambda: went.append(1))) + loop.run() + assert went == [] + + +def test_it_never_asks_behind_another_page_or_another_operation(work: tuple[types.ModuleType, _Loop]) -> None: + module, loop = work + page, view, asked, went = object(), _View(), [], [] + view.pages = ["home", page, "working"] + module.watch(view, page, lambda: asked.append(1) or True, lambda: went.append(1)) + loop.run() + assert asked == [] and went == [] + view.pages.pop() + module._running = True + loop.run() + assert asked == [] and went == [] + module._running = False + loop.run() + assert went == [1] + + +def test_it_ends_with_its_page_and_survives_core_errors(work: tuple[types.ModuleType, _Loop]) -> None: + module, loop = work + page, view, went = object(), _View(), [] + view.pages = ["home", page] + + def broken() -> bool: + raise module.BitcoinCoreError("The local Bitcoin Core command did not complete.") + + module.watch(view, page, broken, lambda: went.append(1)) + loop.run(3) + assert went == [] and loop.queued + view.pages.pop() + loop.run() + assert went == [] and loop.queued == []