Skip to content

jmwallet.utxo_tui

jmwallet.utxo_tui

Shared helpers for the curses-based UTXO TUIs.

Both the freeze manager (jm-wallet freeze) and the interactive UTXO selector (--select-utxos) render the whole wallet grouped by mixdepth. This module holds the layout and navigation primitives they share:

  • building a display list with None separators between groups (mixdepths, or mixdepth/branch groups with fidelity bonds shown first),
  • labelling those separators from the group they introduce (mixdepth title, branch name),
  • cursor navigation that skips separators (and other non-selectable rows),
  • the address column formatting (full address on every row, middle-ellipsis when too long),
  • scroll-offset adjustment to keep the cursor visible,
  • the shared minimum-size prompt used while either terminal has no room for the full layout,
  • the table layout shared by both TUIs: dynamic columns sized to terminal width and content, cell clipping/formatting, and single-row rendering,
  • footer field wrapping/rendering, address-reuse detection (the RU! badge), and the cursor-item description used by both status lines,
  • the wallet-label enrichment both feeders run so the tag column is never empty for regular UTXOs.

Attributes

ADDRESS_COL_WIDTH = 42 module-attribute

EXTERNAL_BRANCH = 0 module-attribute

FIDELITY_BOND_BRANCH = 2 module-attribute

INTERNAL_BRANCH = 1 module-attribute

Classes

Functions:

adjust_scroll(cursor_pos: int, scroll_offset: int, list_height: int, item_count: int) -> int

Return a scroll offset that keeps cursor_pos visible.

The result is clamped to max(0, item_count - list_height) so an offset reached while the window was shrunken is given up as soon as more rows fit on screen again (never scroll further than necessary).

Source code in jmwallet/src/jmwallet/utxo_tui.py
237
238
239
240
241
242
243
244
245
246
247
248
def adjust_scroll(cursor_pos: int, scroll_offset: int, list_height: int, item_count: int) -> int:
    """Return a scroll offset that keeps ``cursor_pos`` visible.

    The result is clamped to ``max(0, item_count - list_height)`` so an
    offset reached while the window was shrunken is given up as soon as
    more rows fit on screen again (never scroll further than necessary).
    """
    if cursor_pos < scroll_offset:
        scroll_offset = cursor_pos
    elif cursor_pos >= scroll_offset + list_height:
        scroll_offset = cursor_pos - list_height + 1
    return min(scroll_offset, max(0, item_count - list_height))

align_control_columns(text: str, width: int) -> list[str]

Lay out a controls hint as aligned key/columns in a footer box.

The fields (split on " | ") are arranged in a column grid: each column is as wide as its longest field, so the | separators line up vertically across rows -- the controls read as a key table. Fields flow to fill a row only while the grid fits width; the last row may carry fewer columns. When everything fits on one line no grid is needed and the hint renders unwrapped (padded by the footer frame later). A field wider than width alone falls back to the plain field wrap (:func:_wrap_footer_fields), which hard-chunks it.

Source code in jmwallet/src/jmwallet/utxo_tui.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
def align_control_columns(text: str, width: int) -> list[str]:
    """Lay out a controls hint as aligned key/columns in a footer box.

    The fields (split on ``" | "``) are arranged in a column grid: each
    column is as wide as its longest field, so the ``|`` separators line
    up vertically across rows -- the controls read as a key table. Fields
    flow to fill a row only while the grid fits ``width``; the last row
    may carry fewer columns. When everything fits on one line no grid is
    needed and the hint renders unwrapped (padded by the footer frame
    later). A field wider than ``width`` alone falls back to the plain
    field wrap (:func:`_wrap_footer_fields`), which hard-chunks it.
    """
    fields = text.split(" | ")
    if len(fields) == 1 or max(_display_width(field) for field in fields) > width:
        return _wrap_footer_fields(text, width)
    if sum(_display_width(field) for field in fields) + 3 * (len(fields) - 1) <= width:
        return [text]

    def grid(rows_of_fields: list[list[str]]) -> list[str]:
        """Render rows on the shared column grid (longest field per column)."""
        column_count = max(len(row) for row in rows_of_fields)
        column_widths = [
            max(_display_width(row[i]) for row in rows_of_fields if i < len(row))
            for i in range(column_count)
        ]
        lines = []
        for row in rows_of_fields:
            # Pad in columns, not characters: a wide character renders 2.
            cells = [
                field + " " * (column_widths[i] - _display_width(field))
                for i, field in enumerate(row[:-1])
            ]
            cells.append(row[-1])
            lines.append(" | ".join(cells))
        return lines

    # Greedy packing on the shared grid: try each column count, prefer the
    # layout with the fewest lines; the widest grid wins ties (fewer rows
    # per screen height budget). One field per row is always possible here:
    # a field wider than ``width`` alone was handled above.
    best: list[str] | None = None
    best_cols = 0
    for columns in range(len(fields), 0, -1):
        rows_of_fields = [fields[i : i + columns] for i in range(0, len(fields), columns)]
        rendered = grid(rows_of_fields)
        if max(_display_width(line) for line in rendered) <= width:
            best, best_cols = rendered, columns
            break
    if best is None:  # unreachable: single-column always fits (checked above)
        return _wrap_footer_fields(text, width)
    if best_cols == len(fields):
        return [text]
    return best

