Skip to content

Commit b5ef808

Browse files
committed
wallet: Share one eligible-wallet observation between CLI and GUI
BitcoinCore._eligible_wallets(names) looks once, without waiting, at which of the given wallets are eligible and returns their encryption and lock state. The CLI's menu and its wait for a new wallet use it with the names they already fetched, so the CLI asks Core exactly what it asked before and still offers only wallets that appeared while it waited. wallet_setup.eligible() is now an adapter over it. The GUI wallet page starts a poll only when the last one has reported, so a slow Core cannot pile polls up behind the work gate; work.busy() had no other use and is gone. Claude-Session: https://claude.ai/code/session_01N8jLK621Vh9wiv9ZntctSG
1 parent 0259e5f commit b5ef808

6 files changed

Lines changed: 89 additions & 21 deletions

File tree

‎src/codex32/_bitcoin_core.py‎

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import string
1010
import subprocess
1111
import time
12-
from collections.abc import Callable
12+
from collections.abc import Callable, Iterable
1313
from dataclasses import dataclass
1414
from time import sleep
1515
from typing import Literal
@@ -360,11 +360,16 @@ def _target(self, name: str) -> tuple[bool, bool] | None:
360360
unlocked = info.get("unlocked_until")
361361
return (unlocked is not None, unlocked == 0) if eligible else None
362362

363+
# One observation, never a wait: (name, encrypted, locked) for each eligible wallet among `names`,
364+
# sorted. The CLI's menu and wait below and the GUI's wallet list all decide eligibility here.
365+
def _eligible_wallets(self, names: Iterable[str]) -> tuple[tuple[str, bool, bool], ...]:
366+
return tuple((name, *state) for name in sorted(names) if (state := self._target(name)) is not None)
367+
363368
def _select(self, ask: Callable[[str], str], tell: Callable[[str], None]) -> str:
364369
def agree(name: str) -> bool:
365370
return ask(f"Use blank wallet {json.dumps(name)}? [y/N]").lower() in ("y", "yes")
366371

367-
choices = tuple(name for name in sorted(self._names()) if self._target(name) is not None)
372+
choices = tuple(row[0] for row in self._eligible_wallets(self._names()))
368373
if len(choices) == 1 and agree(choices[0]):
369374
return choices[0]
370375
while True:
@@ -375,8 +380,7 @@ def agree(name: str) -> bool:
375380
tell(f" {len(choices) + 1}. Create another wallet in Bitcoin Core")
376381
answer = ask("Choose a wallet number")
377382
if answer.isdecimal() and 1 <= int(answer) <= len(choices):
378-
name = choices[int(answer) - 1]
379-
if agree(name):
383+
if agree(name := choices[int(answer) - 1]):
380384
return name
381385
continue
382386
if answer != str(len(choices) + 1):
@@ -388,13 +392,12 @@ def agree(name: str) -> bool:
388392
"private keys enabled."
389393
)
390394
tell("Waiting; press Ctrl-C to stop.")
391-
while True:
395+
appeared: tuple[str, ...] = ()
396+
while not appeared:
392397
sleep(1)
393398
names = set(self._names())
394-
appeared = tuple(name for name in sorted(names - before) if self._target(name) is not None)
395-
if appeared:
396-
break
397-
choices = tuple(name for name in sorted(names) if self._target(name) is not None)
399+
appeared = tuple(row[0] for row in self._eligible_wallets(names - before))
400+
choices = tuple(row[0] for row in self._eligible_wallets(names))
398401
if len(appeared) == 1 and agree(appeared[0]):
399402
return appeared[0]
400403

‎src/codex32_gui/pages.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -819,13 +819,20 @@ def show(listed: tuple[wallet_setup.Wallet, ...]) -> None:
819819
holder.remove(old)
820820
holder.append(group)
821821

822+
polling = False
823+
822824
def refreshed(listed: tuple[wallet_setup.Wallet, ...] | Exception) -> None:
825+
nonlocal polling
826+
polling = False
823827
# A failed poll keeps the list shown; Continue reports Bitcoin Core's error if it persists.
824828
if isinstance(listed, tuple) and listed != found:
825829
show(listed)
826830

827831
def poll() -> bool:
828-
if view.get_visible_page() is page and not work.busy():
832+
nonlocal polling
833+
# One poll at a time: a slow Bitcoin Core must not pile up queued polls behind the gate.
834+
if view.get_visible_page() is page and not polling:
835+
polling = True
829836
work.run(view, page, lambda: wallet_setup.eligible(core), refreshed)
830837
return work.showing(view, page)
831838

‎src/codex32_gui/wallet_setup.py‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -174,12 +174,7 @@ def version_text(core: BitcoinCore) -> str:
174174

175175
def eligible(core: BitcoinCore) -> tuple[Wallet, ...]:
176176
"""List the empty descriptor wallets Bitcoin Core would accept an import into."""
177-
found = []
178-
for name in sorted(core._names()):
179-
state = core._target(name)
180-
if state is not None:
181-
found.append(Wallet(name, state[0], state[1]))
182-
return tuple(found)
177+
return tuple(Wallet(*row) for row in core._eligible_wallets(core._names()))
183178

