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
5 changes: 4 additions & 1 deletion src/codex32/_bitcoin_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
151 changes: 92 additions & 59 deletions src/codex32_gui/pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 "
Expand Down Expand Up @@ -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)
Expand All @@ -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:
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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

Expand All @@ -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:
Expand All @@ -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()
Expand Down Expand Up @@ -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)),
)


Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)
),
),
)

Expand Down Expand Up @@ -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

Expand All @@ -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,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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),
)


Expand Down
5 changes: 5 additions & 0 deletions src/codex32_gui/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Loading
Loading