branch_display_rank(branch: int) -> int

Display rank of a branch group; unknown branches sort last.

Source code in jmwallet/src/jmwallet/utxo_tui.py
97
98
99
def branch_display_rank(branch: int) -> int:
    """Display rank of a branch group; unknown branches sort last."""
    return _BRANCH_DISPLAY_RANK.get(branch, len(_BRANCH_DISPLAY_RANK))

build_display_items(utxos: list[UTXOInfo], *, branch_groups: bool = False) -> list[UTXOInfo | None]

Insert None separators between display groups.

utxos must already be sorted so that all UTXOs of a group are contiguous. By default a group spans one mixdepth: a separator is inserted between consecutive mixdepths. With branch_groups=True the groups are (mixdepth, branch) pairs — external, internal and fidelity bonds get their own separators — and the list starts with a leading separator, so every separator precedes a group and can be labelled from the group's first row. Additionally each new mixdepth is introduced by a blank border-only row, encoded as two consecutive None entries (blank row, then the labelled separator). A None entry renders as a separator line (or, when the next entry is also None, as the blank row) and is skipped during navigation.

Source code in jmwallet/src/jmwallet/utxo_tui.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def build_display_items(
    utxos: list[UTXOInfo], *, branch_groups: bool = False
) -> list[UTXOInfo | None]:
    """Insert ``None`` separators between display groups.

    ``utxos`` must already be sorted so that all UTXOs of a group are
    contiguous. By default a group spans one mixdepth: a separator is inserted
    between consecutive mixdepths. With ``branch_groups=True`` the groups are
    (mixdepth, branch) pairs — external, internal and fidelity bonds get their
    own separators — and the list starts with a leading separator, so every
    separator precedes a group and can be labelled from the group's first row.
    Additionally each new mixdepth is introduced by a blank border-only row,
    encoded as two consecutive ``None`` entries (blank row, then the labelled
    separator). A ``None`` entry renders as a separator line (or, when the
    next entry is also ``None``, as the blank row) and is skipped during
    navigation.
    """
    display_items: list[UTXOInfo | None] = []
    current_group: tuple[int, ...] | None = None
    for utxo in utxos:
        group: tuple[int, ...] = (
            (utxo.mixdepth, utxo_branch(utxo)) if branch_groups else (utxo.mixdepth,)
        )
        if group != current_group:
            if branch_groups:
                if current_group is None or utxo.mixdepth != current_group[0]:
                    display_items.append(None)  # blank border-only row
                display_items.append(None)  # labelled separator
            elif display_items:
                display_items.append(None)
            current_group = group
        display_items.append(utxo)
    return display_items

chunk_to_display_width(text: str, width: int) -> list[str]

Split text into chunks of at most width display columns.

Character boundaries are preferred so a wide character is never split in half: the chunk grows until adding the next character would exceed width columns.

Source code in jmwallet/src/jmwallet/utxo_tui.py
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
def chunk_to_display_width(text: str, width: int) -> list[str]:
    """Split ``text`` into chunks of at most ``width`` display columns.

    Character boundaries are preferred so a wide character is never split in
    half: the chunk grows until adding the next character would exceed
    ``width`` columns.
    """
    chunks: list[str] = []
    chunk = ""
    chunk_cols = 0
    for char in text:
        char_cols = _display_width(char)
        if chunk_cols + char_cols > width and chunk:
            chunks.append(chunk)
            chunk = ""
            chunk_cols = 0
        chunk += char
        chunk_cols += char_cols
    chunks.append(chunk)
    return chunks

draw_resize_prompt(stdscr: curses.window, width: int, reason: str = '') -> None

Draw the minimum-size prompt shared by both TUIs.