184179

185180
def _transferable(text: str, subject: str) -> None:

‎src/codex32_gui/work.py‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,6 @@ def showing(view: Adw.NavigationView, page: Adw.NavigationPage) -> bool:
2828
return any(stack.get_item(position) is page for position in range(stack.get_n_items()))
2929

3030

31-
def busy() -> bool:
32-
"""Report whether an operation holds the gate, so a background poll can skip a turn."""
33-
return _gate.locked()
34-
35-
3631
def run[Result](
3732
view: Adw.NavigationView,
3833
page: Adw.NavigationPage,

‎tests/test_bitcoin_core.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,21 @@ def ask(prompt: str) -> str:
317317
assert messages[1] == "Waiting; press Ctrl-C to stop."
318318

319319

320+
def test_eligible_wallets_observe_once_and_see_a_wallet_become_eligible(
321+
monkeypatch: pytest.MonkeyPatch,
322+
) -> None:
323+
client = BitcoinCore("bitcoin-cli", "main", 300000)
324+
states = iter((None, (True, True)))
325+
names: list[int] = []
326+
monkeypatch.setattr(BitcoinCore, "_names", lambda _client: names.append(1) or ("later",))
327+
monkeypatch.setattr(BitcoinCore, "_target", lambda _client, _name: next(states))
328+
329+
assert client._eligible_wallets(("later",)) == ()
330+
assert client._eligible_wallets(("later",)) == (("later", True, True),)
331+
assert client._eligible_wallets(()) == ()
332+
assert names == []
333+
334+
320335
@dataclass
321336
class _ImportRPC:
322337
private: bool = True

‎tests/test_gui_before_you_start.py‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,3 +165,56 @@ def test_the_wallet_list_refreshes_like_the_cli_and_keeps_the_choice(monkeypatch
165165

166166
view.pop()
167167
assert polls[0]() is False
168+
169+
170+
def _polled_page(monkeypatch: pytest.MonkeyPatch, found: tuple[Any, ...], *listed: tuple[Any, ...]) -> Any:
171+
polls: list[Any] = []
172+
answers = list(listed)
173+
monkeypatch.setattr(pages.GLib, "timeout_add_seconds", lambda _seconds, poll: polls.append(poll))
174+
monkeypatch.setattr(pages.wallet_setup, "eligible", lambda _core: answers.pop(0))
175+
monkeypatch.setattr(pages.work, "run", lambda _view, _page, job, done: done(job()))
176+
view = Adw.NavigationView()
177+
view.push(pages.home(view))
178+
view.push(pages._wallet_page(view, object(), object(), found, "now", None, False)) # type: ignore[arg-type]
179+
return view, polls[0]
180+
181+
182+
def test_a_wallet_that_disappears_takes_the_choice_with_it(monkeypatch: pytest.MonkeyPatch) -> None:
183+
view, poll = _polled_page(monkeypatch, (_wallet("a"), _wallet("b")), (_wallet("b"),))
184+
page = view.get_visible_page()
185+
next(_widgets(page, Gtk.CheckButton)).set_active(True)
186+
poll()
187+
assert not any(choice.get_active() for choice in _widgets(page, Gtk.CheckButton))
188+
assert not _button(page, "Continue").get_sensitive()
189+
190+
191+
def test_a_wallet_named_like_the_create_row_stays_its_own_row(monkeypatch: pytest.MonkeyPatch) -> None:
192+
named = _wallet("Create a new wallet")
193+
imported: list[str] = []
194+
monkeypatch.setattr(pages, "_import", lambda _view, _core, _secret, name, *_rest: imported.append(name))
195+
view, poll = _polled_page(monkeypatch, (named,), (named, _wallet("z")))
196+
page = view.get_visible_page()
197+
list(_widgets(page, Gtk.CheckButton))[-1].set_active(True)
198+
poll()
199+
choices = list(_widgets(page, Gtk.CheckButton))
200+
assert [choice.get_active() for choice in choices] == [False, False, True]
201+
choices[0].set_active(True)
202+
_button(page, "Continue").emit("clicked")
203+
assert imported == ["Create a new wallet"]
204+
205+
206+
def test_a_slow_core_never_queues_a_second_poll(monkeypatch: pytest.MonkeyPatch) -> None:
207+
polls: list[Any] = []
208+
started: list[Any] = []
209+
monkeypatch.setattr(pages.GLib, "timeout_add_seconds", lambda _seconds, poll: polls.append(poll))
210+
monkeypatch.setattr(pages.work, "run", lambda _view, _page, job, done: started.append(done))
211+
view = Adw.NavigationView()
212+
view.push(pages.home(view))
213+
view.push(pages._wallet_page(view, object(), object(), (), "now", None, False)) # type: ignore[arg-type]
214+
215+
polls[0]()
216+
polls[0]()
217+
assert len(started) == 1
218+
started[0](())
219+
polls[0]()
220+
assert len(started) == 2

0 commit comments

Comments
 (0)