reason names the dimension the terminal falls short of ("width" / "height") so the user resizes the right one; the generic message stays the fallback for callers without a diagnosis (the interrupted-repaint path).

Source code in jmwallet/src/jmwallet/utxo_tui.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def draw_resize_prompt(stdscr: curses.window, width: int, reason: str = "") -> None:
    """Draw the minimum-size prompt shared by both TUIs.

    ``reason`` names the dimension the terminal falls short of
    (``"width"`` / ``"height"``) so the user resizes the right one; the
    generic message stays the fallback for callers without a diagnosis
    (the interrupted-repaint path).
    """
    import curses

    if reason == "width":
        text = "Terminal too narrow. Please resize. q/Esc: cancel"
    elif reason == "height":
        text = "Terminal too short. Please resize. q/Esc: cancel"
    else:
        text = "Terminal too small. Please resize. q/Esc: cancel"
    try:
        stdscr.addstr(0, 0, text[: max(1, width - 1)])
    except curses.error:
        # Curses can report ERR after successfully writing the bottom-right cell (1x1).
        pass
    stdscr.refresh()

draw_status_block(stdscr: curses.window, row: int, lines: list[str], sep_width: int) -> int

Draw the framed status block; return the number of rows drawn.

Every line is framed left/right with plain border columns and padded to the table's right edge (same geometry as the footer box); the horizontal rules above and below the block are drawn by the caller (the top rule is the existing title separator, the bottom rule is the existing header top edge -- they stay where they are, only their row numbers shift).

Source code in jmwallet/src/jmwallet/utxo_tui.py
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
def draw_status_block(stdscr: curses.window, row: int, lines: list[str], sep_width: int) -> int:
    """Draw the framed status block; return the number of rows drawn.

    Every line is framed left/right with plain border columns and padded
    to the table's right edge (same geometry as the footer box); the
    horizontal rules above and below the block are drawn by the caller
    (the top rule is the existing title separator, the bottom rule is the
    existing header top edge -- they stay where they are, only their row
    numbers shift).
    """
    import curses

    value_attr = curses.color_pair(3) | curses.A_BOLD
    for line in lines:
        text_cols = _display_width(line)
        stdscr.addstr(row, 0, "|", curses.A_NORMAL)
        stdscr.addstr(row, 1, " " + line, value_attr)
        # Padding and right border stay plain: only the text carries the
        # row's attribute, the box frame never takes the text color.
        pad = sep_width - 2 - text_cols
        if pad > 0:
            stdscr.addstr(row, 2 + text_cols, " " * pad + "|", curses.A_NORMAL)
        elif sep_width >= 2:
            stdscr.addstr(row, sep_width, "|", curses.A_NORMAL)
        row += 1
    return len(lines)

enrich_utxo_labels(label_lookup: Callable[[str], str], utxos: list[UTXOInfo]) -> None

Populate missing wallet labels for display in both UTXO TUIs.

utxo_cache items carry no labels, so without this the tag column stays empty for every regular UTXO. Existing labels (BIP-329 annotations) and fidelity bond rows are preserved -- a bond's tag column already describes the bond state (fb-a/fb-x via :func:jmwallet.wallet.rows.short_label). label_lookup maps an address to its wallet label ("" when none).

Source code in jmwallet/src/jmwallet/utxo_tui.py
354
355
356
357
358
359
360
361
362
363
364
365
366
def enrich_utxo_labels(label_lookup: Callable[[str], str], utxos: list[UTXOInfo]) -> None:
    """Populate missing wallet labels for display in both UTXO TUIs.

    ``utxo_cache`` items carry no labels, so without this the ``tag`` column
    stays empty for every regular UTXO. Existing labels (BIP-329
    annotations) and fidelity bond rows are preserved -- a bond's tag column
    already describes the bond state (``fb-a``/``fb-x`` via
    :func:`jmwallet.wallet.rows.short_label`).
    ``label_lookup`` maps an address to its wallet label (``""`` when none).
    """
    for utxo in utxos:
        if utxo.label is None and not utxo.is_fidelity_bond:
            utxo.label = label_lookup(utxo.address)

format_address_column(address: str) -> str

Format an address for the TUI address column.

Every row shows its own address so duplicate addresses stay visible. Long addresses (e.g. fidelity bond P2WSH) are truncated in the middle.

Source code in jmwallet/src/jmwallet/utxo_tui.py
226
227
228
229
230
231
232
233
234
def format_address_column(address: str) -> str:
    """Format an address for the TUI address column.

    Every row shows its own address so duplicate addresses stay visible.
    Long addresses (e.g. fidelity bond P2WSH) are truncated in the middle.
    """
    if len(address) > ADDRESS_COL_WIDTH:
        return address[:20] + "..." + address[-19:]
    return address

format_utxo_line(utxo: UTXOInfo, max_width: int = 120, excluded_outpoints: set[tuple[str, int]] | None = None, term_width: int = 120, *, allowed_mixdepth: int | None = None, min_confirmations: int = 0, columns: list[tuple[str, int]] | None = None, allow_fidelity_bonds: bool = True, mark_title: str = 'Sel', state_override: StateToken | None = None, reused: bool | None = None) -> str

Format a single UTXO row with separate Label and State columns.

mark_title names the checkbox-style column owned by the row renderer; it is excluded from the formatted line. state_override replaces the selector's State computation (the freeze manager renders its own states: frozn/lock/spend, a subset of the shared catalog). reused marks the coin's address as shared (the callers know the wallet-wide address counts); without it only the auto-freeze reuse label can mark the row.

Source code in jmwallet/src/jmwallet/utxo_tui.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
def format_utxo_line(
    utxo: UTXOInfo,
    max_width: int = 120,
    excluded_outpoints: set[tuple[str, int]] | None = None,
    term_width: int = 120,
    *,
    allowed_mixdepth: int | None = None,
    min_confirmations: int = 0,
    columns: list[tuple[str, int]] | None = None,
    allow_fidelity_bonds: bool = True,
    mark_title: str = "Sel",
    state_override: StateToken | None = None,
    reused: bool | None = None,
) -> str:
    """Format a single UTXO row with separate Label and State columns.

    ``mark_title`` names the checkbox-style column owned by the row
    renderer; it is excluded from the formatted line. ``state_override``
    replaces the selector's State computation (the freeze manager renders
    its own states: frozn/lock/spend, a subset of the shared catalog).
    ``reused`` marks the coin's address as shared (the callers know the
    wallet-wide address counts); without it only the auto-freeze reuse
    label can mark the row.
    """
    columns = columns or _table_columns(term_width, [utxo], mark_title)
    # RU! cell: flush marker when this coin shares its address, blanks keep
    # every row's right border aligned (no content right of the border).
    if reused is None:
        reused = utxo.label == AUTO_FREEZE_REUSE_LABEL
    ru_cell = "RU!" if reused else "   "
    addr_col_width = dict(columns).get("address", 12)
    # Every row shows its own address (duplicate addresses stay visible);
    # long addresses are middle-truncated to the column width.
    if len(utxo.address) > addr_col_width:
        # Middle-ellipsis: show start...end
        prefix_len = (addr_col_width - 3) // 2
        suffix_len = addr_col_width - 3 - prefix_len
        addr_str = utxo.address[:prefix_len] + "..." + utxo.address[-suffix_len:]
    else:
        addr_str = utxo.address

    values = {
        "MD": f"m{utxo.mixdepth}",
        "address": addr_str,
        "sats": f"{utxo.value:,}",
        "confs": f"{utxo.confirmations:,}",
        "tag": _label_col_value(utxo),
        "state": (
            state_override
            if state_override is not None
            else _utxo_state_col(
                utxo,
                excluded_outpoints,
                allowed_mixdepth,
                min_confirmations,
                allow_fidelity_bonds=allow_fidelity_bonds,
            )
        ),
    }
    cells = [(name, size) for name, size in columns if name not in {mark_title, "RU!"}]
    body = _format_cells(values, cells) + " |"
    if any(name == "RU!" for name, _ in columns):
        body += ru_cell + "|"
    return _clip(body, max_width)

group_label(utxo: UTXOInfo) -> str

Label of the (mixdepth, branch) group utxo belongs to.

Example: Mixdepth 0 — fidelity bond addresses.

Source code in jmwallet/src/jmwallet/utxo_tui.py
112
113
114
115
116
117
118
119
def group_label(utxo: UTXOInfo) -> str:
    """Label of the (mixdepth, branch) group ``utxo`` belongs to.

    Example: ``Mixdepth 0 — fidelity bond addresses``.
    """
    branch = utxo_branch(utxo)
    name = _BRANCH_NAMES.get(branch, f"branch {branch}")
    return f"Mixdepth {utxo.mixdepth} — {name}"

group_separator_parts(display_items: list[UTXOInfo | None], pos: int) -> tuple[str, str, str, bool] | None

Label parts for the group separator at pos.

Returns (title, em_dash, branch, full_title) — for example ("Mixdepth 0", " — ", "external addresses", True) — or None for a trailing separator with no following group (renders as plain dashes). full_title is False when the separator only switches the branch within the same mixdepth; renderers then strike the title with dashes so a branch change leaves only the branch name column-flush with the full title above.

Source code in jmwallet/src/jmwallet/utxo_tui.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
def group_separator_parts(
    display_items: list[UTXOInfo | None], pos: int
) -> tuple[str, str, str, bool] | None:
    """Label parts for the group separator at ``pos``.

    Returns ``(title, em_dash, branch, full_title)`` — for example
    ``("Mixdepth 0", " — ", "external addresses", True)`` — or ``None`` for a
    trailing separator with no following group (renders as plain dashes).
    ``full_title`` is False when the separator only switches the branch within
    the same mixdepth; renderers then strike the title with dashes so a branch
    change leaves only the branch name column-flush with the full title above.
    """
    prev_item, next_item = _neighbor_items(display_items, pos)
    if next_item is None:
        return None
    title, em_dash, branch = group_label(next_item).partition(" — ")
    full_title = prev_item is None or prev_item.mixdepth != next_item.mixdepth
    return title, em_dash, branch, full_title

maker_bot_status() -> str

Maker process status, or UNKNOWN when procfs is unavailable.

Scans /proc argv for jm-maker (the maker console script and the systemd unit both run this entry point), so the TUI sees the maker whether it was started manually, via the legacy TUI menu, or under the Raspiblitz systemd service. pgrep -f parity without a subprocess: the exact argv match cannot hit the scanner's own process (whose argv is a Python TUI command line) or unrelated grep invocations.

Source code in jmwallet/src/jmwallet/utxo_tui.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
def maker_bot_status() -> str:
    """Maker process status, or ``UNKNOWN`` when procfs is unavailable.

    Scans ``/proc`` argv for ``jm-maker`` (the maker console script and the
    systemd unit both run this entry point), so the TUI sees the maker
    whether it was started manually, via the legacy TUI menu, or under the
    Raspiblitz systemd service. ``pgrep -f`` parity without a subprocess:
    the exact argv match cannot hit the scanner's own process (whose argv
    is a Python TUI command line) or unrelated grep invocations.
    """
    from pathlib import Path

    try:
        proc_dirs = list(Path("/proc").iterdir())
    except OSError:
        return "UNKNOWN"

    for proc_dir in proc_dirs:
        if not proc_dir.name.isdigit():
            continue
        try:
            argv = (proc_dir / "cmdline").read_bytes().split(b"\x00")
        except (OSError, PermissionError):
            continue
        for arg in argv:
            if arg == b"":
                continue
            try:
                arg_text = arg.decode("utf-8", errors="ignore")
            except UnicodeDecodeError:
                continue
            # pgrep -f parity: match the entry point whether it was invoked
            # via PATH (``jm-maker serve``) or by absolute path
            # (``/home/.../jm-maker serve``). The basename comparison never
            # matches unrelated commands (``not-jm-maker-x`` stays clean).
            if arg_text == "jm-maker" or arg_text.rsplit("/", 1)[-1] == "jm-maker":
                return "RUNNING"
    return "STOPPED"

seek_selectable(display_items: list[UTXOInfo | None], start: int, direction: int, is_selectable: Callable[[UTXOInfo], bool]) -> int

Return the nearest index from start whose item satisfies is_selectable.

None separators are always skipped. Searches in direction first and falls back to the opposite direction; returns start when nothing matches at all.

Source code in jmwallet/src/jmwallet/utxo_tui.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def seek_selectable(
    display_items: list[UTXOInfo | None],
    start: int,
    direction: int,
    is_selectable: Callable[[UTXOInfo], bool],
) -> int:
    """Return the nearest index from ``start`` whose item satisfies ``is_selectable``.

    ``None`` separators are always skipped. Searches in ``direction`` first
    and falls back to the opposite direction; returns ``start`` when nothing
    matches at all.
    """
    pos = start

    # Search in the requested direction
    while 0 <= pos < len(display_items):
        item = display_items[pos]
        if item is not None and is_selectable(item):
            return pos
        pos += direction

    # If not found, search in the opposite direction from start
    opposite = -direction
    pos = start + opposite
    while 0 <= pos < len(display_items):
        item = display_items[pos]
        if item is not None and is_selectable(item):
            return pos
        pos += opposite

    return start

show_help_overlay(stdscr: curses.window, state_tokens: Sequence[str], title: str) -> None

Keep the help legend scrollable and its controls visible after a resize.

Source code in jmwallet/src/jmwallet/utxo_tui.py
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
def show_help_overlay(stdscr: curses.window, state_tokens: Sequence[str], title: str) -> None:
    """Keep the help legend scrollable and its controls visible after a resize."""
    import curses

    offset = 0
    while True:
        height, width = stdscr.getmaxyx()
        try:
            stdscr.clear()
            if height < 8 or width < 30:
                draw_resize_prompt(stdscr, width, "height" if height < 8 else "width")
            else:
                sep_width = width - 1
                rows = _help_overlay_rows(sep_width, state_tokens)
                body, controls = rows[1:-3], rows[-3:]
                # Reserve the title, top border, controls section and last screen row.
                capacity = height - 7
                max_offset = max(0, len(body) - capacity)
                offset = min(offset, max_offset)
                if max_offset:
                    hint, attr = controls[1]
                    hint = f"j/k: scroll | {hint}"
                    if len(hint) > sep_width - 2:
                        hint = "j/k: scroll | q/Esc: back"
                    controls[1] = (hint, attr)
                stdscr.addstr(
                    1, 0, title.center(width)[:width], curses.color_pair(3) | curses.A_BOLD
                )
                visible_rows = [rows[0], *body[offset : offset + capacity], *controls]
                _draw_footer(stdscr, 2, visible_rows, sep_width)
                stdscr.refresh()
        except curses.error:
            # A resize can invalidate the dimensions between getmaxyx() and a write.
            pass

        key = stdscr.getch()
        if key in (curses.KEY_DOWN, ord("j")):
            offset += 1
        elif key in (curses.KEY_UP, ord("k")):
            offset = max(0, offset - 1)
        elif key != curses.KEY_RESIZE:
            return

status_header_lines(sep_width: int, wallet_name: str, fingerprint: str, maker_status: str, max_lines: int = 2) -> list[str]

Build the framed status lines shown above the column titles.

Layout follows the legacy whiptail menu_header: values align in one column (both labels are 15 columns wide), and the fields degrade in three stages as the terminal narrows:

  1. one line: name | fingerprint | maker status;
  2. name + maker status, fingerprint below (aligned under the name);
  3. name alone, fingerprint + maker status below.

Every stage keeps the name and fingerprint values aligned; stage 4 is per-value clipping inside stage 2/3 layouts (a value too long even for its line is clipped to the available columns, never overflowing the right border). Widths are measured in terminal columns (:func:_display_width), never character count.

max_lines is the height budget the caller can afford: with 1 only the single-line form is built (values clipped to fit), so a terminal narrow enough to force the two-line cascade but too short to pay for the extra row still renders instead of hitting the resize prompt -- any screen that rendered before the status block keeps rendering with it.

Source code in jmwallet/src/jmwallet/utxo_tui.py
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
def status_header_lines(
    sep_width: int, wallet_name: str, fingerprint: str, maker_status: str, max_lines: int = 2
) -> list[str]:
    """Build the framed status lines shown above the column titles.

    Layout follows the legacy whiptail ``menu_header``: values align in
    one column (both labels are 15 columns wide), and the fields degrade
    in three stages as the terminal narrows:

    1. one line: name | fingerprint | maker status;
    2. name + maker status, fingerprint below (aligned under the name);
    3. name alone, fingerprint + maker status below.

    Every stage keeps the name and fingerprint values aligned; stage 4 is
    per-value clipping inside stage 2/3 layouts (a value too long even for
    its line is clipped to the available columns, never overflowing the
    right border). Widths are measured in terminal columns
    (:func:`_display_width`), never character count.

    ``max_lines`` is the height budget the caller can afford: with 1 only
    the single-line form is built (values clipped to fit), so a terminal
    narrow enough to force the two-line cascade but too short to pay for
    the extra row still renders instead of hitting the resize prompt --
    any screen that rendered before the status block keeps rendering
    with it.
    """
    body_width = max(1, sep_width - 2)
    name_prefix = "Active Wallet: "
    fp_prefix = "Fingerprint:   "
    assert len(name_prefix) == _STATUS_LABEL_WIDTH == len(fp_prefix)

    def clip_to(text: str, width: int) -> str:
        """Column-exact clip (``_clip`` counts characters, not columns)."""
        if _display_width(text) <= width:
            return text
        while text and _display_width(text + "...") > width:
            text = text[:-1]
        return text + "..."

    maker_field = f"Maker Bot: {maker_status}"
    name_full = f"{name_prefix}{wallet_name}"
    fp_full = f"{fp_prefix}{fingerprint}"

    if max_lines <= 1:
        line = f"{name_full} | {fp_full} | {maker_field}"
        if _display_width(line) <= body_width:
            return [line]
        # Too tight for everything: keep all three fields and clip the name
        # value (the fingerprint and maker status are short, fixed-shape
        # values; dropping a whole field would hide more information).
        fixed = _display_width(f"{name_prefix} | {fp_full} | {maker_field}")
        budget = body_width - fixed
        if budget >= 4:  # room for at least one name char plus the "..." marker
            fitted = f"{name_prefix}{clip_to(wallet_name, budget)} | {fp_full} | {maker_field}"
            if _display_width(fitted) <= body_width:
                return [fitted]
        # Last resort: head-clip the whole line.
        return [clip_to(line, body_width)]

    lines: list[str] = []
    one_line = f"{name_full} | {fp_full} | {maker_field}"
    if _display_width(one_line) <= body_width:
        lines.append(one_line)
    else:
        two_line = f"{name_full} | {maker_field}"
        if _display_width(two_line) <= body_width:
            lines.append(two_line)
            lines.append(fp_full)
        else:
            lines.append(name_full)
            lines.append(f"{fp_full} | {maker_field}")

    clipped: list[str] = []
    for line in lines:
        clipped.append(clip_to(line, body_width))
    return clipped

utxo_branch(utxo: UTXOInfo) -> int

Return the branch component of the UTXO's derivation path.

Branch is the fourth numeric component in paths like m/84'/0'/0'/0/3 (external), .../1/3 (internal) or .../2/{timenumber} (fidelity bond); a trailing :locktime suffix does not affect it. Returns -1 for paths without a branch component so malformed paths group together instead of crashing the spend flow.

Source code in jmwallet/src/jmwallet/utxo_tui.py
84
85
86
87
88
89
90
91
92
93
94
def utxo_branch(utxo: UTXOInfo) -> int:
    """Return the branch component of the UTXO's derivation path.

    Branch is the fourth numeric component in paths like ``m/84'/0'/0'/0/3``
    (external), ``.../1/3`` (internal) or ``.../2/{timenumber}`` (fidelity
    bond); a trailing ``:locktime`` suffix does not affect it. Returns -1 for
    paths without a branch component so malformed paths group together instead
    of crashing the spend flow.
    """
    parts = utxo_sort_key(utxo)
    return parts[3] if len(parts) > 3 else -1

utxo_cursor_description(utxo: UTXOInfo) -> str

One-sentence explanation of a coin for the UTXO Status footer line.

Coin meanings are identical in the selector and the freeze manager.

Source code in jmwallet/src/jmwallet/utxo_tui.py
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
def utxo_cursor_description(utxo: UTXOInfo) -> str:
    """One-sentence explanation of a coin for the UTXO Status footer line.

    Coin meanings are identical in the selector and the freeze manager.
    """
    if utxo.is_fidelity_bond:
        # is_locked implies a locktime; the None check lets mypy see it.
        if utxo.is_locked and utxo.locktime is not None:
            return (
                f"Active Fidelity Bond: Locked and not spendable until "
                f"{datetime.fromtimestamp(utxo.locktime, UTC).strftime('%Y-%m-%d')} UTC!"
            )
        return "Expired Fidelity Bond"
    if utxo.label == "cj-change":
        return "Change output from a CoinJoin (deanonymising, keep separate)"
    if utxo.label == "cj-out":
        return "CoinJoin output (mixed funds)"
    if utxo.label == "non-cj-change":
        return "Regular change (not from CoinJoin)"
    if utxo.label == "deposit":
        return "Address with funds from internal or external sources"
    if utxo.label:
        return f"Label: {utxo.label}"
    return ""

utxo_display_sort_key(utxo: UTXOInfo) -> tuple[int, int, tuple[int, ...]]

Sort key for the interactive views: mixdepth, then branch in display order (fidelity bonds, external, internal), then derivation index.

Within a branch group the numeric path order of :func:utxo_sort_key is preserved, so indices >= 10 still sort correctly.

Source code in jmwallet/src/jmwallet/utxo_tui.py
102
103
104
105
106
107
108
109
def utxo_display_sort_key(utxo: UTXOInfo) -> tuple[int, int, tuple[int, ...]]:
    """Sort key for the interactive views: mixdepth, then branch in display
    order (fidelity bonds, external, internal), then derivation index.

    Within a branch group the numeric path order of :func:`utxo_sort_key` is
    preserved, so indices >= 10 still sort correctly.
    """
    return (utxo.mixdepth, branch_display_rank(utxo_branch(utxo)), utxo_sort_key(utxo))

utxo_sort_key(utxo: UTXOInfo) -> tuple[int, ...]

Numeric derivation-path sort key shared by the freeze manager and the interactive UTXO selector.

Paths look like m/84'/0'/0'/0/3 (receive), .../1/3 (change) or .../2/{timenumber} (fidelity bond). Comparing these as plain strings misorders indices >= 10 (.../0/10 sorts before .../0/2), so the integer path components are compared instead. A fidelity-bond locktime appended as :locktime adds a trailing tie-breaker and sorts consistently with the bare .../2/{timenumber} form.

Source code in jmwallet/src/jmwallet/utxo_tui.py
52
53
54
55
56
57
58
59
60
61
62
63
def utxo_sort_key(utxo: UTXOInfo) -> tuple[int, ...]:
    """Numeric derivation-path sort key shared by the freeze manager and the
    interactive UTXO selector.

    Paths look like ``m/84'/0'/0'/0/3`` (receive), ``.../1/3`` (change) or
    ``.../2/{timenumber}`` (fidelity bond). Comparing these as plain strings
    misorders indices >= 10 (``.../0/10`` sorts before ``.../0/2``), so the
    integer path components are compared instead. A fidelity-bond locktime
    appended as ``:locktime`` adds a trailing tie-breaker and sorts
    consistently with the bare ``.../2/{timenumber}`` form.
    """
    return tuple(int(part) for part in re.findall(r"\d+", utxo.path))

utxo_status_text(utxo: UTXOInfo, extra: list[str] | None = None) -> str

The footer's UTXO Status payload for utxo (shared by both TUIs).

Line 1 is Outpoint: with the full txid:vout; wrap it with :func:wrap_status_text, which moves the complete value below the label when the line is too wide instead of breaking mid-value. The explanation -- the cursor description plus any caller-supplied restriction fields -- always goes on its own line below, without a separator at the line break.

Source code in jmwallet/src/jmwallet/utxo_tui.py
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
def utxo_status_text(utxo: UTXOInfo, extra: list[str] | None = None) -> str:
    """The footer's UTXO Status payload for ``utxo`` (shared by both TUIs).

    Line 1 is ``Outpoint:`` with the full txid:vout; wrap it with
    :func:`wrap_status_text`, which moves the complete value below the
    label when the line is too wide instead of breaking mid-value. The
    explanation -- the cursor description plus any caller-supplied
    restriction fields -- always goes on its own line below, without a
    separator at the line break.
    """
    text = f"Outpoint: {utxo.txid}:{utxo.vout}"
    fields = [utxo_cursor_description(utxo), *(extra or [])]
    fields = [field for field in fields if field]
    if fields:
        text += "\n" + " | ".join(fields)
    return text

wrap_status_text(text: str, width: int) -> list[str]

Wrap a UTXO Status payload, keeping the outpoint value whole.

The Outpoint: label keeps the value on its line only while it fits; otherwise the complete txid:vout moves to its own line below the label (no mid-value break). Only a value too wide for the box even on its own line is hard-chunked. The explanation below (after \n) wraps like any other footer field via :func:_wrap_footer_fields.

Source code in jmwallet/src/jmwallet/utxo_tui.py
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
def wrap_status_text(text: str, width: int) -> list[str]:
    """Wrap a UTXO Status payload, keeping the outpoint value whole.

    The ``Outpoint:`` label keeps the value on its line only while it fits;
    otherwise the complete ``txid:vout`` moves to its own line below the
    label (no mid-value break). Only a value too wide for the box even on
    its own line is hard-chunked. The explanation below (after ``\\n``)
    wraps like any other footer field via :func:`_wrap_footer_fields`.
    """
    head, _, tail = text.partition("\n")
    lines: list[str] = []
    prefix = "Outpoint: "
    if head.startswith(prefix):
        value = head[len(prefix) :]
        if _display_width(head) > width:
            lines.append("Outpoint:")
            if _display_width(value) > width:
                lines.extend(chunk_to_display_width(value, width))
            else:
                lines.append(value)
        else:
            lines.append(head)
    else:
        lines.extend(_wrap_footer_fields(head, width))
    if tail:
        lines.extend(_wrap_footer_fields(tail, width))
    return lines