From 4d2528351b6df2c54ce5506797722f37317047e5 Mon Sep 17 00:00:00 2001 From: Lance Date: Sun, 20 Sep 2026 00:48:53 -0400 Subject: [PATCH 01/78] android: poll the live wallet-child probe so the sync line moves MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The wallet screen's 2s loop read Wire::wallet_status, which only re-reads the snapshot the last probe left in the store — so the `sync h/t` segment sat frozen until a chain-mode tap ran start_wallet_child (which probes on its way out). The loop now paints once from the cached read (non-dialing, so the screen has a record immediately) and then calls Wire::wallet_child_refresh for every tick: one live probe of the child's loopback wallet RPC, and of the configured local daemon's get_info when that RPC does not answer. Same 2s cadence, same Dispatchers.IO, same sticky walletChildError, same one-poller guarantee. The loop is a top-level function taking its two reads as parameters, which is the only seam a JVM test has — requireWire() is NodeHost.requireOpen(), a process-global only a real Arti bootstrap sets. WalletChildRefreshLoopTest pins that the cached read paints exactly once and every tick after it is the live probe, that a probe slower than the tick is never overlapped, and that cancelling the loop (leaving the screen) stops the dialing. --- .../siriusdevops/onionwire/WireViewModel.kt | 82 +++++++++++-- .../onionwire/WalletChildRefreshLoopTest.kt | 108 ++++++++++++++++++ 2 files changed, 180 insertions(+), 10 deletions(-) create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/WalletChildRefreshLoopTest.kt diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 1efd980..6f26632 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -652,10 +652,17 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { fun openWalletChild() { if (walletChildPoller?.isActive == true) return walletChildPoller = viewModelScope.launch { - while (currentCoroutineContext().isActive) { - refreshWalletChild() - delay(WALLET_CHILD_TICK_MS) - } + walletChildRefreshLoop( + tickMs = WALLET_CHILD_TICK_MS, + // The first paint is the cached read: it never dials, so the + // screen has a record to render while the first probe is still + // in flight. + cached = ::paintWalletChildCached, + // Every tick after that is a live probe, so `height` / + // `target_height` move on their own instead of only when a + // chain-mode button is tapped. + live = ::refreshWalletChild, + ) } } @@ -671,17 +678,45 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { } /** - * One `wallet_status()` read. + * The first paint: one `wallet_status()` read. * * `Wire::wallet_status` is synchronous in Rust and re-reads the sealed * wallet-child record out of the SQLCipher store, so it goes to * [Dispatchers.IO] — a store decrypt on the main thread is an ANR waiting - * for a slow device. It never dials and never spawns, so a 2s cadence is - * cheap. + * for a slow device. It never dials and never spawns, so it is the right + * read to have a record on screen — and the wrong one to poll with. */ - suspend fun refreshWalletChild() { - val read = withContext(Dispatchers.IO) { runCatching { requireWire().walletStatus() } } - read.fold( + suspend fun paintWalletChildCached() = readWalletChild { requireWire().walletStatus() } + + /** + * One tick: a live probe, `Wire::wallet_child_refresh()`. + * + * `Wire::wallet_status` above only re-reads what the last probe left behind, + * so polling it pins the `sync h/t` segment on whatever the last + * start/stop saw. This one dials — the child's loopback wallet RPC, and the + * configured local daemon's `get_info` when the wallet RPC does not answer + * — which is what makes the chain's height and target move between ticks. + * + * It never spawns a child, and the core short-circuits with the cached + * snapshot when there is no live child, so it cannot invent `ready` for a + * wallet that is not there. Not free, though: the tick stays on the order of + * seconds rather than frames. + * + * Failure is folded into the sticky [walletChildError], same as the cached + * read: a probe that fails once must not blink the previous error off the + * screen. + */ + suspend fun refreshWalletChild() = readWalletChild { requireWire().walletChildRefresh() } + + /** + * Runs one of the two reads on [Dispatchers.IO] and lands it in the wallet + * state. `requireWire()` throws when the node is locked, so it is called + * *inside* the [runCatching] — a locked node has to surface as + * [walletChildError], not as a crash on the tick. + */ + private suspend fun readWalletChild(read: suspend () -> WalletChildStatus) { + val result = withContext(Dispatchers.IO) { runCatching { read() } } + result.fold( onSuccess = { _walletChild.value = it }, onFailure = { _walletChildError.value = it.message ?: it.toString() }, ) @@ -856,5 +891,32 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { ) } +/** + * The wallet-child refresh loop: one [cached] paint so the screen has something + * to render, then a live [live] probe every [tickMs]. + * + * The reads are parameters only so the JVM test tree can drive this loop + * without a `Wire` — `NodeHost.requireOpen()` is a process-global the unit test + * cannot prime. The two call sites in [WireViewModel.openWalletChild] bind them + * to the cached read and to the live probe. + * + * Serialized by construction, and that is the point: the loop suspends on each + * read before it sleeps, so a probe slower than [tickMs] delays the next tick + * instead of overlapping it. Do not turn this into a `Flow` with + * `collectLatest`, and do not `launch` the probe: two concurrent + * `wallet_child_refresh` calls against one wallet child is a racing probe. + */ +suspend fun walletChildRefreshLoop( + tickMs: Long, + cached: suspend () -> Unit, + live: suspend () -> Unit, +) { + cached() + while (currentCoroutineContext().isActive) { + delay(tickMs) + live() + } +} + /** Cadence of the wallet-child refresh loop, in milliseconds. */ private const val WALLET_CHILD_TICK_MS: Long = 2_000 diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/WalletChildRefreshLoopTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/WalletChildRefreshLoopTest.kt new file mode 100644 index 0000000..a1b59c2 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/WalletChildRefreshLoopTest.kt @@ -0,0 +1,108 @@ +package com.siriusdevops.onionwire + +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.currentTime +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * The wallet screen's refresh loop. + * + * `Wire` has no seam a JVM test can fake: `requireWire()` reads + * `NodeHost.requireOpen()`, a process-global that only `openWire()` — i.e. a + * real Arti bootstrap — sets, and `Wire` itself is the generated UniFFI + * interface. So the loop takes its two reads as parameters, and these tests + * drive it with recording lambdas to pin the two things that make the + * `sync h/t` segment live: + * + * - the cheap cached read paints once, and every tick after it is the live + * probe (`Wire::wallet_child_refresh`), not the cached status read + * (`Wire::wallet_status`) that only re-reads what the last probe left behind; + * - the ticks are serialized by construction — a probe slower than the tick + * delays the next one instead of overlapping it, so no two + * `wallet_child_refresh` calls are ever in flight against one wallet child. + * + * The binding of `live` to `WireViewModel.refreshWalletChild()` (and `cached` + * to `paintWalletChildCached()`) is the two lines in + * `WireViewModel.openWalletChild()`, and the source there is the evidence for + * it — nothing in this test can observe a `NodeHost` that is not open. + * + * Time is virtual, so the 2s cadence is free to assert. Note the scheduler's + * rule: `advanceTimeBy(n)` runs what is scheduled strictly before `n`, not the + * task at `n` itself. + */ +class WalletChildRefreshLoopTest { + + @Test + fun the_first_paint_is_the_cached_read_and_every_tick_after_it_is_live() = runTest { + var cached = 0 + var live = 0 + val job = launch { + walletChildRefreshLoop(tickMs = TICK_MS, cached = { cached++ }, live = { live++ }) + } + + // Four ticks of virtual time: probes at 2s, 4s and 6s; the 8s one has + // not fired yet. + advanceTimeBy(4 * TICK_MS) + + assertEquals("the cheap read paints once, and only once", 1, cached) + assertEquals("every tick after the paint is a live probe", 3, live) + assertEquals("and they land on the tick, not back to back", 4 * TICK_MS, currentTime) + + job.cancel() + advanceTimeBy(10 * TICK_MS) + assertEquals("cancelling the loop is what stops the dialing", 3, live) + } + + @Test + fun a_probe_slower_than_the_tick_is_never_overlapped() = runTest { + var inFlight = 0 + var maxInFlight = 0 + var probes = 0 + val job = launch { + walletChildRefreshLoop( + tickMs = TICK_MS, + cached = {}, + live = { + inFlight++ + if (inFlight > maxInFlight) maxInFlight = inFlight + delay(5 * TICK_MS) // a probe five ticks long + inFlight-- + probes++ + }, + ) + } + + // Probe 1 at 2s runs to 12s, probe 2 at 14s to 24s, probe 3 at 26s to + // 36s: each of them pushes the next tick out by its own length. + advanceTimeBy(19 * TICK_MS) + + assertEquals("two concurrent wallet_child_refresh probes is a race", 1, maxInFlight) + assertEquals("three probes done, none of them skipped or doubled", 3, probes) + assertEquals(19 * TICK_MS, currentTime) + + job.cancel() + } + + @Test + fun cancelling_the_loop_stops_the_probes() = runTest { + var live = 0 + val job = launch { + walletChildRefreshLoop(tickMs = TICK_MS, cached = {}, live = { live++ }) + } + + advanceTimeBy(3 * TICK_MS) + assertEquals("two ticks have gone by", 2, live) + + job.cancel() + advanceTimeBy(10 * TICK_MS) + assertEquals("leaving the wallet screen stops the dialing", 2, live) + } + + private companion object { + const val TICK_MS = 2_000L + } +} From c65946bfd5a5629da81f3442d2a9b1aba1560e69 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 20 Sep 2026 00:52:43 -0400 Subject: [PATCH 02/78] docs(android): rewrite Android docs to match the tree android/README.md, CUPRATE_DAEMON.md and MONERO_BINARIES.md were the half PR #133 left out. Releases are two manual dispatches, not a push to main; the APK version comes from the tag android-release checks out; the layout now includes wallet/ and keepalive/; the status line's sync h/t is documented; the APK poller still calls wallet_status, not wallet_child_refresh. --- android/CUPRATE_DAEMON.md | 107 +++++++++++------ android/MONERO_BINARIES.md | 45 +++++--- android/README.md | 228 ++++++++++++++++++++++++++++++++----- 3 files changed, 305 insertions(+), 75 deletions(-) diff --git a/android/CUPRATE_DAEMON.md b/android/CUPRATE_DAEMON.md index 1708d9e..e3b422b 100644 --- a/android/CUPRATE_DAEMON.md +++ b/android/CUPRATE_DAEMON.md @@ -5,10 +5,13 @@ OnionWire process** — is compiled into the Android build. This document is the provenance record for that: how the feature is enabled, why the link line looks the way it does, what CI checks, and what has *not* been proven. -Companion reading: `docs/WALLET.md` ("The in-process chain daemon") for what the -daemon is, `docs/cuprate-android-spike.md` for the cross-compile spike this -plumbing comes from, and `MONERO_BINARIES.md` for the `monero-wallet-rpc` -executable, which is still a child process — Cuprate has no wallet layer. +Companion reading: [docs/WALLET.md](../docs/WALLET.md) ("The in-process chain +daemon") for what the daemon is, [docs/cuprate-android-spike.md](../docs/cuprate-android-spike.md) +for the cross-compile spike this plumbing comes from, +[MONERO_BINARIES.md](MONERO_BINARIES.md) for the `monero-wallet-rpc` executable +(still a child process — Cuprate has no wallet layer), and +[README.md](README.md#wallet-child-and-chain-sources-as-android-sees-them) for +how the Android wallet screen drives it. ## What changed in the build @@ -34,6 +37,10 @@ the request rather than only the task name: cargo ndk build for arm64-v8a features=cuprate-daemon api=26 ndk=28.2.13676358 ``` +There is no `-P` knob that turns the feature off. A build that silently dropped +it would ship an APK whose on-device node can only fail; `android-ci.yml` greps +the artifact (below) so that is not only a log line. + ## The link line RandomX is C++ and its aarch64 JIT calls `__clear_cache`, and `randomx-rs`'s build @@ -88,6 +95,10 @@ else: the `rust-version = "1.91"` MSRV are untouched, because the feature-off workspace does not need the bump and moving the MSRV is a separate decision. +`:sdk:preBuild` also runs `verifyDynamicLibc`: `libonionwire_sdk.so` must have +`libc.so` in `DT_NEEDED`. Linking the NDK's static `libc.a` instead null-derefs +inside `dlopen` on the first SDK call. + ## What ends up in the APK ``` @@ -103,8 +114,9 @@ lib/arm64-v8a/librandomx_rs-.so <- new, see below RandomX code is statically inside the SDK's own `.so` (its symbols and strings are there). `cargo-ndk` copies every cdylib the target directory produced into `jniLibs`, and `randomx-rs` also builds one. It is left in place rather than -filtered out: it is 1,122,296 bytes uncompressed / 387,996 deflated, and dropping -it would be a packaging rule that silently breaks the day something *does* link it. +filtered out: it is 1,122,296 bytes uncompressed / 387,996 deflated (sizes from +the feature-on CI run in the table below), and dropping it would be a packaging +rule that silently breaks the day something *does* link it. ## The CI gate @@ -125,11 +137,12 @@ above is the other half of the proof — request and artifact, separately checka * Selecting **On-device node (Cuprate)** stores `ChainChoice.InProcessCuprate` with an **empty** `monerod_datadir`, which the SDK resolves to - `$ONIONWIRE_HOME/chain` — the same directory a spawned `monerod` would use. Kotlin - never invents an absolute path. + `$ONIONWIRE_HOME/chain/{testnet,mainnet-pruned,mainnet-full}` from the stored + `mainnet` / `prune` flags — Kotlin never invents an absolute path. * `monero-wallet-rpc` is still required and still a subprocess: Start is gated on the bundled binary exactly as before, and an in-process node does not bundle - `arti`, so a `.onion` daemon is still refused. + `arti`, so a `.onion` daemon is still refused. Wallet RPC is loopback only. + Chain traffic stays off until the user opted into a wallet and chose a source. * The status line renders the core's words verbatim and grows a `node ` segment from `WalletChildStatus.node_state` for this source only. An unrecognised word is never rendered as ready. @@ -141,19 +154,29 @@ above is the other half of the proof — request and artifact, separately checka `node` segment) whenever either is non-zero: `0/0` means the last probe failed or the daemon is not up, so it is *unknown*, not `0%` — there is no percent, no progress bar and no ETA anywhere in the UI, and a zero target still prints as - `/0`. This is the **daemon's** chain height, not the wallet's scan height. The - same string is what the status row's screen-reader `contentDescription` carries - (`walletChildStatusDescription`), so the spoken row is never shorter than the - visible one. Cross-compiled and unit-tested on the JVM; still not device-proven. + `/0` when height is non-zero. This is the **daemon's** chain height, not the + wallet's scan height. The same string is what the status row's screen-reader + `contentDescription` carries (`walletChildStatusDescription`), so the spoken row + is never shorter than the visible one. Cross-compiled and unit-tested on the + JVM; still not device-proven. +* **What writes that snapshot on Android.** The wallet screen's 2 s loop + (`WireViewModel.refreshWalletChild`) calls `Wire.walletStatus()` — the cached + UniFFI read, no dial. The live probe `Wire.walletChildRefresh()` + (`Wire::wallet_child_refresh` in `crates/onionwire-sdk`) exists and is what + makes height/target move between calls; the TUI uses it. The APK poller on + this tree does not. See [README.md](README.md#what-the-apk-refresh-loop-actually-calls). * **Storage honesty.** The card shows the free space on the filesystem the fjall store grows into (`StatFs` on the app's data dir) and refuses Start below a - 3 GiB floor, or when that filesystem cannot be read at all. The floor is a - *floor*, not a sync estimate, and the doc comment says why: nothing in this stack + floor, or when that filesystem cannot be read at all. The floor is a *floor*, + not a sync estimate, and the doc comment says why: nothing in this stack exposes one — `WalletChildStatus` has no size field, and Cuprate's restricted RPC - reports a hardcoded 5 GiB `database_size` placeholder. + reports a hardcoded 5 GiB `database_size` placeholder. Floors in + `ui/WalletChildStatusText.kt`: 3 GiB testnet, 64 GiB mainnet-pruned, 280 GiB + mainnet-full. * **Pre-production warning**, above the Start button, in a sentence: - `CUPRATE_PREPRODUCTION_WARNING` — quoted user book, testnet-only, and Cuprate - issue #278, assertable in `WalletChildStatusTextTest`. Opt-in, never a default. + `CUPRATE_PREPRODUCTION_WARNING` — quoted user book, testnet-only / mainnet + unvalidated, and Cuprate issue #278, assertable in `WalletChildStatusTextTest`. + Opt-in, never a default. ## What it costs in CI @@ -164,6 +187,9 @@ the feature on. There are two feature-on regimes, and the second is the one a PR author feels — the first build after the feature lands compiles the whole cuprated graph, every later build is incremental against the same volume. +These figures are the **recorded** costs from the runs that landed the feature +(not re-measured on `fa0e4b2`): + | | feature off — `main` 773dacb, run 402 | feature on — PR #113 head 3860c3d (merged as 8626da2), run 412 | |---|---|---| | Gradle | `BUILD SUCCESSFUL in 6m 10s` | `BUILD SUCCESSFUL in 7m 14s` | @@ -182,29 +208,42 @@ cargo job on the runner. After that it settles to roughly **+2 minutes over the feature-off build** (7m 14s vs 6m 10s), because only this repo's own crates recompile. -Nothing needed mitigating: the job's `timeout-minutes` is 120, so even the 44-minute -first build fits with room to spare, and the volume grows to 5.6 G on a runner -filesystem with 37 G free (the `df -h` in the run log). The feature is **not** gated -on a build variant, a label or a manual dispatch — the release path builds exactly -what CI verifies. +`android-ci.yml`'s job `timeout-minutes` is **120**; `android-release.yml`'s +Android job is **90**. Even the 44-minute first build fits both with room to +spare, and the volume grew to 5.6 G on a runner filesystem with 37 G free (the +`df -h` in the run log). The feature is **not** gated on a build variant, a label +or a manual dispatch — the release path builds exactly what CI verifies. `android-ci.yml` prints `du -sh /cargo-target`, the length/method/deflated size of every native lib, and both artifact digests, and the workflow echoes `build_wall_clock_seconds`: the next person changing this graph reads the cost and the artifact's identity out of the run log rather than re-deriving either. -## Not verified +## What has not been proven The daemon was **not executed on a device or an emulator**. There is no -`arm64-v8a` AVD on the build host (the same gap `MONERO_BINARIES.md` records), and -no aarch64 Android sysroot to run it under `qemu-user`. What is proven: it -cross-compiles and links against the NDK's C++ runtime, the feature is in the -shipped `.so`, the artifact packages, and the Kotlin that drives it compiles and -passes its unit tests. What is not: that `cuprated` starts, opens its fjall store -and answers on loopback under Android's runtime — and, on top of that, Cuprate -itself is pre-production and testnet-only. +`arm64-v8a` AVD on the build host (the same gap [MONERO_BINARIES.md](MONERO_BINARIES.md) +records), and no aarch64 Android sysroot to run it under `qemu-user`. What is +proven: it cross-compiles and links against the NDK's C++ runtime, the feature is +in the shipped `.so`, the artifact packages, and the Kotlin that drives it +compiles and passes its unit tests. What is not: -To close the gap, on an arm64 device or a software-emulated arm64 AVD: +* that `cuprated` starts, opens its fjall store and answers on loopback under + Android's runtime; +* **mainnet remains unvalidated.** Cuprate itself is pre-production and its own + user book says not to use `cuprated` for serious purposes. The Android screen + can store a mainnet-pruned or mainnet-full mode; that is not a claim this build + has run either. Core still surfaces `testnet only — mainnet is unvalidated` + (`cuprate::TESTNET_ONLY`); +* **a daemon that dies after the wallet child came up cannot be reported + `exited`.** The in-process node is a value this app owns, not a process with a + pid. The SDK derives `node_state` from the wallet-child state + (`crates/onionwire-sdk/src/lib.rs`, `node_state`). If the daemon dies after its + wallet child is up, the chain probe fails and the state stays `syncing`. It is + never reported `ready` from that failure. `exited` still means what it says: + the `monero-wallet-rpc` child is gone. + +To close the device gap, on an arm64 device or a software-emulated arm64 AVD: ```bash sdkmanager "system-images;android-35;google_apis;arm64-v8a" @@ -217,4 +256,6 @@ then unlock the node, open Wallet, tap **On-device node (Cuprate)**, read the warning, press **Start wallet**, and watch the status line for `connecting → syncing · in-process node · node starting → node syncing`. A wallet balance needs the chain synced, which on a phone is a long wait — the status line -is the thing to watch, not the balance. +is the thing to watch, not the balance. On this tree the APK loop will not itself +refresh height from the daemon; a live probe is a separate SDK call the TUI +makes and the Android poller does not. diff --git a/android/MONERO_BINARIES.md b/android/MONERO_BINARIES.md index c9f4185..4409049 100644 --- a/android/MONERO_BINARIES.md +++ b/android/MONERO_BINARIES.md @@ -1,22 +1,28 @@ # Bundled native executables (`jniLibs`) The wallet screen starts an **app-owned `monero-wallet-rpc` child** (issue #107, -`src/wallet_child.rs`). Monero ships no Android binaries, so this repository -carries one, built here. +[`src/wallet_child.rs`](../src/wallet_child.rs)). Monero ships no Android +binaries, so this repository carries one, built here. | | | |---|---| | File in the tree | `android/app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so` | | Bytes | 19 954 224 (stripped) | | sha256 | `d9126788030ecd1ccdb40c7764e66e9a14d158a147ad335b256f0577681b5ad4` | -| Format | `ELF 64-bit LSB shared object, ARM aarch64, dynamically linked, interpreter /system/bin/linker64, for Android 21, built by NDK r17b` | +| Format | `ELF 64-bit LSB shared object, ARM aarch64, version 1 (SYSV), dynamically linked, interpreter /system/bin/linker64, for Android 21, built by NDK r17b (4828580), stripped` | | Needed libs | `libc.so`, `libm.so`, `libdl.so` — everything else is static | | Source | `https://github.com/monero-project/monero` | | Tag | `v0.18.4.4` | -| Commit | `516e5355a103a2bf0b7e10328ebcaa2945019445` | +| Commit | `516e5355a103a2bf0b7e10328ebcaa2945019445` (peeled annotated tag) | | Reproduce with | `scripts/build-monero-wallet-rpc-android.sh` | | Verified by | `android/monero-binaries.sha256`, checked by `scripts/build-android-local.sh` on every build (local and CI) | +Re-checked on this tree (`fa0e4b2`): `stat -c %s` is 19954224; `sha256sum` of the +blob equals the hash above and equals the line in `android/monero-binaries.sha256` +(that file's path is relative to `android/`: +`app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so`). `readelf -d` NEEDED is +`libdl.so`, `libm.so`, `libc.so`. + Only `arm64-v8a` is built. `-Ponionwire.abis=x86_64` produces an APK with no wallet binary in it — the screen says so (`NO_WALLET_RPC_MESSAGE`) instead of offering a Start that cannot work. @@ -28,8 +34,10 @@ cross-compile path — `contrib/depends` (boost, openssl, libunbound, libzmq, libsodium, ncurses, readline, libiconv, expat for `aarch64-linux-android`) plus the `toolchain.cmake` it emits — and then builds the single CMake target `wallet_rpc_server`. It takes ~40 min on 12 cores and needs ~15 GB of scratch -space. It is **not** part of the CI path: CI here runs on a Raspberry Pi and the -Gradle build is already ~9 minutes. CI verifies the committed bytes instead. +space. It is **not** part of the CI path: the Android Gradle jobs already run +on `docker-amd64` for ~9 minutes with warm volumes, and rebuilding Monero's C++ +tree is a separate 30–45 min host job. CI verifies the committed bytes instead +(`sha256sum -c` plus the APK-entry check in `scripts/build-android-local.sh`). Four things about the build are worth writing down, because each one is a failure that looks like something else: @@ -83,6 +91,11 @@ shipped blob** and the thing CI re-verifies — not a reproducible-build assertion. If you rebuild, update both `android/monero-binaries.sha256` and this table in the same commit, and say what changed in the tag or the toolchain. +The reproduce script pins **the tag** (`MONERO_TAG=v0.18.4.4`, shallow clone). +The commit in the table is the peeled object of that annotated tag on GitHub, +recorded here so a rebuild can be compared; it is not a second pin in the +script. + ## Why it is a `jniLibs` `.so` and not an asset Since Android 10 (API 29) an app may not `exec()` a file in its own data @@ -108,6 +121,8 @@ AGP's strip pass cannot rewrite the bytes that CI verifies. Cost: the release APK grows from ~9 MB to ~28 MB (the binary is deflate-stored at 6.9 MB) and installs ~20 MB into the app's native library directory. +(Those packaging sizes are the original measurement when the blob landed; the +committed blob's **uncompressed** size is the 19 954 224 bytes above.) ## `arti` is NOT bundled @@ -116,8 +131,7 @@ daemon, and `ChildConfig::validate` requires a non-empty `arti_bin` for any chain source that is not receive-only. There is no `arti` executable in this build, and producing one (a standalone `arti` binary for `aarch64-linux-android`, from a crate the Rust side does not currently build as -a bin) is a follow-up, not something this card could do without editing -`Cargo.toml`/`crates/**`. +a bin) is a follow-up, not something this document can invent. What the app does about it, honestly: @@ -133,9 +147,9 @@ So today: **loopback and clearnet daemons work; `.onion` daemons do not.** ## Verification in CI -`.forgejo/workflows/android-ci.yml` builds the APK on every `android/**` PR and -`scripts/build-android-local.sh` does the checking, so both CI jobs and local -builds get it: +`.forgejo/workflows/android-ci.yml` (and `android-release.yml`) build the APK on +`docker-amd64` and `scripts/build-android-local.sh` does the checking, so both +CI jobs and local builds get it: 1. before Gradle, `sha256sum -c android/monero-binaries.sha256` against the committed blob; @@ -171,8 +185,7 @@ at the arti notice above. The third chain source — Cuprate's chain daemon running inside the OnionWire process — is a **linked feature of the SDK's `.so`**, not a `jniLibs` executable, -so it has its own record: `android/CUPRATE_DAEMON.md` (feature wiring, the NDK C++ -/ compiler-rt link line, the CI check that greps the shipped `.so` for a -cuprated-only string, and what has not been verified). `monero-wallet-rpc` above -stays a child process for it — Cuprate has no wallet layer. - +so it has its own record: [CUPRATE_DAEMON.md](CUPRATE_DAEMON.md) (feature wiring, +the NDK C++ / compiler-rt link line, the CI check that greps the shipped `.so` +for a cuprated-only string, and what has not been verified). `monero-wallet-rpc` +above stays a child process for it — Cuprate has no wallet layer. diff --git a/android/README.md b/android/README.md index 31d3980..6d58f6a 100644 --- a/android/README.md +++ b/android/README.md @@ -11,6 +11,14 @@ The Linux TUI in the repository root is a **separate product** with a separate Cargo workspace. Nothing here turns it into a WebView, and nothing here imports its TUI code. Same wire protocol: [docs/PROTOCOL.md](../docs/PROTOCOL.md). +Companion records (not duplicated here): + +* in-process chain daemon in the APK — [CUPRATE_DAEMON.md](CUPRATE_DAEMON.md) +* bundled `monero-wallet-rpc` blob — [MONERO_BINARIES.md](MONERO_BINARIES.md) +* wallet / chain-source behaviour (core + SDK) — [docs/WALLET.md](../docs/WALLET.md) +* consuming the AAR — [crates/onionwire-sdk/README.md](../crates/onionwire-sdk/README.md) +* how a maintainer actually cuts a release — [docs/RELEASING.md](../docs/RELEASING.md) + ## Requirements * JDK 17+ (built and tested on JDK 21) @@ -36,7 +44,8 @@ cd android ``` The Rust cross-compile and the UniFFI Kotlin bindings are wired into the Gradle -tasks — there is no manual codegen step. `:sdk:preBuild` depends on them. +tasks — there is no manual codegen step. `:sdk:preBuild` depends on +`cargoBuildAndroid`, `uniffiBindgen`, and `verifyDynamicLibc`. Emulator / x86_64 slice: @@ -44,13 +53,20 @@ Emulator / x86_64 slice: ./gradlew :app:assembleDebug -Ponionwire.abis=arm64-v8a,x86_64 ``` +That extra ABI does **not** ship `libmonerowalletrpc.so` for x86_64. The wallet +screen says so (`NO_WALLET_RPC_MESSAGE`) instead of offering a Start that cannot +work. See [MONERO_BINARIES.md](MONERO_BINARIES.md). + Or from the repo root, with checksums and an optional publish step: ```bash scripts/build-android-local.sh # -> dist/onionwire--android-arm64-v8a.apk -PUBLISH_TAG=v0.1.0 scripts/build-android-local.sh +PUBLISH_TAG=v0.14.0 scripts/build-android-local.sh ``` +The script re-verifies `android/monero-binaries.sha256` before Gradle, then +again against the bytes inside the APK. It does not create tags. + ## Decisions you should know about ### `minSdk = 26` (Android 8.0) @@ -79,12 +95,24 @@ readelf -l android/sdk/build/rustJniLibs/arm64-v8a/libonionwire_sdk.so | grep LO ### Permissions -`INTERNET` only, declared at first launch. No camera (invites are pasted, not -scanned), no contacts, no storage permission — the data directory is -`context.filesDir`, which is already app-private. There is **no** -`FOREGROUND_SERVICE` and no keep-alive notification in v1: the node lives only -while the process does, and the UI says so. Adding one is a product decision -(battery, Play's FGS type declarations), not a silent fix. +`INTERNET` is the only permission requested at first launch. No camera (invites +are pasted, not scanned), no contacts, no storage permission — the data +directory is `context.filesDir`, which is already app-private. + +The node is **not** process-lifetime-only. After unlock, `KeepAliveService` is +a foreground service (`specialUse`, not `dataSync`) with an ongoing +notification so the onion stays published across Doze and backgrounding. The +manifest therefore also declares: + +* `FOREGROUND_SERVICE` +* `FOREGROUND_SERVICE_SPECIAL_USE` +* `POST_NOTIFICATIONS` (API 33+; denial hides the drawer notification, it does + not stop the service) + +`NodeHost` owns the single `Wire` handle. The service never does. Lock, or the +notification's Stop action, drops the keep-alive anchor; the node stays up +only while another owner (the UI) still holds it. `START_NOT_STICKY`: a +restarted empty service would show "reachable" over a dead onion. ### Data at rest @@ -148,9 +176,11 @@ Release APKs are signed with a **repo-owned keystore**, not the debug key. present (`~/.android/onionwire-release.jks` + `.env`, mode 600). Local and CI APKs then verify as the same cert and can upgrade in place. * If the env file is missing, Gradle **warns** and signs with the debug - keystore so a laptop build still installs. CI sets + keystore so a laptop build still installs. CI's `android-release.yml` sets `ONIONWIRE_REQUIRE_RELEASE_KEY=true` and **fails closed** instead — a per-machine debug key would make every CI APK uninstallable over the last. + `android-ci.yml` deliberately does **not** set that: it is a verification + build and `apksigner` reporting the debug cert there is expected. * Never commit a keystore, password, or `android/local.properties`. This is not a Play upload key; nothing here should be uploaded to Play. @@ -162,23 +192,148 @@ path and an on-device test of the JNI surface is how you ship an `UnsatisfiedLinkError` nobody can read. Turn it on together with crash deobfuscation, not before. -## CI +## Wallet child and chain sources (as Android sees them) -`.forgejo/workflows/android-release.yml` runs on `docker-amd64` (T480 dind). -The job image is `node:20-bullseye` (EOL) — **do not apt-get there**. The -toolchain runs in a sibling `debian:bookworm` container -(stdin-tar + `docker cp`, same pattern as the Rust CI job). -Any push to `main` that touches Android **sources or build config** -(`android/app/**`, `android/sdk/**`, Gradle files — not `android/README.md`) -workflow) builds `onionwire--android-arm64-v8a.apk` and -`onionwire-sdk-.aar`, verifies them, and attaches them to the Forgejo -release for that tag. Version is the latest `v*.*.*` tag plus patch, or -**v0.1.0** when there are no tags. `versionName` matches the tag; -`versionCode` is `major*10000 + minor*100 + patch` (so 0.1.0 → 100). +Chain traffic is **off** until the user opens Wallet, picks a source, and +presses Start. Receive-only is the default: no `monero-wallet-rpc` child, no +daemon, no P2P. -`workflow_dispatch` with `dry_run=true` builds and checksums without creating -a tag or publishing. `scripts/build-android-local.sh` remains the offline -fallback; it does not create tags. +The app owns `monero-wallet-rpc` (issue #107). It is still a **child process**, +exec'd from `applicationInfo.nativeLibraryDir/libmonerowalletrpc.so`. Cuprate +has no wallet layer — an in-process node does not replace that binary. + +Sources the screen offers: + +1. **Receive-only** — no child, no chain. +2. **A daemon address you type** — loopback or clearnet. Wallet RPC itself is + loopback only. A `.onion` host is refused while `libarti.so` is absent + (`ONION_NEEDS_ARTI_NOTICE`); this APK does not bundle `arti`. +3. **On-device node (Cuprate)** — opt-in. Selecting it stores + `ChainChoice.InProcessCuprate` with an empty `monerod_datadir`, which the + SDK resolves to `$ONIONWIRE_HOME/chain`. Kotlin never invents an absolute + path. The pre-production warning (`CUPRATE_PREPRODUCTION_WARNING`) sits + **above Start**, not after. The screen can store testnet, mainnet-pruned, or + mainnet-full (and applies the matching storage floor); **mainnet remains + unvalidated** and the warning says so. Cross-compiled is not device-proven. + See [CUPRATE_DAEMON.md](CUPRATE_DAEMON.md). + +Start is gated on the bundled wallet-rpc binary, on the storage floor for the +chosen Cuprate mode, and on the `.onion`/arti check. The floors are floors, not +sync estimates — nothing in this stack exposes a chain size: + +| Mode | Floor | +|---|---| +| testnet | 3 GiB | +| mainnet pruned | 64 GiB | +| mainnet full | 280 GiB | + +Unreadable free space (`StatFs` failed) is fail-closed: Start stays blocked. + +### Status line + +`ui/WalletChildStatusText.kt` is the pure model. The line renders the core's +words verbatim (`off` / `connecting` / `syncing` / `ready` / `exited`), then +the chain-source label, then — for the in-process source only — `node ` +from `WalletChildStatus.node_state`. An unrecognised word is never rendered as +ready. + +When the last probe reported a non-zero height or target, the line grows +` · sync h/t`. That is the **daemon's** chain height, not the wallet's scan +height. `0/0` is omitted (unknown), not printed as 0%. There is **no +percentage, no progress bar, and no ETA** anywhere in the UI. The same string +is the row's screen-reader `contentDescription`. + +Honest limit of the in-process node word: a daemon that dies *after* the wallet +child came up cannot be reported `exited` — there is no separate pid for the +in-process daemon, the chain probe fails, and the state stays `syncing`. +`exited` still means the `monero-wallet-rpc` child is gone. Details: +[CUPRATE_DAEMON.md](CUPRATE_DAEMON.md#what-has-not-been-proven). + +### What the APK refresh loop actually calls + +`WireViewModel.openWalletChild()` polls every 2 s +(`WALLET_CHILD_TICK_MS = 2_000`). Each tick is `Wire.walletStatus()` — the +cached, non-dialing UniFFI read (`Wire::wallet_status`). It never spawns and +it never probes the daemon, so `sync h/t` only moves when something else +wrote a fresh snapshot (start, a previous live probe). + +The SDK also exposes `Wire.walletChildRefresh()` (`Wire::wallet_child_refresh`): +a live probe of the loopback wallet RPC, and of the local daemon's `get_info` +when that RPC does not answer. The TUI uses it. **This APK's poller does not.** +Do not read the moving `sync h/t` docs in [docs/WALLET.md](../docs/WALLET.md) +as a description of the Android loop on this tree. + +## CI and releases + +A merge to `main` does **not** publish an APK. Neither does a tag push. +Releases are manual and batched: two dispatches. Full procedure: +[docs/RELEASING.md](../docs/RELEASING.md). + +### `android-ci.yml` (verification, not a release) + +Runs on `docker-amd64` (T480 dind) for every `push`/`pull_request` whose paths +include `android/**`, `src/**`, `crates/**`, `Cargo.toml`, `Cargo.lock`, +`scripts/build-android-local.sh`, or the workflow itself — plus +`workflow_dispatch`. Job image is `node:20-bullseye` (EOL) — **do not apt-get +there**. The toolchain runs in a sibling `debian:bookworm` container +(stdin-tar + `docker cp`). Both Android workflows install `cmake` in that +container (RandomX). + +It calls `scripts/build-android-local.sh` with the **debug** key +(`ONIONWIRE_REQUIRE_RELEASE_KEY` unset). Nothing is published. After the APK +is built it greps `lib/arm64-v8a/libonionwire_sdk.so` for `target_max_memory` +and **fails** if that cuprated-only string is missing. + +### `android-release.yml` (the APK that lands on a tag) + +`on:` is `workflow_dispatch` (and a declared `workflow_call` that this Forgejo +10.0.3 instance cannot invoke). **No `push` trigger.** Inputs: + +| Input | Default | Meaning | +|---|---|---| +| `tag` | empty | Existing tag to check out, build, and attach. | +| `dry_run` | `false` | Build and checksum; skip the Pi publish job. | + +Operator path, after `release.yml` has minted the tag (`dry_run=true` on that +workflow first): + +1. Actions → **android-release** → Run workflow, `tag=vX.Y.Z` (the tag core + just created), `dry_run=false`. +2. The Android job **checks out that tag** (`ref:` is the tag, not `main`) and + stamps `versionName` / `versionCode` from it. +3. `versionCode` is `major*10000 + minor*100 + patch` (so 0.14.0 → 1400). +4. Publish is a second job on the Pi runner (`docker`). It attaches + `onionwire--android-arm64-v8a.apk`, `onionwire-sdk-.aar`, + and both `.sha256` files to **that same tag**. + +The APK is built from **the tag's tree**. Building from `main` and stamping a +tag you did not check out is how you ship a binary that does not match the +tag. + +**Empty `tag` is the foot-gun.** Checkout then falls back to `github.sha` +(usually `main` HEAD). Version is *not* "latest `v*.*.*` plus patch" as a +rule: + +* no tags at all → `0.1.0`; +* latest `v*.*.*` release is **missing** the Android APK (or the job cannot + inspect the release) → **join** that version: same `versionName` restamped + onto whatever tree was checked out. Android will refuse to install that APK + over an already-installed build of the same `versionName`/`versionCode`; +* latest tag already has an Android APK → `patch+1` of that version, still + built from `github.sha`, and this workflow may then **create** that new tag + at publish time if it does not exist. + +Do not dispatch `android-release` with an empty `tag` to ship a release. Core +owns minting (`release.yml`, default `bump=minor`). This workflow attaches. + +`workflow_dispatch` with `dry_run=true` builds and checksums without +publishing. `scripts/build-android-local.sh` remains the offline fallback; it +does not create tags. + +The Android job image / bookworm-container story is the same as `android-ci.yml`. +The cuprated graph is built with `RUST_TOOLCHAIN=1.98` here (workspace MSRV +stays 1.91). Job timeout is **90** minutes on `android-release.yml` and **120** +on `android-ci.yml`. ## Layout @@ -187,17 +342,38 @@ android/ settings.gradle.kts build.gradle.kts # plugin aliases only gradle/libs.versions.toml # version catalog + gradle/wrapper/ + monero-binaries.sha256 # provenance of the bundled wallet-rpc blob + CUPRATE_DAEMON.md + MONERO_BINARIES.md sdk/ # -> AAR build.gradle.kts # cargo-ndk + uniffi-bindgen wiring consumer-rules.pro src/main/AndroidManifest.xml app/ # -> APK build.gradle.kts + src/main/AndroidManifest.xml src/main/java/com/siriusdevops/onionwire/ MainActivity.kt # NavHost - WireViewModel.kt # owns the single Wire node + WireViewModel.kt # UI-side Wire handle; wallet-child poller crypto/ # Keystore-wrapped store passphrase + keepalive/ # NodeHost, KeepAliveService, policy, lifetime + wallet/ # ChainStorage, WalletChildBinaries ui/ # Compose screens (M3) - src/test/ # JVM tests (envelope, store, invite flow) + WalletScreen.kt + WalletChildStatusText.kt + ChatScreen.kt + RosterScreen.kt + InviteScreens.kt + InviteAddFlow.kt + OutboxDetail.kt + MessageDelivery.kt + UnlockScreen.kt + UnlockSubmit.kt + RotateScreen.kt + Insets.kt + Theme.kt + src/test/ # JVM: envelope, store, invite, outbox, keepalive, wallet line src/androidTest/ # device-only: AndroidKeyStore + src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so ``` From 0a8105584fde8bd2604d017716a60fa20c477a5b Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 20 Sep 2026 00:56:08 -0400 Subject: [PATCH 03/78] docs(android): the APK poller now calls wallet_child_refresh #135 merged against fa0e4b2-era docs that said the loop was still wallet_status. #134 already landed: first paint is cached, every later tick is Wire::wallet_child_refresh. --- android/CUPRATE_DAEMON.md | 17 ++++++++--------- android/README.md | 31 ++++++++++++++++++++----------- 2 files changed, 28 insertions(+), 20 deletions(-) diff --git a/android/CUPRATE_DAEMON.md b/android/CUPRATE_DAEMON.md index e3b422b..8689f2a 100644 --- a/android/CUPRATE_DAEMON.md +++ b/android/CUPRATE_DAEMON.md @@ -159,12 +159,12 @@ above is the other half of the proof — request and artifact, separately checka `contentDescription` carries (`walletChildStatusDescription`), so the spoken row is never shorter than the visible one. Cross-compiled and unit-tested on the JVM; still not device-proven. -* **What writes that snapshot on Android.** The wallet screen's 2 s loop - (`WireViewModel.refreshWalletChild`) calls `Wire.walletStatus()` — the cached - UniFFI read, no dial. The live probe `Wire.walletChildRefresh()` - (`Wire::wallet_child_refresh` in `crates/onionwire-sdk`) exists and is what - makes height/target move between calls; the TUI uses it. The APK poller on - this tree does not. See [README.md](README.md#what-the-apk-refresh-loop-actually-calls). +* **What writes that snapshot on Android.** The wallet screen's loop + (`WireViewModel.openWalletChild` → `walletChildRefreshLoop`) does one cached + `Wire.walletStatus()` paint, then every 2 s a live + `Wire.walletChildRefresh()` (`Wire::wallet_child_refresh`). The live call is + what makes height/target move between ticks; it never spawns. See + [README.md](README.md#what-the-apk-refresh-loop-actually-calls). * **Storage honesty.** The card shows the free space on the filesystem the fjall store grows into (`StatFs` on the app's data dir) and refuses Start below a floor, or when that filesystem cannot be read at all. The floor is a *floor*, @@ -256,6 +256,5 @@ then unlock the node, open Wallet, tap **On-device node (Cuprate)**, read the warning, press **Start wallet**, and watch the status line for `connecting → syncing · in-process node · node starting → node syncing`. A wallet balance needs the chain synced, which on a phone is a long wait — the status line -is the thing to watch, not the balance. On this tree the APK loop will not itself -refresh height from the daemon; a live probe is a separate SDK call the TUI -makes and the Android poller does not. +is the thing to watch, not the balance. After the first cached paint, the APK +loop probes live every 2 s, so `sync h/t` should move once the daemon answers. diff --git a/android/README.md b/android/README.md index 6d58f6a..c96aaa4 100644 --- a/android/README.md +++ b/android/README.md @@ -251,17 +251,26 @@ in-process daemon, the chain probe fails, and the state stays `syncing`. ### What the APK refresh loop actually calls -`WireViewModel.openWalletChild()` polls every 2 s -(`WALLET_CHILD_TICK_MS = 2_000`). Each tick is `Wire.walletStatus()` — the -cached, non-dialing UniFFI read (`Wire::wallet_status`). It never spawns and -it never probes the daemon, so `sync h/t` only moves when something else -wrote a fresh snapshot (start, a previous live probe). +`WireViewModel.openWalletChild()` runs `walletChildRefreshLoop` with a 2 s +tick (`WALLET_CHILD_TICK_MS = 2_000`): -The SDK also exposes `Wire.walletChildRefresh()` (`Wire::wallet_child_refresh`): -a live probe of the loopback wallet RPC, and of the local daemon's `get_info` -when that RPC does not answer. The TUI uses it. **This APK's poller does not.** -Do not read the moving `sync h/t` docs in [docs/WALLET.md](../docs/WALLET.md) -as a description of the Android loop on this tree. +1. **First paint** — `paintWalletChildCached()` → `Wire.walletStatus()` + (`Wire::wallet_status`). Cached, no dial, so the screen has a record + while the first probe is still in flight. +2. **Every tick after that** — `refreshWalletChild()` → + `Wire.walletChildRefresh()` (`Wire::wallet_child_refresh`). That dials + the child's loopback wallet RPC, and the configured local daemon's + `get_info` when the wallet RPC does not answer, which is what makes + `sync h/t` move without another Start. It never spawns a child. With no + live child the core short-circuits to the cached `off` / `exited` + snapshot, so this cannot invent `ready`. + +The loop suspends on each read before it sleeps: a probe slower than 2 s +delays the next tick instead of overlapping it. Do not run two concurrent +`wallet_child_refresh` calls against one child. + +See [docs/WALLET.md](../docs/WALLET.md) (Android / SDK) for the same two +methods as the UniFFI surface. ## CI and releases @@ -373,7 +382,7 @@ android/ RotateScreen.kt Insets.kt Theme.kt - src/test/ # JVM: envelope, store, invite, outbox, keepalive, wallet line + src/test/ # JVM: envelope, store, invite, outbox, keepalive, wallet line, refresh loop src/androidTest/ # device-only: AndroidKeyStore src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so ``` From cb411da813aecba8a081fef8f885b03191136a22 Mon Sep 17 00:00:00 2001 From: sirius Date: Sun, 20 Sep 2026 09:17:05 -0400 Subject: [PATCH 04/78] wallet: answer the Digest challenge on the connection that issued it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the `http_server_auth` lives inside `http_custom_handler`, which is created per connection, so its nonce starts empty and any request without a valid `Authorization` field mints a fresh one. The client opened a *second* connection for the authenticated retry, presenting a nonce that socket never issued — so a real wallet RPC answered 401 forever, however correct the login was. That is the `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the canned mocks replayed the challenge on any socket, so they stayed green. - `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry, no `Connection: close` on the challenge (epee closes the socket with the 401 when the request asks for it), `read_one_response` honouring `Content-Length` (a keep-alive response never ends in EOF; with no length the body ends at EOF, which is what keeps the 1 MiB cap meaningful for an open RPC). - A 401 after our *own* challenge now reads: the login does not match the child's `--rpc-login`. - Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce: `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one connection, and a nonce presented on another connection is refused. - `docs/WALLET.md`: what a 401 means and why it is not the flow. Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`, `--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401 Unauthorized`; fixed tree → `connected: true` with the wallet's real address. --- docs/WALLET.md | 8 ++ src/node.rs | 159 ++++++++++++++-------------- src/wallet.rs | 158 +++++++++++++++++++++------- tests/wallet.rs | 275 ++++++++++++++++++++++++++++++++++++++++-------- 4 files changed, 437 insertions(+), 163 deletions(-) diff --git a/docs/WALLET.md b/docs/WALLET.md index 6e431e2..054c48c 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -283,6 +283,14 @@ OnionWire refuses an RPC that answers HTTP 200 without a Digest challenge, and refuses URLs without credentials. Prefer `ONIONWIRE_WALLET_RPC_LOGIN` over userinfo in the URL. Do not log the password. +`monero-wallet-rpc` mints its Digest nonce **per TCP connection** (epee's +`http_custom_handler` owns the auth state), so the challenge and the +authenticated retry have to ride the same socket — a retry on a fresh connection +is refused with 401 no matter how correct the login is. OnionWire does exactly +that. A `wallet RPC HTTP HTTP/1.1 401 Unauthorized` status therefore means one +thing: the login does not match the child's `--rpc-login`. Regenerate the child +(and its sealed creds) rather than retrying. + ## The spend-authority warning An OnionWire instance pointed at a **spend-capable** `monero-wallet-rpc` is a diff --git a/src/node.rs b/src/node.rs index 15e7220..fcc8015 100644 --- a/src/node.rs +++ b/src/node.rs @@ -2205,59 +2205,80 @@ mod tests { .to_string() } - /// A wallet child that clears the Digest challenge and answers one - /// `transfer` — the two-connection dance `tests/wallet.rs` mocks. + /// Serve a mock wallet RPC whose Digest state is **per connection**, the way + /// epee does it: the nonce is minted by the socket that answered 401 and is + /// valid nowhere else, so a client that retries on a fresh socket is refused + /// forever. `reply` maps a request to its JSON-RPC body. The socket closes + /// after an authenticated reply — the client asks for `Connection: close` + /// there and the real server honours it. + async fn serve_mock_rpc( + listener: tokio::net::TcpListener, + reply: Arc String + Send + Sync>, + ) { + use std::sync::atomic::{AtomicUsize, Ordering}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + static NEXT_NONCE: AtomicUsize = AtomicUsize::new(1); + + while let Ok((mut sock, _)) = listener.accept().await { + let reply = Arc::clone(&reply); + tokio::spawn(async move { + let mut nonce: Option = None; + loop { + let mut buf = vec![0u8; 8192]; + let Ok(n) = sock.read(&mut buf).await else { + return; + }; + if n == 0 { + return; + } + let req = String::from_utf8_lossy(&buf[..n]).to_string(); + let answered = req.contains("Authorization:") + && nonce.as_deref().is_some_and(|held| req.contains(held)); + if !answered { + let fresh = format!("nonce{}", NEXT_NONCE.fetch_add(1, Ordering::Relaxed)); + let challenge = format!( + "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"{fresh}\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\n\r\n" + ); + if sock.write_all(challenge.as_bytes()).await.is_err() { + return; + } + nonce = Some(fresh); + continue; + } + let body = reply(&req); + let ok = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ); + let _ = sock.write_all(ok.as_bytes()).await; + return; + } + }); + } + } + /// A loopback wallet RPC that answers what the tip path actually asks for: /// a digest challenge, then a synced `get_info` for the readiness gate and /// `tx_hash` for the transfer. The old single-answer mock stopped covering /// the path when `Wallet::transfer` started probing the chain tip first — /// it answered `tx_hash` to `get_info` and every tip was refused as unsynced. async fn mock_wallet() -> Wallet { - use tokio::io::{AsyncReadExt, AsyncWriteExt}; - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await .expect("bind mock wallet"); let port = listener.local_addr().expect("mock wallet addr").port(); - tokio::spawn(async move { - // Every call starts unauthenticated, so every call gets one - // challenge — the client retries each request with digest auth. - for _ in 0..8 { - let Ok((mut sock, _)) = listener.accept().await else { - return; - }; - let mut buf = vec![0u8; 8192]; - let Ok(n) = sock.read(&mut buf).await else { - return; - }; - let req = String::from_utf8_lossy(&buf[..n]).to_string(); - if !req.contains("Authorization:") { - let _ = sock - .write_all( - b"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", - ) - .await; - continue; - } - let body = if req.contains("get_info") { - r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"# - } else { - r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"# - }; - let _ = sock - .write_all( - format!( - "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - ) - .as_bytes(), - ) - .await; + let reply: Arc String + Send + Sync> = Arc::new(|req: &str| { + if req.contains("get_info") { + r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"# + .to_string() + } else { + r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#.to_string() } }); + tokio::spawn(serve_mock_rpc(listener, reply)); Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") } - /// The payer of a tip must see it in their own chat: `receipt_chat_line` is /// the recipient's view of the frame that arrived, `tip_chat_line` is what /// the sender just spent. @@ -2522,60 +2543,34 @@ mod tests { } } + /// A loopback wallet RPC that answers the *status* probe: a digest + /// challenge, then `get_address` / `get_balance` / `get_info`, with the + /// chain numbers a syncing daemon reports. [`mock_wallet`] above answers the + /// *transfer* path; this one answers a refresh, which never transfers. /// A loopback wallet RPC that answers the *status* probe: a digest /// challenge, then `get_address` / `get_balance` / `get_info`, with the /// chain numbers a syncing daemon reports. [`mock_wallet`] above answers the /// *transfer* path; this one answers a refresh, which never transfers. async fn mock_syncing_wallet(height: u64, target: u64) -> Wallet { - use tokio::io::{AsyncReadExt, AsyncWriteExt}; - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await .expect("bind mock wallet"); let port = listener.local_addr().expect("mock wallet addr").port(); - tokio::spawn(async move { - // Every call starts unauthenticated, so every call gets one - // challenge — the client retries each request with digest auth. - for _ in 0..8 { - let Ok((mut sock, _)) = listener.accept().await else { - return; - }; - let mut buf = vec![0u8; 8192]; - let Ok(n) = sock.read(&mut buf).await else { - return; - }; - let req = String::from_utf8_lossy(&buf[..n]).to_string(); - if !req.contains("Authorization:") { - let _ = sock - .write_all( - b"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", - ) - .await; - continue; - } - let body = if req.contains("get_info") { - format!( - r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target},"synchronized":true}}}}"# - ) - } else if req.contains("get_address") { - format!( - r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#, - addr = xmr_addr() - ) - } else { - r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0"}}"#.to_string() - }; - let _ = sock - .write_all( - format!( - "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - ) - .as_bytes(), - ) - .await; + let reply: Arc String + Send + Sync> = Arc::new(move |req: &str| { + if req.contains("get_info") { + format!( + r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target},"synchronized":true}}}}"# + ) + } else if req.contains("get_address") { + format!( + r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#, + addr = xmr_addr() + ) + } else { + r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0"}}"#.to_string() } }); + tokio::spawn(serve_mock_rpc(listener, reply)); Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") } diff --git a/src/wallet.rs b/src/wallet.rs index 226dab0..7195691 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -848,26 +848,21 @@ impl Wallet { "params": params, }) .to_string(); - let raw = post_timeout(ep, &build_req(ep, &body, None), budget).await?; + let (challenged, raw) = post_digest(ep, &body, budget).await?; let status = http_status(&raw).unwrap_or(0); - if status == 200 { + if status == 401 { + // A digest built from *this* connection's own challenge was + // refused, so the login is wrong, not the flow. + return Err(Error( + "wallet RPC digest rejected (HTTP 401) — the login does not match the child's --rpc-login" + .into(), + )); + } + if !challenged && status == 200 { return Err(Error( "wallet RPC requires digest auth (open RPC refused)".into(), )); } - if status != 401 { - return parse_json_rpc(&raw); - } - let challenge = www_authenticate(&raw).ok_or_else(|| { - Error("wallet RPC digest required (--rpc-login / HTTP Digest)".into()) - })?; - if !challenge.trim().to_ascii_lowercase().starts_with("digest") { - return Err(Error( - "wallet RPC digest required (--rpc-login / HTTP Digest)".into(), - )); - } - let auth = digest_authorization(ep, &challenge)?; - let raw = post_timeout(ep, &build_req(ep, &body, Some(&auth)), budget).await?; parse_json_rpc(&raw) } } @@ -996,19 +991,65 @@ fn host_header(host: &str, port: u16) -> String { const MAX_RPC_BYTES: usize = 1024 * 1024; -async fn post_timeout(ep: &Endpoint, req: &str, budget: Duration) -> Result> { - tokio::time::timeout(budget, http_post(ep, req.as_bytes())) +/// One loopback connection: ask for the digest challenge, answer it, and hand +/// back `(was_challenged, final_response)`. +/// +/// The retry has to ride the **same socket** as the challenge. epee owns its +/// digest state per connection — `http_custom_handler` holds the +/// `http_server_auth`, whose session starts with an empty nonce and counter 0, +/// and any request without a valid `Authorization` field makes it mint a fresh +/// nonce. A retry that opens a new socket presents a nonce that connection never +/// issued, so `monero-wallet-rpc` answers 401 again, permanently. That is the +/// 401 the TUI and Android showed against a real wallet RPC while a canned mock +/// (which replays the challenge on any socket) stayed green. +async fn post_digest(ep: &Endpoint, body: &str, budget: Duration) -> Result<(bool, Vec)> { + tokio::time::timeout(budget, http_digest(ep, body)) .await .map_err(|_| Error("wallet RPC timed out".into()))? } -fn build_req(ep: &Endpoint, body: &str, authorization: Option<&str>) -> String { +async fn http_digest(ep: &Endpoint, body: &str) -> Result<(bool, Vec)> { + let mut stream = TcpStream::connect((ep.host.as_str(), ep.port)) + .await + .map_err(|e| Error(format!("wallet connect: {e}")))?; + // No `Connection: close` on the challenge: epee closes the socket with the + // 401 when the request asks for it, and the retry needs this connection. + let req = build_req(ep, body, None, false); + stream + .write_all(req.as_bytes()) + .await + .map_err(|e| Error(format!("wallet write: {e}")))?; + let raw = read_one_response(&mut stream).await?; + let status = http_status(&raw).unwrap_or(0); + if status != 401 { + return Ok((false, raw)); + } + let challenge = www_authenticate(&raw) + .ok_or_else(|| Error("wallet RPC digest required (--rpc-login / HTTP Digest)".into()))?; + if !challenge.trim().to_ascii_lowercase().starts_with("digest") { + return Err(Error( + "wallet RPC digest required (--rpc-login / HTTP Digest)".into(), + )); + } + let auth = digest_authorization(ep, &challenge)?; + let req = build_req(ep, body, Some(&auth), true); + stream + .write_all(req.as_bytes()) + .await + .map_err(|e| Error(format!("wallet write: {e}")))?; + Ok((true, read_to_eof(&mut stream).await?)) +} + +fn build_req(ep: &Endpoint, body: &str, authorization: Option<&str>, close: bool) -> String { let host_hdr = host_header(&ep.host, ep.port); let mut req = format!( - "POST {} HTTP/1.1\r\nHost: {host_hdr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n", + "POST {} HTTP/1.1\r\nHost: {host_hdr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n", ep.path, body.len() ); + if close { + req.push_str("Connection: close\r\n"); + } if let Some(auth) = authorization { req.push_str("Authorization: "); req.push_str(auth); @@ -1019,32 +1060,73 @@ fn build_req(ep: &Endpoint, body: &str, authorization: Option<&str>) -> String { req } -async fn http_post(ep: &Endpoint, req: &[u8]) -> Result> { - let mut stream = TcpStream::connect((ep.host.as_str(), ep.port)) - .await - .map_err(|e| Error(format!("wallet connect: {e}")))?; - stream - .write_all(req) - .await - .map_err(|e| Error(format!("wallet write: {e}")))?; +/// Read exactly one HTTP response: its head, then `Content-Length` body bytes. +/// epee always emits `Content-Length`, and a keep-alive response never ends in +/// EOF — reading to EOF here would hang on a healthy server. +async fn read_one_response(stream: &mut TcpStream) -> Result> { let mut buf = Vec::new(); - let mut tmp = [0u8; 8192]; - loop { - let n = stream - .read(&mut tmp) - .await - .map_err(|e| Error(format!("wallet read: {e}")))?; - if n == 0 { + let head_end = loop { + if let Some(i) = find_head_end(&buf) { + break i; + } + if !read_more(stream, &mut buf).await? { + // Closed before a full head: hand back what arrived, the status-line + // parse decides what that means. + return Ok(buf); + } + }; + let head = std::str::from_utf8(&buf[..head_end]).unwrap_or_default(); + // epee always sends `Content-Length`, but an open (challenge-less) RPC may + // not: with no length the body ends at EOF, so keep reading — the cap below + // is what stops a server that streams forever. + let Some(want) = content_length(head) else { + while read_more(stream, &mut buf).await? {} + return Ok(buf); + }; + while buf.len() < head_end + 4 + want { + if !read_more(stream, &mut buf).await? { break; } - if buf.len().saturating_add(n) > MAX_RPC_BYTES { - return Err(Error("wallet RPC response too large".into())); - } - buf.extend_from_slice(&tmp[..n]); } Ok(buf) } +async fn read_to_eof(stream: &mut TcpStream) -> Result> { + let mut buf = Vec::new(); + while read_more(stream, &mut buf).await? {} + Ok(buf) +} + +/// One read into `buf`. `false` means the peer closed. Enforces the shared cap. +async fn read_more(stream: &mut TcpStream, buf: &mut Vec) -> Result { + let mut tmp = [0u8; 8192]; + let n = stream + .read(&mut tmp) + .await + .map_err(|e| Error(format!("wallet read: {e}")))?; + if n == 0 { + return Ok(false); + } + if buf.len().saturating_add(n) > MAX_RPC_BYTES { + return Err(Error("wallet RPC response too large".into())); + } + buf.extend_from_slice(&tmp[..n]); + Ok(true) +} + +fn find_head_end(buf: &[u8]) -> Option { + buf.windows(4).position(|w| w == b"\r\n\r\n") +} + +fn content_length(head: &str) -> Option { + head.lines().skip(1).find_map(|line| { + let (k, v) = line.split_once(':')?; + k.eq_ignore_ascii_case("content-length") + .then(|| v.trim().parse().ok()) + .flatten() + }) +} + fn http_status(raw: &[u8]) -> Option { let text = std::str::from_utf8(raw).ok()?; let line = text.lines().next()?; diff --git a/tests/wallet.rs b/tests/wallet.rs index 3007ab9..da8e8f3 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -248,6 +248,81 @@ async fn oversized_rpc_response_is_err() { ); } +/// The Digest challenge is bound to the **connection** that answered 401, the +/// way epee does it: `http_custom_handler` owns the `http_server_auth`, whose +/// nonce starts empty, so a nonce is only ever valid on the socket that received +/// it. A client that retries on a fresh socket presents a nonce that socket +/// never issued and is refused again — the real `monero-wallet-rpc` 401 this +/// suite reproduces. One socket serves requests until it closes; the mock closes +/// after an authenticated reply, because the client asks for `Connection: close` +/// there and epee honours it. +async fn serve_one_conn( + mut sock: tokio::net::TcpStream, + reply: Arc String + Send + Sync>, + log: Option>>>, + delay: Option, + raw_reply: bool, +) { + let mut nonce: Option = None; + while let Some(req) = read_http_request(&mut sock).await { + if let Some(log) = &log { + log.lock().expect("log").push(req.clone()); + } + let sent = authorization_nonce(&req); + if sent.is_some() && sent == nonce { + assert!(req.contains("Authorization: Digest"), "missing digest auth: {req}"); + assert!(req.contains("username=\"ow\""), "missing user: {req}"); + assert!(req.contains("response=\""), "missing response: {req}"); + if let Some(d) = delay { + tokio::time::sleep(d).await; + } + let answer = reply(&rpc_method(&req)); + // `raw_reply` servers hand back a whole HTTP response (some tests + // bake their own status line); the default is a JSON-RPC body. + let wire = if raw_reply { + answer + } else { + http_200_body(&answer) + }; + let _ = sock.write_all(wire.as_bytes()).await; + return; + } + let fresh = next_nonce(); + let _ = sock.write_all(digest_401(&fresh).as_bytes()).await; + nonce = Some(fresh); + } +} + +/// Accept loop for [`serve_one_conn`]. +async fn serve_rpc_conns( + listener: TcpListener, + reply: Arc String + Send + Sync>, + log: Option>>>, + delay: Option, +) { + serve_rpc_conns_with(listener, reply, log, delay, false).await +} + +/// [`serve_rpc_conns`] with the reply contract spelled out: `raw_reply` means the +/// closure returns a complete HTTP response, otherwise a JSON-RPC body. +async fn serve_rpc_conns_with( + listener: TcpListener, + reply: Arc String + Send + Sync>, + log: Option>>>, + delay: Option, + raw_reply: bool, +) { + while let Ok((sock, _)) = listener.accept().await { + tokio::spawn(serve_one_conn( + sock, + Arc::clone(&reply), + log.clone(), + delay, + raw_reply, + )); + } +} + /// Records every request the client sends, answers the Digest challenge and /// then replies per RPC method. Lets a test assert on the *request log*. async fn serve_recording( @@ -255,21 +330,62 @@ async fn serve_recording( log: Arc>>, reply: Arc String + Send + Sync>, ) { - loop { - let Ok((mut sock, _)) = listener.accept().await else { - return; - }; - let mut buf = vec![0u8; 8192]; - let n = sock.read(&mut buf).await.unwrap_or(0); - let req = String::from_utf8_lossy(&buf[..n]).to_string(); - log.lock().expect("log").push(req.clone()); - if req.contains("Authorization:") { - let body = reply(&rpc_method(&req)); - let _ = sock.write_all(http_200_body(&body).as_bytes()).await; - } else { - let _ = sock.write_all(digest_401().as_bytes()).await; + serve_rpc_conns(listener, reply, Some(log), None).await +} + +/// Read one whole request: its head, then `Content-Length` body bytes. `None` +/// when the peer closed. +async fn read_http_request(sock: &mut tokio::net::TcpStream) -> Option { + let mut buf = Vec::new(); + let mut tmp = [0u8; 4096]; + let head_end = loop { + if let Some(i) = find_head_end(&buf) { + break i; + } + match sock.read(&mut tmp).await { + Ok(0) | Err(_) => return None, + Ok(n) => buf.extend_from_slice(&tmp[..n]), + } + }; + let head = String::from_utf8_lossy(&buf[..head_end]).to_string(); + let want = content_length(&head).unwrap_or(0); + while buf.len() < head_end + 4 + want { + match sock.read(&mut tmp).await { + Ok(0) | Err(_) => break, + Ok(n) => buf.extend_from_slice(&tmp[..n]), } } + Some(String::from_utf8_lossy(&buf).to_string()) +} + +fn find_head_end(buf: &[u8]) -> Option { + buf.windows(4).position(|w| w == b"\r\n\r\n") +} + +fn content_length(head: &str) -> Option { + head.lines().skip(1).find_map(|line| { + let (k, v) = line.split_once(':')?; + k.eq_ignore_ascii_case("content-length") + .then(|| v.trim().parse().ok()) + .flatten() + }) +} + +/// The `nonce` a request's `Authorization` field answers. +fn authorization_nonce(req: &str) -> Option { + let head = req.split("\r\n\r\n").next().unwrap_or(req); + let line = head + .lines() + .find(|l| l.to_ascii_lowercase().starts_with("authorization:"))?; + let rest = line.split_once("nonce=")?.1; + Some(rest.trim_start_matches('"').split('"').next()?.to_string()) +} + +/// A fresh server nonce per 401, so a stale one never passes by luck. +fn next_nonce() -> String { + use std::sync::atomic::{AtomicUsize, Ordering}; + static NEXT: AtomicUsize = AtomicUsize::new(1); + format!("nonce{:016x}", NEXT.fetch_add(1, Ordering::Relaxed)) } fn rpc_method(req: &str) -> String { @@ -588,28 +704,106 @@ fn from_env_reads_no_spend_flag() { assert!(!Wallet::from_env().no_spend(), "unset must be off"); } -fn digest_401() -> String { - "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into() +fn digest_401(nonce: &str) -> String { + format!( + "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"{nonce}\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\n\r\n" + ) } +/// Answers the Digest challenge on one connection with `ok` — a complete HTTP +/// response — to every method. async fn serve_digest_then(listener: TcpListener, ok: String) { - let (mut sock, _) = listener.accept().await.expect("accept"); - let mut buf = vec![0u8; 8192]; - let _ = sock.read(&mut buf).await; - sock.write_all(digest_401().as_bytes()).await.expect("401"); - drop(sock); + serve_rpc_conns_with(listener, Arc::new(move |_| ok.clone()), None, None, true).await +} - let (mut sock, _) = listener.accept().await.expect("accept2"); - buf.fill(0); - let n = sock.read(&mut buf).await.unwrap_or(0); - let req = String::from_utf8_lossy(&buf[..n]); - assert!( - req.contains("Authorization: Digest"), - "missing digest auth: {req}" +/// The digest retry must ride the socket that issued the challenge. epee binds +/// the nonce to the connection, so the pre-fix shape — challenge on one socket, +/// authenticated retry on another — is refused with 401 forever. That is the +/// `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed while +/// this suite stayed green against a mock that replayed the challenge on any +/// socket. +#[tokio::test] +async fn digest_retry_rides_the_connection_that_issued_the_challenge() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let conns = Arc::new(AtomicUsize::new(0)); + let counted = Arc::clone(&conns); + tokio::spawn(async move { + while let Ok((sock, _)) = listener.accept().await { + counted.fetch_add(1, Ordering::SeqCst); + tokio::spawn(serve_one_conn( + sock, + Arc::new(|_: &str| { + rpc_result( + r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#, + ) + }), + None, + None, + false, + )); + } + }); + + let got = recording_wallet(port) + .get_address() + .await + .expect("a same-socket digest retry must be accepted"); + assert!(got.starts_with('4'), "got {got}"); + assert_eq!( + conns.load(Ordering::SeqCst), + 1, + "one RPC call must use one connection: challenge and retry share it" + ); +} + +/// The flip side, pinned at the socket level: the nonce belongs to the +/// connection that minted it, so the same digest on a second connection is +/// refused. Without this the mock could silently go back to accepting the +/// cross-connection retry and stop catching the bug. +#[tokio::test] +async fn the_mock_refuses_a_digest_presented_on_another_connection() { + use tokio::net::TcpStream; + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(|_: &str| rpc_result("{}")), + None, + None, + )); + + let body = r#"{"jsonrpc":"2.0","id":"0","method":"get_version","params":{}}"#; + let plain = format!( + "POST /json_rpc HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ); + + let mut first = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + first.write_all(plain.as_bytes()).await.unwrap(); + let raw = read_http_request(&mut first).await.expect("the 401"); + assert!(raw.starts_with("HTTP/1.1 401"), "got {raw}"); + let nonce = raw + .split_once("nonce=\"") + .and_then(|(_, rest)| rest.split('"').next()) + .expect("a challenge nonce") + .to_string(); + drop(first); + + let answered = format!( + "POST /json_rpc HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAuthorization: Digest username=\"ow\", realm=\"monero-rpc\", nonce=\"{nonce}\", uri=\"/json_rpc\", algorithm=MD5, response=\"deadbeef\"\r\n\r\n{body}", + body.len() + ); + let mut second = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + second.write_all(answered.as_bytes()).await.unwrap(); + let raw = read_http_request(&mut second).await.expect("the second 401"); + assert!( + raw.starts_with("HTTP/1.1 401"), + "a nonce from another connection must not be accepted: {raw}" ); - assert!(req.contains("username=\"ow\""), "missing user: {req}"); - assert!(req.contains("response=\""), "missing response: {req}"); - sock.write_all(ok.as_bytes()).await.expect("200"); } #[tokio::test] @@ -628,23 +822,18 @@ async fn mock_digest_auth_accepted() { /// Answers the Digest challenge, then holds the reply for `delay`. Lets a test /// prove which call classes get which budget. async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) { - while let Ok((mut sock, _)) = listener.accept().await { - let mut buf = vec![0u8; 8192]; - let n = sock.read(&mut buf).await.unwrap_or(0); - let req = String::from_utf8_lossy(&buf[..n]).to_string(); - if !req.contains("Authorization:") { - let _ = sock.write_all(digest_401().as_bytes()).await; - continue; - } - tokio::time::sleep(delay).await; - let body = match rpc_method(&req).as_str() { + serve_rpc_conns( + listener, + Arc::new(|method: &str| match method { "get_info" => synced_info(), _ => rpc_result( r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#, ), - }; - let _ = sock.write_all(http_200_body(&body).as_bytes()).await; - } + }), + None, + Some(delay), + ) + .await } const SPEND_ADDR: &str = "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; From 145036fda83c1bbd7703bfdf3989014cec35c7cb Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 20 Sep 2026 11:53:19 -0400 Subject: [PATCH 05/78] wallet: expose an on-demand seed accessor over core + UniFFI Wallet::create_wallet returned the 25-word seed exactly once and nothing could reach it afterwards, so a seed that was never backed up at creation was unrecoverable. Add Wallet::mnemonic() (one query_key mnemonic call on the open wallet file), Node::wallet_seed() mirroring wallet_create, and the additive UniFFI export Wire::wallet_seed() -> Kotlin Wire.walletSeed(). No existing signature changes. The refusals stay leak-free: an unconfigured wallet gets NOT_CONFIGURED_MSG without a dial, a watch-only wallet keeps the RPC's -29 view-only mapping, and no error string carries the RPC login. Tests (tests/wallet.rs) drive the per-connection Digest mock: the words come back verbatim, a JSON-RPC error surfaces without the login or endpoint, a rejected digest refusal does not leak the password, and an unconfigured wallet is refused without dialing. --- crates/onionwire-sdk/src/lib.rs | 11 +++++ src/node.rs | 12 ++++++ src/wallet.rs | 19 +++++++++ tests/wallet.rs | 74 +++++++++++++++++++++++++++++++++ 4 files changed, 116 insertions(+) diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 154b602..3680aa7 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -594,6 +594,17 @@ impl Wire { .map_err(WireError::new) } + /// Re-read this wallet's 25-word seed so the UI can offer a "back up seed" + /// action after creation. Dials the wallet child's RPC (`query_key + /// mnemonic`), so it is cheap but not free, and it needs a wallet the child + /// has open. The result is a spend key: call this only from an explicit + /// user action, show it, and do not persist or log it. + /// + /// The Kotlin binding is `Wire.walletSeed()`. + pub async fn wallet_seed(&self) -> WResult { + self.node()?.wallet_seed().await.map_err(WireError::new) + } + /// Import a wallet from an existing 25-word seed. This is the only path /// that takes a user-supplied secret. pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> { diff --git a/src/node.rs b/src/node.rs index fcc8015..a78ea8d 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1179,6 +1179,18 @@ impl Node { .map_err(|e| e.to_string()) } + /// Re-read the seed of the wallet file the child has open. `create_wallet` + /// returns it once; after that this is the only path to it. The seed is a + /// spend key, so the caller must only show it on an explicit user action + /// and must not log or store it. + pub async fn wallet_seed(&self) -> Result { + let w = self.wallet_snapshot(); + if !w.configured() { + return Err(wallet::NOT_CONFIGURED_MSG.into()); + } + w.mnemonic().await.map_err(|e| e.to_string()) + } + /// Import a wallet from an existing 25-word seed. This is the only path /// that takes a user-supplied secret. pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<(), String> { diff --git a/src/wallet.rs b/src/wallet.rs index 7195691..e4437da 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -788,6 +788,25 @@ impl Wallet { json_str(&v, "key") } + /// Re-read the seed of the wallet file the RPC has open (`query_key + /// mnemonic`). After `create_wallet` this is the **only** way to recover a + /// created wallet's seed, so the UI can offer a backup action instead of + /// showing it once. It needs an open, spend-capable wallet file; a + /// watch-only one answers the RPC's `-29` and surfaces as the view-only + /// refusal. + /// + /// The returned words are a spend key: never log them, never store them, + /// and never put them in an error string. + pub async fn mnemonic(&self) -> Result { + if !self.configured() { + return Err(Error(NOT_CONFIGURED_MSG.into())); + } + let v = self + .rpc("query_key", serde_json::json!({"key_type": "mnemonic"})) + .await?; + json_str(&v, "key") + } + /// Import an existing wallet from its 25-word seed. This is the only path /// that takes a user-supplied secret. pub async fn restore_wallet(&self, filename: &str, password: &str, seed: &str) -> Result<()> { diff --git a/tests/wallet.rs b/tests/wallet.rs index da8e8f3..9c8649b 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -819,6 +819,80 @@ async fn mock_digest_auth_accepted() { assert!(got.starts_with('4'), "got {got}"); } +/// The seed is a spend key: `mnemonic` must be one `query_key mnemonic` call +/// and nothing else, so the caller sees exactly what the open wallet answers. +#[tokio::test] +async fn mnemonic_returns_the_words_the_rpc_answers() { + const WORDS: &str = "one two three four five six seven eight nine ten eleven twelve \ +thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty twentyone \ +twentytwo twentythree twentyfour twentyfive"; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(|method: &str| match method { + "query_key" => rpc_result(&format!(r#"{{"key":"{WORDS}"}}"#)), + other => panic!("mnemonic must make one query_key call, saw {other}"), + }), + None, + None, + )); + let got = recording_wallet(port).mnemonic().await.expect("mnemonic"); + assert_eq!(got, WORDS); +} + +/// A wallet with no open file answers a JSON-RPC error. It must surface as the +/// wallet's error, and the RPC login from the URL must not ride along with it. +#[tokio::test] +async fn mnemonic_surfaces_an_rpc_error_without_leaking_the_login() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(|_: &str| rpc_error(-1, "wallet file is not open")), + None, + None, + )); + let err = recording_wallet(port).mnemonic().await.unwrap_err(); + let msg = err.to_string(); + assert!(msg.contains("wallet file is not open"), "got {err}"); + assert!(!msg.contains("secret"), "password leaked: {err}"); + assert!(!msg.contains("http://"), "endpoint leaked: {err}"); +} + +/// The refused-digest refusal names the login in prose ("the login does not +/// match"), which is exactly the copy that must not carry the credential. +#[tokio::test] +async fn mnemonic_refuses_a_rejected_digest_without_leaking_the_login() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(serve_rpc_conns_with( + listener, + Arc::new(|_: &str| "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n".to_string()), + None, + None, + true, + )); + let err = recording_wallet(port).mnemonic().await.unwrap_err(); + let msg = err.to_string(); + assert!(msg.contains("digest rejected"), "got {err}"); + assert!(!msg.contains("secret"), "password leaked: {err}"); +} + +/// No endpoint, no dial: the refusal is the configured-guard copy the rest of +/// the wallet uses, not a connection error. +#[test] +fn mnemonic_on_an_unconfigured_wallet_is_a_refusal_not_a_dial() { + let w = Wallet::disabled(); + let err = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(w.mnemonic()) + .unwrap_err(); + assert_eq!(err.to_string(), NOT_CONFIGURED_MSG); +} + /// Answers the Digest challenge, then holds the reply for `delay`. Lets a test /// prove which call classes get which budget. async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) { From 118191c5412aa489d5c2cf3f8c8b1bc764861af2 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 20 Sep 2026 12:09:48 -0400 Subject: [PATCH 06/78] android: block the wallet screen on an unbacked seed, and make it re-showable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A created wallet's seed was two lines of small text at the bottom of the wallet page, dismissed by one tap, gone for good once the screen was left. A real user created a wallet, never saw the seed, and the app had no way to show it again. - `SeedBackupGate` (new, pure Kotlin): the confirm word `SEEN` and its case-insensitive match mirror the TUI's own `WalletSetup::CreateSeed` gate; create starts unbacked, import is backed up without the gate, and only a correct word can confirm. - The seed card is the whole body until the word is typed and Done is tapped: no Cancel, no copy button (the Android clipboard is readable by every other app), Done dead until `SEEN`. - "Back up seed" re-reads the seed through the new `Wire::wallet_seed()` (`WireViewModel.walletSeed()`), so a seed missed the first time is not lost. Its failure is shown next to the button, not at the bottom of a long scroll. - While unconfirmed: a warning strip stays at the top of the wallet screen and the receive address and Show QR are hidden — XMR received into a wallet whose 25 words were never written down is unrecoverable. - The flag lives in app-local prefs (`wallet_seed_backup`), not in the Keystore-wrapped store, and is reset by `createWallet` itself so no caller can forget it. The stored flag is nullable, and the null is load-bearing. `false` means this install created a wallet and nobody has confirmed the seed, so the strip is up whether or not the balance reads. `null` means nothing is stored — an install that predates the flag, or one that has never created a wallet here — and there the strip waits for `wallet_balance` to return a real amount, the core's own evidence that the child has a wallet open. Without that distinction a first-run user who had configured a chain source but not yet created a wallet (`wallet_balance` returns "err") would be warned about a seed they do not have. The app-bar Back still leaves the screen, deliberately — it is the TUI's `Esc`. It costs nothing now, because leaving no longer loses the seed. Verification: `./gradlew :app:testDebugUnitTest` green, 135 tests (`SeedBackupGateTest` 18 of them). --- .../siriusdevops/onionwire/WireViewModel.kt | 76 ++++++ .../onionwire/ui/SeedBackupGate.kt | 113 +++++++++ .../siriusdevops/onionwire/ui/WalletScreen.kt | 240 ++++++++++++++++-- .../onionwire/ui/SeedBackupGateTest.kt | 176 +++++++++++++ 4 files changed, 588 insertions(+), 17 deletions(-) create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/SeedBackupGate.kt create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/ui/SeedBackupGateTest.kt diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 6f26632..7be3c6a 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -1,6 +1,8 @@ package com.siriusdevops.onionwire import android.app.Application +import android.content.Context +import android.content.SharedPreferences import androidx.core.app.NotificationManagerCompat import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope @@ -11,6 +13,8 @@ import com.siriusdevops.onionwire.crypto.StoredPassphraseStore import com.siriusdevops.onionwire.keepalive.KeepAliveService import com.siriusdevops.onionwire.keepalive.KeepAliveStatus import com.siriusdevops.onionwire.keepalive.NodeHost +import com.siriusdevops.onionwire.ui.SeedBackupGate +import com.siriusdevops.onionwire.ui.WalletKeyOrigin import com.siriusdevops.onionwire.wallet.ChainStorage import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE import com.siriusdevops.onionwire.wallet.WalletChildBinaries @@ -588,11 +592,32 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { suspend fun sendTip(pubkeyHex: String, amountXmr: String, memo: String = ""): Result = runCatching { requireWire().sendTip(pubkeyHex, amountXmr, memo) } + /** + * Create a wallet and read its seed once. The seed-backup flag is reset + * here, not by the screen: every successful create is a new seed nobody has + * read, and a caller that forgot to reset it would leave a spend key + * unrecoverable. See [SeedBackupGate.afterWallet]. + */ suspend fun createWallet(password: String): Result = runCatching { requireWire().createWallet(password) } + .onSuccess { setWalletSeedConfirmed(SeedBackupGate.afterWallet(WalletKeyOrigin.Created)) } + /** + * Import a wallet from a user-supplied seed. That seed is already on paper — + * the user just pasted it — so the wallet counts as backed up without the + * confirm step. + */ suspend fun importWallet(password: String, seed: String): Result = runCatching { requireWire().importWallet(password, seed) } + .onSuccess { setWalletSeedConfirmed(SeedBackupGate.afterWallet(WalletKeyOrigin.Imported)) } + + /** + * Re-read the open wallet's 25-word seed, for the "Back up seed" recovery + * path. A spend key: only ever called from that explicit user action, shown + * on the blocking card, and dropped. Never logged and never persisted. + */ + suspend fun walletSeed(): Result = + runCatching { requireWire().walletSeed() } fun spendAuthorityWarning(): String = runCatching { requireWire().spendAuthorityWarning() @@ -600,6 +625,47 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { "this wallet file can spend. anyone with its passphrase or the RPC creds can move the balance. write down the seed." } + // --- Seed backup gate -------------------------------------------------- + // Whether the open wallet's seed has been confirmed written down. This is + // NOT a secret — it is a boolean in app-local prefs, deliberately kept out + // of the Keystore-wrapped store under `filesDir/secrets`, which holds the + // passphrase and nothing else. + // + // The flow is nullable, and the null is load-bearing: nothing stored means + // "this install has never created or imported a wallet through this build", + // which is not the same as "the user created one and has not confirmed it". + // See [SeedBackupGate.warningVisible] for why the screen needs both. + + private val seedBackupPrefs: SharedPreferences = + app.getSharedPreferences(SEED_BACKUP_PREFS, Context.MODE_PRIVATE) + + private val _walletSeedConfirmed = MutableStateFlow( + if (seedBackupPrefs.contains(SEED_BACKED_UP_KEY)) { + seedBackupPrefs.getBoolean(SEED_BACKED_UP_KEY, false) + } else { + null + }, + ) + + /** + * The stored seed-backup flag: `false` unconfirmed, `true` confirmed or + * imported, `null` nothing stored (an install that predates the flag). + */ + val walletSeedConfirmed: StateFlow = _walletSeedConfirmed.asStateFlow() + + /** + * One confirm step from the blocking seed card. The gate decides: a wrong + * word leaves the flag where it was, so this can never un-confirm a wallet. + */ + fun confirmWalletSeed(typed: String) { + setWalletSeedConfirmed(SeedBackupGate.afterConfirm(typed, _walletSeedConfirmed.value == true)) + } + + private fun setWalletSeedConfirmed(confirmed: Boolean) { + seedBackupPrefs.edit().putBoolean(SEED_BACKED_UP_KEY, confirmed).apply() + _walletSeedConfirmed.value = confirmed + } + // --- App-owned wallet child (issue #107) ------------------------------- // The app owns `monero-wallet-rpc` instead of asking the user to start one // and export `ONIONWIRE_WALLET_RPC`. The core's own states are surfaced @@ -920,3 +986,13 @@ suspend fun walletChildRefreshLoop( /** Cadence of the wallet-child refresh loop, in milliseconds. */ private const val WALLET_CHILD_TICK_MS: Long = 2_000 + +/** + * App-local prefs file for the seed-backup flag. Not a secret, so it is a plain + * prefs file rather than anything under `filesDir/secrets`. + */ +private const val SEED_BACKUP_PREFS: String = "wallet_seed_backup" + +/** Key inside [SEED_BACKUP_PREFS]: has the open wallet's seed been written down? */ +private const val SEED_BACKED_UP_KEY: String = "backed_up" + diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/SeedBackupGate.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/SeedBackupGate.kt new file mode 100644 index 0000000..ee0c303 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/SeedBackupGate.kt @@ -0,0 +1,113 @@ +package com.siriusdevops.onionwire.ui + +/** + * Where the open wallet's key material came from. + * + * The distinction is the whole gate. A seed the user *supplied* (import) is a + * seed the user already has on paper, so that wallet is backed up from the + * start. A seed the app *generated* (create) has been read by nobody until it + * is put on screen, so that wallet starts unbacked and stays unbacked until the + * user proves it is written down. + */ +enum class WalletKeyOrigin { + Created, + Imported, +} + +/** + * The seed-backup gate: every decision the wallet screen makes about an + * unconfirmed seed, as pure Kotlin — no Compose, no Android, no prefs — so the + * rules are covered by `SeedBackupGateTest` on the JVM without a device. + * + * The gate exists because a seed shown once and then lost is an unrecoverable + * wallet: XMR received into a wallet whose 25 words were never written down + * cannot be spent or recovered by anyone, including this app. So the answer is + * not advisory — while it says the seed is unbacked, the wallet screen keeps a + * warning up and hides the receive address and its QR. + * + * The confirm word and its case-insensitivity mirror the TUI's own seed screen + * (`src/tui.rs`, `WalletSetup::CreateSeed`, which compares with + * `eq_ignore_ascii_case("SEEN")`) instead of inventing a second convention for + * the same wallet. + */ +object SeedBackupGate { + + /** The word that releases the block. The TUI's word, not a new one. */ + const val CONFIRM_WORD: String = "SEEN" + + /** + * True when [typed] releases the block. + * + * Trimmed and case-insensitive, so a soft keyboard's auto-capitalised `Seen` + * and a trailing space from a paste both count. Everything else — including + * the empty string — stays blocked. + */ + fun accepts(typed: String): Boolean = + typed.trim().equals(CONFIRM_WORD, ignoreCase = true) + + /** + * The flag right after a wallet is created or imported. + * + * A create always resets it: the wallet file is new, and the seed it was + * built from has never been read by anyone. + */ + fun afterWallet(origin: WalletKeyOrigin): Boolean = when (origin) { + WalletKeyOrigin.Created -> false + WalletKeyOrigin.Imported -> true + } + + /** + * The flag after one confirm step. + * + * Only a correct [typed] can flip it to `true`; a wrong word can never + * un-confirm a wallet that is already backed up. + */ + fun afterConfirm(typed: String, backedUp: Boolean): Boolean = + backedUp || accepts(typed) + + /** Done is dead until the word is right. */ + fun confirmEnabled(typed: String): Boolean = accepts(typed) + + /** + * The persistent strip is up while this install has an unconfirmed seed. + * + * [confirmed] is the stored flag, and it is nullable on purpose: + * + * - `false` — this install created a wallet and nobody has confirmed the + * seed. The wallet exists whether or not its balance reads, so the strip + * is up regardless. + * - `true` — confirmed, or imported. Nothing to say. + * - `null` — nothing stored: an install that predates this flag, or one + * that has never created or imported a wallet here. "We never asked" is + * not "the user wrote it down", but it is also not evidence that a wallet + * exists — so the strip waits for [walletReadable], the core's own proof + * that the child has a wallet open. + * + * Without that last distinction the strip would fire on every install that + * has configured a chain source but not yet created a wallet, which is + * exactly the state a first-run user is in. + */ + fun warningVisible(confirmed: Boolean?, walletReadable: Boolean): Boolean = when (confirmed) { + true -> false + false -> true + null -> walletReadable + } + + /** + * The receive address and its QR are shown only while there is no unbacked + * seed to worry about. Receiving into an unbacked wallet is the one mistake + * this gate exists to prevent, so the address is hidden rather than merely + * warned about. + */ + fun receiveAddressVisible(confirmed: Boolean?, walletReadable: Boolean): Boolean = + !warningVisible(confirmed, walletReadable) + + /** + * The strip's words. One source: the screen renders this verbatim, so the + * reason the address disappeared travels with the hiding. + */ + const val WARNING: String = + "seed not backed up. write down the 25 words before you receive anything — " + + "a wallet whose seed was never written down cannot be recovered. " + + "the receive address stays hidden until you do." +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index 4fbeeac..ec98015 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -76,6 +76,7 @@ fun WalletScreen( val childError by vm.walletChildError.collectAsStateWithLifecycle() val starting by vm.walletChildStarting.collectAsStateWithLifecycle() val chain by vm.chainSource.collectAsStateWithLifecycle() + val seedConfirmed by vm.walletSeedConfirmed.collectAsStateWithLifecycle() val scope = rememberCoroutineScope() // Resolved once per composition: the native library directory is fixed for // the life of the process. @@ -92,7 +93,11 @@ fun WalletScreen( var error by remember { mutableStateOf(null) } var composer by remember { mutableStateOf(null) } var setup by remember { mutableStateOf(null) } - var backupSeed by remember { mutableStateOf(null) } + // The seed currently on the blocking card: set by a successful create, or by + // "Back up seed" re-reading it from the wallet child. Null means no card. + // Never persisted and never logged — it is a spend key. + var pendingSeed by remember { mutableStateOf(null) } + var seedConfirm by remember { mutableStateOf("") } var daemonText by remember { mutableStateOf("") } var daemonError by remember { mutableStateOf(null) } @@ -103,6 +108,26 @@ fun WalletScreen( runCatching { transfers = vm.walletRecentTransfers(25) } } + /** + * "Back up seed": re-read the open wallet's seed from the wallet child and + * put it on the blocking card. This is the only path to a seed that was + * created before this screen existed, so the failure is shown rather than + * swallowed — it is the difference between "the child is not running" and + * "there is nothing to recover". + */ + fun openSeedBackup() { + scope.launch { + error = null + vm.walletSeed().fold( + onSuccess = { seed -> + pendingSeed = seed + seedConfirm = "" + }, + onFailure = { error = it.message ?: it.toString() }, + ) + } + } + LaunchedEffect(Unit) { reload() vm.refreshChainSource() @@ -151,6 +176,46 @@ fun WalletScreen( .screenContentInsets() .verticalScroll(rememberScrollState()), ) { + // The blocking seed step. While a seed is on screen this card is the + // whole body: no Cancel, and Done stays dead until the confirm word + // is typed, so the one-shot seed cannot be dismissed unread. The + // app-bar Back still leaves the screen — that is the TUI's `Esc` — + // and it costs nothing now, because leaving no longer loses the + // seed: the wallet stays unbacked (strip up, receive address hidden) + // until "Back up seed" puts this card back on screen. + val seed = pendingSeed + if (seed != null) { + SeedBackupCard( + seed = seed, + typed = seedConfirm, + onTyped = { seedConfirm = it }, + onDone = { + // The gate owns the transition: a wrong word (which the + // disabled Done button already blocks) cannot confirm. + vm.confirmWalletSeed(seedConfirm) + pendingSeed = null + seedConfirm = "" + }, + ) + error?.let { ErrorLine(it) } + return@Column + } + + // The persistent unbacked strip, above everything else on the page. + // `walletReadable` is the core's own evidence that the child has a + // wallet open: `wallet_balance` returns exactly "off" for a chain + // source that was never configured, "err" for a configured one whose + // read failed (no wallet file open yet, or the child is down), and a + // real amount otherwise. The gate uses it only for an install that + // has never created a wallet here, so a first-run user who has + // configured a daemon but not yet created anything is not nagged + // about a seed they do not have. + val walletReadable = balance != null && balance != "off" && balance != "err" + val unbacked = SeedBackupGate.warningVisible(seedConfirmed, walletReadable) + if (unbacked) { + UnbackedSeedCard(error = error, onBackUpSeed = { openSeedBackup() }) + } + Card( modifier = Modifier .fillMaxWidth() @@ -173,7 +238,12 @@ fun WalletScreen( style = MaterialTheme.typography.headlineSmall, fontFamily = FontFamily.Monospace, ) - val addr = address + // Hidden until the seed is confirmed written down: XMR into a + // wallet whose 25 words were never recorded is unrecoverable, + // so the address and its QR are gated, not just warned about. + val addr = address?.takeIf { + SeedBackupGate.receiveAddressVisible(seedConfirmed, walletReadable) + } if (addr != null) { Spacer(Modifier.height(8.dp)) Text( @@ -333,7 +403,9 @@ fun WalletScreen( onCancel = { setup = null }, onCreated = { seed -> setup = null - backupSeed = seed + // The card is the whole body from here until SEEN. + pendingSeed = seed + seedConfirm = "" scope.launch { reload() } }, onImported = { @@ -374,36 +446,170 @@ fun WalletScreen( modifier = Modifier.weight(1f), ) { Text("Import") } } + // The recovery path for a wallet whose seed was missed. The + // strip above carries its own copy of this button while the + // seed is unconfirmed, so exactly one is ever on screen — + // and this copy is only offered once the child can actually + // read a wallet, which is the only state in which the seed + // read can succeed. + if (walletReadable && !SeedBackupGate.warningVisible(seedConfirmed, walletReadable)) { + Spacer(Modifier.height(8.dp)) + OutlinedButton( + onClick = { openSeedBackup() }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-seed-backup-action"), + ) { Text("Back up seed") } + } } } - backupSeed?.let { seed -> - Text( - "write this seed down once. anyone with it can spend.", - style = MaterialTheme.typography.labelSmall, - modifier = Modifier.padding(horizontal = 12.dp), - ) - Text( - seed, - style = MaterialTheme.typography.bodySmall, - fontFamily = FontFamily.Monospace, - modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), - ) - TextButton(onClick = { backupSeed = null }) { Text("I wrote it down") } + // While the strip is up the error belongs next to the button that + // caused it: this page is one long scroll and the daemon card sits + // between the strip and the bottom, so a failed `wallet_seed` read + // would otherwise land off-screen. + if (!unbacked) { + error?.let { ErrorLine(it) } } + } + } +} +/** The one error line every wallet action shares. */ +@Composable +private fun ErrorLine(text: String) { + Text( + text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) +} + +/** + * The persistent unbacked strip: up at the top of the wallet screen from the + * moment a create succeeds until the seed is confirmed written down, and again + * on any install whose wallet predates the flag. + * + * It is not a toast and not a dialog — leaving the screen does not dismiss it, + * because the state it reports is the wallet's, not the screen's. Its button is + * the recovery path for a seed that was created before the user knew to look. + */ +@Composable +private fun UnbackedSeedCard( + error: String?, + onBackUpSeed: () -> Unit, +) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp) + .testTag("wallet-seed-warning"), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text( + SeedBackupGate.WARNING, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onErrorContainer, + ) + Spacer(Modifier.height(8.dp)) + OutlinedButton( + onClick = onBackUpSeed, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-seed-backup-action"), + ) { Text("Back up seed") } error?.let { + Spacer(Modifier.height(6.dp)) Text( it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error, - modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), ) } } } } +/** + * The blocking seed step: the 25 words, and a Done that is dead until the + * confirm word is typed. + * + * There is no Cancel and no copy button. No Cancel, because a seed this card is + * showing for the first time has never been written down anywhere else, so + * dismissing it unread is how a wallet becomes unrecoverable. No copy button, + * because the Android clipboard is readable by every other app on the device + * (and by the clipboard history on Android 13+), which would hand the spend key + * to whoever asks for it next. + * + * The seed is a Kotlin `String`, so it cannot be wiped in place the way the + * TUI's `Zeroizing` is; dropping the reference is the strongest thing + * available here. That is another reason it is never written to disk. + */ +@Composable +private fun SeedBackupCard( + seed: String, + typed: String, + onTyped: (String) -> Unit, + onDone: () -> Unit, +) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(12.dp) + .testTag("wallet-seed-card"), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text("Back up this seed", style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(8.dp)) + Text( + "These 25 words are the only way to recover this wallet, and anyone who " + + "reads them can spend it. Write them down now — this is the only copy.", + style = MaterialTheme.typography.bodySmall, + ) + Spacer(Modifier.height(8.dp)) + Text( + seed, + style = MaterialTheme.typography.bodyMedium, + fontFamily = FontFamily.Monospace, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-seed-words"), + ) + Spacer(Modifier.height(12.dp)) + Text( + "Type ${SeedBackupGate.CONFIRM_WORD} to confirm you have written it down.", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(4.dp)) + OutlinedTextField( + value = typed, + onValueChange = onTyped, + singleLine = true, + label = { Text("type ${SeedBackupGate.CONFIRM_WORD}") }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-seed-confirm-input"), + ) + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + Button( + onClick = onDone, + enabled = SeedBackupGate.confirmEnabled(typed), + modifier = Modifier.testTag("wallet-seed-confirm-done"), + ) { Text("Done") } + } + } + } +} + @Composable private fun TransferCard(t: TransferRow) { Card( diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/SeedBackupGateTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/SeedBackupGateTest.kt new file mode 100644 index 0000000..9318753 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/SeedBackupGateTest.kt @@ -0,0 +1,176 @@ +package com.siriusdevops.onionwire.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The seed-backup gate's rules, on the JVM. + * + * These are the decisions the wallet screen renders from: whether the created + * seed card is still blocking, whether the persistent warning is up, and + * whether the receive address is on screen at all. Pure logic, so no + * Robolectric and no Compose test dependency — same shape as + * `WalletChildStatusTextTest` and `OutboxDetailTest`. + */ +class SeedBackupGateTest { + + /** A wallet the child can actually read: `wallet_balance` returned a value. */ + private val readable = true + + /** `wallet_balance` said "off" (no chain source) or "err" (nothing open). */ + private val notReadable = false + + // --- the confirm word is the TUI's word --------------------------------- + + @Test + fun the_confirm_word_is_the_tui_word() { + // `src/tui.rs` `WalletSetup::CreateSeed` compares against "SEEN". A + // second convention here would be a different gate than the TUI's. + assertEquals("SEEN", SeedBackupGate.CONFIRM_WORD) + } + + @Test + fun a_correct_word_releases_the_block_whatever_its_case_or_padding() { + assertTrue(SeedBackupGate.accepts("SEEN")) + // The TUI compares with `eq_ignore_ascii_case`. + assertTrue(SeedBackupGate.accepts("seen")) + assertTrue(SeedBackupGate.accepts("SeEn")) + // A soft keyboard auto-capitalises and a paste can carry whitespace. + assertTrue(SeedBackupGate.accepts(" seen ")) + } + + @Test + fun a_blank_or_wrong_word_stays_blocked() { + assertFalse(SeedBackupGate.accepts("")) + assertFalse(SeedBackupGate.accepts(" ")) + assertFalse(SeedBackupGate.accepts("SEE")) + // A prefix is not the word: the TUI only fires on the whole match. + assertFalse(SeedBackupGate.accepts("SEENN")) + assertFalse(SeedBackupGate.accepts("seen.")) + // The other word in this flow is the spend-authority one. + assertFalse(SeedBackupGate.accepts("SPEND")) + } + + @Test + fun done_is_dead_until_the_word_is_right() { + assertFalse(SeedBackupGate.confirmEnabled("")) + assertFalse(SeedBackupGate.confirmEnabled("SEENN")) + assertTrue(SeedBackupGate.confirmEnabled("SEEN")) + assertTrue(SeedBackupGate.confirmEnabled("seen")) + } + + // --- the state transitions ---------------------------------------------- + + @Test + fun a_create_starts_unbacked() { + assertFalse(SeedBackupGate.afterWallet(WalletKeyOrigin.Created)) + } + + @Test + fun an_import_is_backed_up_without_the_gate() { + // The user pasted the seed to get here, so there is nothing to confirm. + assertTrue(SeedBackupGate.afterWallet(WalletKeyOrigin.Imported)) + } + + @Test + fun a_successful_confirm_marks_the_wallet_backed_up() { + val created = SeedBackupGate.afterWallet(WalletKeyOrigin.Created) + assertTrue(SeedBackupGate.afterConfirm("SEEN", created)) + } + + @Test + fun a_wrong_word_leaves_an_unbacked_wallet_unbacked() { + assertFalse(SeedBackupGate.afterConfirm("", false)) + assertFalse(SeedBackupGate.afterConfirm("nope", false)) + } + + @Test + fun a_wrong_word_cannot_un_confirm_a_backed_up_wallet() { + // Done is disabled for a wrong word, but the flag must not be a way to + // walk a confirmed wallet back into the hidden-address state. + assertTrue(SeedBackupGate.afterConfirm("", true)) + assertTrue(SeedBackupGate.afterConfirm("SPEND", true)) + } + + @Test + fun a_new_create_resets_a_confirmed_wallet_to_unbacked() { + // Create -> confirm -> create again: the second wallet file has its own + // seed, and nobody has read it yet. + val first = + SeedBackupGate.afterConfirm("SEEN", SeedBackupGate.afterWallet(WalletKeyOrigin.Created)) + assertTrue(first) + assertFalse(SeedBackupGate.afterWallet(WalletKeyOrigin.Created)) + } + + // --- what the screen does with the flag --------------------------------- + + @Test + fun a_created_wallet_keeps_the_strip_up_until_the_word_is_typed() { + val created = SeedBackupGate.afterWallet(WalletKeyOrigin.Created) + assertTrue(SeedBackupGate.warningVisible(created, readable)) + + val confirmed = SeedBackupGate.afterConfirm("seen", created) + assertFalse(SeedBackupGate.warningVisible(confirmed, readable)) + } + + @Test + fun an_imported_wallet_never_shows_the_strip() { + val backedUp = SeedBackupGate.afterWallet(WalletKeyOrigin.Imported) + assertFalse(SeedBackupGate.warningVisible(backedUp, readable)) + assertFalse(SeedBackupGate.warningVisible(backedUp, notReadable)) + } + + @Test + fun a_created_wallet_keeps_the_strip_up_even_before_its_balance_reads() { + // A create is proof a wallet exists, so a child that has not answered + // yet must not be read as "no wallet to warn about". + assertTrue(SeedBackupGate.warningVisible(false, notReadable)) + } + + @Test + fun the_receive_address_is_hidden_while_the_seed_is_unconfirmed() { + assertFalse(SeedBackupGate.receiveAddressVisible(false, readable)) + assertTrue(SeedBackupGate.receiveAddressVisible(true, readable)) + } + + @Test + fun a_created_wallet_hides_its_receive_address_until_the_word_is_typed() { + val created = SeedBackupGate.afterWallet(WalletKeyOrigin.Created) + assertFalse(SeedBackupGate.receiveAddressVisible(created, readable)) + + val confirmed = SeedBackupGate.afterConfirm("seen", created) + assertTrue(SeedBackupGate.receiveAddressVisible(confirmed, readable)) + } + + @Test + fun an_install_that_never_created_a_wallet_here_waits_for_a_readable_wallet() { + // `null` is "nothing stored": an install that predates the flag, or one + // that has only configured a chain source. `wallet_balance` returns + // "err" for a configured chain whose child has no wallet open, and a + // first-run user is in exactly that state — nagging them about a seed + // they do not have is the false positive this rule exists to prevent. + assertFalse(SeedBackupGate.warningVisible(null, notReadable)) + assertTrue(SeedBackupGate.receiveAddressVisible(null, notReadable)) + } + + @Test + fun an_unconfirmed_wallet_that_predates_the_flag_is_warned_about_once_it_reads() { + // The user this gate is for: they created a wallet on an older build, + // so nothing is stored, but the child can read the wallet. That is a + // real wallet whose seed nobody has confirmed. + assertTrue(SeedBackupGate.warningVisible(null, readable)) + assertFalse(SeedBackupGate.receiveAddressVisible(null, readable)) + } + + @Test + fun the_strip_says_why_the_address_is_gone() { + // The hiding is only fair if the strip names it; assert the strip is + // not empty and actually mentions the seed and the receive address. + val text = SeedBackupGate.WARNING + assertTrue(text.contains("seed")) + assertTrue(text.contains("receive address")) + assertTrue(text.contains("recovered")) + } +} From 467510f0969d0aaf3618d86f7ec6f1ad6bf22138 Mon Sep 17 00:00:00 2001 From: "rust-dev (hermes)" Date: Mon, 21 Sep 2026 10:21:48 -0400 Subject: [PATCH 07/78] store: a wallet catalogue in the encrypted db Wallets were only ever a file in $ONIONWIRE_HOME/wallet plus the single-row wallet_child config for the one the child is currently pointed at, so a created wallet was not remembered and a second create had nowhere to go. Add a 'wallets' table (id, name, identity_pubkey, onion_locator, wallet_filename, created_at) and CRUD on Store: create_wallet, get_wallet_by_id, list_wallets, delete_wallet. wallet_filename is UNIQUE so a second wallet cannot silently reuse the first one's file, and identity_pubkey is deliberately not unique (identity is the roster key, a wallet is a file; the locator may rotate or be empty). No new crate: the store is already rusqlite + SQLCipher with a raw PRAGMA key, and sqlx has no SQLCipher path, so a second pool would be a second unencrypted way in. Tests: 5 store cases in tests/store.rs (round-trip, coexistence across a reopen, duplicate filename, delete, blank label/filename) plus the at_rest upgrade case in src/store.rs. --- src/lib.rs | 4 +- src/store.rs | 184 +++++++++++++++++++++++++++++++++++++++++++++++++ tests/store.rs | 123 +++++++++++++++++++++++++++++++++ 3 files changed, 309 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 226aa94..9e4c7c2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -20,6 +20,6 @@ pub mod wallet; pub mod wallet_child; pub use store::{ - Friend, FriendProfile, Message, Payment, PaymentWrite, SelfIdentity, Store, - resolve_store_passphrase, + Friend, FriendProfile, Message, NewWallet, Payment, PaymentWrite, SelfIdentity, Store, + WalletRecord, resolve_store_passphrase, }; diff --git a/src/store.rs b/src/store.rs index 676a1fa..9f5caae 100644 --- a/src/store.rs +++ b/src/store.rs @@ -177,6 +177,34 @@ pub struct PaymentWrite<'a> { pub verified: bool, } +/// Fields the caller supplies to add a wallet to the catalogue. `id` and +/// `created_at` are assigned by the store, never by the caller. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NewWallet { + /// Optional user label. Blank (or whitespace) is stored as SQL NULL. + pub name: Option, + /// The identity this wallet belongs to. Identity is the pubkey, so several + /// wallets may share one — this column is deliberately not unique. + pub identity_pubkey: [u8; 32], + /// The onion locator current at creation. A locator, not an identity: it + /// rotates (F4) and is allowed to be empty before the HS publishes. + pub onion_locator: String, + /// The wallet file name under the wallet dir. Unique: a second wallet must + /// get its own file rather than overwrite the first one's. + pub wallet_filename: String, +} + +/// One wallet in the catalogue: the row that makes a wallet survive a restart. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WalletRecord { + pub id: i64, + pub name: Option, + pub identity_pubkey: [u8; 32], + pub onion_locator: String, + pub wallet_filename: String, + pub created_at: i64, +} + impl Store { pub fn open() -> Result { Self::open_at(&home_dir()?) @@ -275,6 +303,21 @@ impl Store { no_spend INTEGER NOT NULL, updated_at INTEGER NOT NULL ); + -- The wallet catalogue: one row per wallet file this install knows + -- about, so a created wallet is remembered across restarts (the + -- wallet child's own config only describes the one it is pointed at + -- right now). `identity_pubkey` is the owning identity and is NOT + -- unique — identity is the roster key, while a wallet is one file; + -- `onion_locator` is a locator and may be stale or empty. + CREATE TABLE IF NOT EXISTS wallets ( + id INTEGER PRIMARY KEY, + name TEXT, + identity_pubkey BLOB NOT NULL, + onion_locator TEXT NOT NULL DEFAULT '', + wallet_filename TEXT NOT NULL UNIQUE, + created_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS wallets_by_created ON wallets (created_at, id); CREATE TABLE IF NOT EXISTS payments ( id INTEGER PRIMARY KEY, friend_id INTEGER NOT NULL REFERENCES friends(id), @@ -418,6 +461,93 @@ impl Store { })) } + /// Add a wallet to the catalogue and return the stored row (id and + /// `created_at` assigned here). This is the only way a wallet becomes + /// remembered: the wallet file on disk is not a directory listing the app + /// scans. + /// + /// `wallet_filename` is unique. Creating a second wallet is not a rewrite of + /// the first — it must be handed its own file name, otherwise both wallets + /// would open the same file and the second would look like a failed create. + pub fn create_wallet(&self, w: &NewWallet) -> Result { + let filename = w.wallet_filename.trim(); + if filename.is_empty() { + return Err(Error("wallet filename required".into())); + } + let name = w.name.as_deref().map(str::trim).filter(|n| !n.is_empty()); + let taken: Option = self + .conn + .query_row( + "SELECT id FROM wallets WHERE wallet_filename = ?1", + params![filename], + |row| row.get(0), + ) + .optional()?; + if let Some(id) = taken { + return Err(Error(format!( + "wallet filename already in use: {filename} (wallet {id})" + ))); + } + let created_at = unix_now(); + self.conn.execute( + "INSERT INTO wallets (name, identity_pubkey, onion_locator, wallet_filename, created_at) + VALUES (?1, ?2, ?3, ?4, ?5)", + params![ + name, + w.identity_pubkey.as_slice(), + w.onion_locator, + filename, + created_at + ], + )?; + Ok(WalletRecord { + id: self.conn.last_insert_rowid(), + name: name.map(str::to_string), + identity_pubkey: w.identity_pubkey, + onion_locator: w.onion_locator.clone(), + wallet_filename: filename.to_string(), + created_at, + }) + } + + /// One wallet by row id, or `None` when there is no such wallet. + pub fn get_wallet_by_id(&self, id: i64) -> Result> { + Ok(self + .conn + .query_row( + "SELECT id, name, identity_pubkey, onion_locator, wallet_filename, created_at + FROM wallets WHERE id = ?1", + params![id], + wallet_row, + ) + .optional()?) + } + + /// Every known wallet, oldest first (row id breaks a `created_at` tie, so + /// the order a wallet-selection screen shows is stable across runs). + pub fn list_wallets(&self) -> Result> { + let mut stmt = self.conn.prepare( + "SELECT id, name, identity_pubkey, onion_locator, wallet_filename, created_at + FROM wallets ORDER BY created_at, id", + )?; + let rows = stmt + .query_map([], wallet_row)? + .collect::, _>>()?; + Ok(rows) + } + + /// Forget a wallet. `true` when a row was removed, `false` when there was + /// nothing to remove (an unknown id is not an error). + /// + /// This drops the catalogue row only; the wallet file on disk and the + /// payments already recorded stay where they are. + pub fn delete_wallet(&self, id: i64) -> Result { + let removed = self + .conn + .execute("DELETE FROM wallets WHERE id = ?1", params![id])?; + Ok(removed > 0) + } + pub fn replace_identity_keys( &self, identity_sk: &[u8], @@ -1651,6 +1781,31 @@ fn unix_now() -> i64 { .unwrap_or(0) } +/// Read one `wallets` row. A pubkey column that is not exactly 32 bytes is a +/// corrupt row, not a value to guess at. +fn wallet_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { + let pubkey: Vec = row.get(2)?; + let len = pubkey.len(); + let identity_pubkey: [u8; 32] = pubkey.try_into().map_err(|_| { + rusqlite::Error::FromSqlConversionFailure( + 2, + rusqlite::types::Type::Blob, + Box::new(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("identity_pubkey is {len} bytes, expected 32"), + )), + ) + })?; + Ok(WalletRecord { + id: row.get(0)?, + name: row.get(1)?, + identity_pubkey, + onion_locator: row.get(3)?, + wallet_filename: row.get(4)?, + created_at: row.get(5)?, + }) +} + /// AAD for the sealed wallet-child row. Domain-separates it from message and /// outbox blobs that share the same store data key. const WALLET_CHILD_AAD: &[u8] = b"onionwire/wallet-child/v1"; @@ -2308,4 +2463,33 @@ mod at_rest { } } } + + /// An install that predates the `wallets` table (the Android upgrade path) + /// gains it on the next open, and keeps everything else it had: the schema + /// is additive (`CREATE TABLE IF NOT EXISTS` on every open). + #[test] + fn a_store_without_the_wallets_table_gains_it_on_reopen() { + let dir = tempfile::tempdir().unwrap(); + let wallet = crate::store::NewWallet { + name: Some("First".into()), + identity_pubkey: [9u8; 32], + onion_locator: "w.onion".into(), + wallet_filename: "onionwire".into(), + }; + { + let store = Store::open_at_with_passphrase(dir.path(), "upgrade-pass").unwrap(); + let row = store.create_wallet(&wallet).unwrap(); + assert_eq!(store.get_wallet_by_id(row.id).unwrap().unwrap(), row); + // Simulate a pre-`wallets` install. + store.conn.execute_batch("DROP TABLE wallets").unwrap(); + } + let store = Store::open_at_with_passphrase(dir.path(), "upgrade-pass").unwrap(); + assert!( + store.list_wallets().unwrap().is_empty(), + "the dropped table comes back empty, not missing" + ); + let row = store.create_wallet(&wallet).unwrap(); + assert_eq!(store.list_wallets().unwrap().len(), 1); + assert_eq!(store.get_wallet_by_id(row.id).unwrap().unwrap(), row); + } } diff --git a/tests/store.rs b/tests/store.rs index c9fee33..ddf7d5c 100644 --- a/tests/store.rs +++ b/tests/store.rs @@ -540,3 +540,126 @@ fn ratchet_state_survives_reopening_the_store() { assert_eq!(store.load_ratchet(&pk(1)).expect("load"), Some(blob)); assert_eq!(store.list_messages(&pk(1)).unwrap()[0].plaintext, b"hello"); } + +// ---- the wallet catalogue (`wallets`) -------------------------------------- +// +// Several wallet *files* live under one identity: the row here is what makes a +// wallet survive a restart, because the wallet child's own config only ever +// describes the one it is pointed at right now. + +fn new_wallet(filename: &str, name: Option<&str>) -> onionwire::NewWallet { + onionwire::NewWallet { + name: name.map(str::to_string), + identity_pubkey: pk(7), + onion_locator: "walletloc.onion".to_string(), + wallet_filename: filename.to_string(), + } +} + +#[test] +fn create_wallet_stores_every_field_and_reads_it_back() { + let dir = tempfile::tempdir().expect("tempdir"); + let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open"); + + let row = store + .create_wallet(&new_wallet("savings", Some("Savings"))) + .expect("create"); + assert!(row.id > 0, "id assigned: {row:?}"); + assert!(row.created_at > 0, "created_at stamped: {row:?}"); + assert_eq!(row.wallet_filename, "savings"); + assert_eq!(row.name.as_deref(), Some("Savings")); + assert_eq!(row.identity_pubkey, pk(7)); + assert_eq!(row.onion_locator, "walletloc.onion"); + + let got = store + .get_wallet_by_id(row.id) + .expect("get") + .expect("row exists"); + assert_eq!(got, row, "the stored row is what came back"); +} + +#[test] +fn multiple_wallets_coexist_and_survive_a_reopen() { + let dir = tempfile::tempdir().expect("tempdir"); + let (spending, savings) = { + let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open"); + let spending = store + .create_wallet(&new_wallet("spending", Some("Spending"))) + .expect("spending"); + let savings = store + .create_wallet(&new_wallet("savings", None)) + .expect("savings"); + assert_ne!(spending.id, savings.id, "two wallets, two rows"); + (spending.id, savings.id) + }; + + let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("reopen"); + let rows = store.list_wallets().expect("list"); + assert_eq!(rows.len(), 2, "both wallets remembered: {rows:?}"); + assert_eq!(rows[0].id, spending, "creation order"); + assert_eq!(rows[1].id, savings); + assert_eq!( + rows[1].name, None, + "an unlabelled wallet round-trips as None" + ); + assert_eq!(rows[1].wallet_filename, "savings"); +} + +#[test] +fn a_second_wallet_cannot_reuse_a_wallet_filename() { + let dir = tempfile::tempdir().expect("tempdir"); + let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open"); + let first = store + .create_wallet(&new_wallet("onionwire", None)) + .expect("first"); + + let err = store + .create_wallet(&new_wallet("onionwire", Some("Clash"))) + .expect_err("a duplicate filename must not overwrite the first wallet"); + assert!( + err.to_string().contains("onionwire"), + "names the file: {err}" + ); + + let rows = store.list_wallets().expect("list"); + assert_eq!(rows.len(), 1, "the rejected insert left one row: {rows:?}"); + assert_eq!(rows[0], first, "the first wallet is untouched"); +} + +#[test] +fn delete_wallet_removes_only_that_row() { + let dir = tempfile::tempdir().expect("tempdir"); + let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open"); + let a = store.create_wallet(&new_wallet("a", None)).expect("a"); + let b = store.create_wallet(&new_wallet("b", None)).expect("b"); + + assert!(store.delete_wallet(a.id).expect("delete"), "row was there"); + assert_eq!(store.get_wallet_by_id(a.id).expect("get"), None); + let rows = store.list_wallets().expect("list"); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].id, b.id); + + assert!( + !store + .delete_wallet(9999) + .expect("unknown id is not an error"), + "nothing to delete reports false" + ); +} + +#[test] +fn a_wallet_without_a_label_or_locator_stores_nulls_and_rejects_a_blank_filename() { + let dir = tempfile::tempdir().expect("tempdir"); + let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open"); + + let mut blank = new_wallet("blank", Some(" ")); + blank.onion_locator = String::new(); + let row = store.create_wallet(&blank).expect("blank label"); + assert_eq!(row.name, None, "a whitespace label is no label"); + assert_eq!(row.onion_locator, "", "a locator may be empty pre-publish"); + + let err = store + .create_wallet(&new_wallet(" ", None)) + .expect_err("an empty filename cannot name a wallet file"); + assert!(err.to_string().contains("filename"), "{err}"); +} From 99a4ab640e91841aedf4dcb88bc326e91252daa5 Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 21 Sep 2026 10:41:53 -0400 Subject: [PATCH 08/78] tui: wallet selection screen (F6 -> w) with create as the last row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Screen::WalletSelect: a table of saved wallets — name, identity prefix, locator prefix, creation day — the selected row's full identity and locator under it, and a `+ create new wallet` row as the last item. j/k or arrows move, Enter takes the choice, Esc back. Empty, failed and in-flight reads each get their own copy; a wallet with a NULL label, no published locator or no usable timestamp reads `(unlabelled)` / `-` / `unknown` rather than blank. Presentation only. Rows are plain display data (WalletRow) built by the caller; the render path never reads the store, and the selection is by row index because two records may share an identity key. Loading a chosen record into the session is the wallet-store integration step, so the F6 `w` entry opens the screen on its unavailable state until that accessor lands, and the create row works today either way. Evidence: tests/tui_select.rs (16 tests) drives the real draw path through TestBackend at 80x24, 120x40 and 200x60, pins the dumped frame's footer to status_footer_phased(..., wallet_select_footer_hint()), asserts exactly one focus marker, a cell-width line budget from 20 to 200 columns, the window disclosure with the create row always visible, hostile labels (ESC/BEL/C1/ bidi/newline/tab) and the crate-local UTC date formatter. --- docs/TUI.md | 23 +- src/tui.rs | 599 +++++++++++++++++++++++++++++++++++++++++++- tests/tui_select.rs | 475 +++++++++++++++++++++++++++++++++++ 3 files changed, 1095 insertions(+), 2 deletions(-) create mode 100644 tests/tui_select.rs diff --git a/docs/TUI.md b/docs/TUI.md index 9c52c70..7b64afd 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -23,6 +23,7 @@ ASCII chrome. | `Profile` | `/profile` | Edit name, bio, optional Monero address | | `ConfirmKeys` / `Passphrase` | `/backup`, `/restore` | Type `BACKUP`/`RESTORE`, then passphrase | | `Wallet` | `F6` | Receive QR, balance, transfers, child, chain source | +| `WalletSelect` | `F6` `w` | Saved wallets, pick one or create one | | `WalletSetup` | `F6` `c` / `i`, or `/wallet create` / `import` | Spend warning, seed, import | | `WalletsSettings` | `F9` or `/settings` | Discovery menu (does not replace F-keys) | | `PeerPayments` | F9 then `p` | Peer-scoped `/pay` / `/tip` history | @@ -109,12 +110,13 @@ Pane-specific (`pane_footer_hints`): Footer: ``` -c create i import r qr s/x child 1 pruned 2 full 3 testnet Esc back ? help +c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help ``` | Key | Effect | |---|---| | `r` or Enter | Toggle receive-address QR | +| `w` | Saved wallets (`WalletSelect`) | | `c` | Create wallet (`SPEND` then seed once, type `SEEN`) | | `i` | Import 25-word seed | | `s` | Start app-owned wallet child | @@ -133,6 +135,24 @@ feature name. Create/import require the wallet RPC started with `--wallet-dir`. Filename: `onionwire`. Seed is never collected on the composer. +## Saved wallets (`F6` then `w`) + +`WalletSelect`. One row per persisted wallet — name, identity prefix, locator +prefix, creation day — plus the selected row's full identity and locator under +the table. `j`/`k` or arrows select, Enter opens the selection, Esc back to +Main. Footer: `Esc back j k select Enter open ? help`. + +The last item is **not** a wallet: `+ create new wallet` starts the same create +flow as `F6` `c`, so an empty list still has a way forward. An unlabelled wallet +(`NULL` in the store) reads `(unlabelled)`; a wallet whose onion service is not +published yet reads `-`; an unknown creation time reads `unknown`. A read that +failed is named on the screen — that is a different state from `no saved wallets +yet`, and the two never share copy. + +Rows are plain display data (`WalletRow`), built by the caller from +`Store::list_wallets`; the render path never reads the store. Selection is by +row index, not by identity key (two records may share one). + ## Wallets & settings (`F9` / `/settings`) Discovery layer, not a replacement. Function keys stay live on this screen. @@ -180,4 +200,5 @@ Floor **80×24**. Target **120×40**. Frame dumps: ``` cargo test --locked --test tui_spec -- --nocapture dump_spec_frames cargo test --locked --test tui_spec -- --nocapture wallets_settings_menu_frame_dumps +cargo test --locked --test tui_select -- --nocapture wallet_select_frame_dumps ``` diff --git a/src/tui.rs b/src/tui.rs index a72d071..7e7b9eb 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1288,6 +1288,12 @@ enum Screen { PeerPayments { state: PeerPaymentsState, }, + /// F6 → `w`: pick a saved wallet, or create one. The rows are a snapshot + /// like the other two, and the `create new wallet` row is part of the list + /// rather than a separate key. + WalletSelect { + state: WalletSelectState, + }, Quit { prompt: QuitPrompt, }, @@ -1425,6 +1431,9 @@ impl App { let mut open_payments = false; let mut payments_back = false; let mut payments_move = 0i32; + let mut select_back = false; + let mut select_move = 0i32; + let mut select_enter = false; // The function-key shortcuts stay live on the WALLETS & SETTINGS screen // and the peer history too: the settings screen's whole point is naming @@ -1666,6 +1675,9 @@ impl App { Screen::Wallet { .. } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Char('r') | KeyCode::Enter => self.wallet_toggle_qr(), + // `w` is the wallet list: the F6 screen is about the wallet you + // are on, and this is how you get off it. + KeyCode::Char('w') => self.open_wallet_select(), KeyCode::Char('s') => self.wallet_child_start(), KeyCode::Char('x') => self.wallet_child_stop(), KeyCode::Char('p') => self.wallet_child_probe(), @@ -1698,6 +1710,13 @@ impl App { KeyCode::Down | KeyCode::Char('j') => payments_move = 1, _ => {} }, + Screen::WalletSelect { .. } => match key.code { + KeyCode::Esc => select_back = true, + KeyCode::Up | KeyCode::Char('k') => select_move = -1, + KeyCode::Down | KeyCode::Char('j') => select_move = 1, + KeyCode::Enter => select_enter = true, + _ => {} + }, Screen::Quit { prompt } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Enter => match prompt.on_char('\n') { @@ -1729,6 +1748,22 @@ impl App { if payments_back { self.screen = Screen::Main; } + if select_move != 0 + && let Screen::WalletSelect { state } = &mut self.screen + { + if select_move < 0 { + state.select_prev(); + } else { + state.select_next(); + } + } + if select_back { + // A full surface like the F9 menu: Esc leaves it for the main view. + self.screen = Screen::Main; + } + if select_enter { + self.choose_wallet()?; + } if open_payments { self.open_peer_payments()?; } @@ -2037,6 +2072,45 @@ impl App { Ok(()) } + /// Enter on the wallet selection screen: `create new wallet` starts the + /// existing creation flow, and a wallet row is a choice the app has to + /// resolve. + /// + /// Resolving a row into the session is the wallet-store integration step: + /// the record's identity and locator have to be read back and loaded, and + /// `Node` has no wallet-record accessor yet. Until that lands the choice is + /// reported instead of silently dropped — an Enter that does nothing is + /// worse than one that says what is missing. + fn choose_wallet(&mut self) -> Result<(), String> { + let Screen::WalletSelect { state } = &self.screen else { + return Ok(()); + }; + match state.choice() { + WalletChoice::Create => { + self.screen = Screen::WalletSetup(WalletSetup::CreateWarn { + typed: String::new(), + }); + } + WalletChoice::Open(_) => { + self.status_note = Some("wallet switching is not wired up yet".into()); + } + } + Ok(()) + } + + /// F6 `w`: the wallet selection screen. + /// + /// The rows come from the wallet store; reading them is the integration + /// card's step (`Store::list_wallets`), and the render path never touches + /// the store. Until that accessor exists the screen opens on its + /// unavailable state, which says so — the `create new wallet` row at the + /// bottom works either way. + fn open_wallet_select(&mut self) { + self.screen = Screen::WalletSelect { + state: WalletSelectState::error(SELECT_UNAVAILABLE.to_string()), + }; + } + /// `c` on the WALLETS & SETTINGS menu: copy the receive address through the /// terminal's own clipboard (OSC 52 — no crate, and it survives SSH). The /// address never touches a file. @@ -2578,6 +2652,17 @@ impl App { ); draw_peer_payments(f, state, &footer) } + Screen::WalletSelect { state } => { + let footer = status_footer_phased( + f.area().width, + &self.me_fp, + &self.me_onion, + Some(TorPhase::of(self.node.tor_state())), + self.status_note.as_deref(), + footer_hints(&self.screen), + ); + draw_wallet_select(f, state, &footer) + } } if self.help_open { draw_text_overlay(f, "? help", help_overlay_text()); @@ -3193,7 +3278,7 @@ match screen { }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", Screen::Wallet { .. } => { - "c create i import r qr s/x child 1 pruned 2 full 3 testnet Esc back ? help" + "c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help" } Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => { @@ -3203,6 +3288,7 @@ match screen { Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help", Screen::WalletsSettings { .. } => wallets_settings_footer_hint(), Screen::PeerPayments { .. } => peer_payments_footer_hint(), + Screen::WalletSelect { .. } => wallet_select_footer_hint(), Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help", } } @@ -4351,6 +4437,497 @@ pub fn draw_peer_payments(f: &mut Frame, state: &PeerPaymentsState, footer: &str ); } +/// One persisted wallet, display-ready. +/// +/// Plain data on purpose: the render path never reads the store, so the screen +/// takes rows the caller built. `name`, `identity_pubkey` and `onion_locator` +/// are untrusted display data (a label the user typed), sanitized at draw time. +/// +/// The store's `WalletRecord` maps onto this like so — +/// `name: r.name.unwrap_or_default()` (a blank label is the placeholder +/// `(unlabelled)` on screen), `identity_pubkey: hex(r.identity_pubkey)` (the +/// column is `[u8; 32]`, so it is encoded here as text), `onion_locator: +/// r.onion_locator` (empty until the HS is published — that renders as `-`), +/// `created_at: r.created_at`. `wallet_filename` is deliberately not carried: +/// it is not on the screen, and the render path has no business with a path. +/// +/// Selection is by **row index**, never by identity: two records may share an +/// identity key, so `WalletChoice::Open` names a position, not a wallet. +#[derive(Clone, Debug, Default)] +pub struct WalletRow { + /// User-given label. Empty means unlabelled (`NULL` in the store) and the + /// row says so rather than leaving the primary cell blank. + pub name: String, + /// The wallet's identity public key, hex. + pub identity_pubkey: String, + /// The wallet's v3 onion locator, without the `.onion` suffix. Empty until + /// the service is published. + pub onion_locator: String, + /// Creation time, unix seconds UTC. `0` (or negative) means unknown. + pub created_at: i64, +} + +/// What Enter does on the selection screen. +/// +/// The index is into the state's `rows` (display order), never into the store's +/// ids: the render path does not know them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WalletChoice { + /// Open the wallet at this index. + Open(usize), + /// The `create new wallet` row — the last item in the list. + Create, +} + +/// What the wallet selection screen draws. +/// +/// One item in the list is not a wallet: the `create new wallet` row, always +/// last, so Enter on it can start the creation flow instead of loading a +/// record. `selected` indexes rows **plus** that trailing row, which is why +/// `rows.len()` is a legal index and `choice()` reads it as `Create`. +/// +/// `error` is display-ready and only set when the read itself failed — an +/// account with no saved wallets is an empty list, not an error. +#[derive(Clone, Debug, Default)] +pub struct WalletSelectState { + pub rows: Vec, + pub selected: usize, + /// The read is in flight. The create row is still listed: it does not + /// depend on the store, so Enter stays live while the list loads. + pub reading: bool, + /// Why the list could not be read, display-ready. + pub error: Option, +} + +impl WalletSelectState { + /// The list a read returned. An empty list is the first-run state. + pub fn from_rows(rows: Vec) -> Self { + Self { + rows, + selected: 0, + reading: false, + error: None, + } + } + + /// The read is in flight. Nothing is listed yet, so the selection sits on + /// the create row. + pub fn reading() -> Self { + Self { + rows: Vec::new(), + selected: 0, + reading: true, + error: None, + } + } + + /// The read failed. This is not "no wallets": the screen says so. + pub fn error(why: String) -> Self { + Self { + rows: Vec::new(), + selected: 0, + reading: false, + error: Some(why), + } + } + + /// Move down one item. The bottom is the create row and is sticky. + pub fn select_next(&mut self) { + self.selected = (self.selected + 1).min(self.rows.len()); + } + + /// Move up one item. The top is the first wallet (or create) and is sticky. + pub fn select_prev(&mut self) { + self.selected = self.selected.saturating_sub(1); + } + + /// The row under the marker, `None` on the create row. + pub fn selected_row(&self) -> Option<&WalletRow> { + self.rows.get(self.selected) + } + + /// What Enter means right now. One past the last wallet — and the only + /// item of an empty or failed list — is `Create`. + pub fn choice(&self) -> WalletChoice { + match self.rows.get(self.selected) { + Some(_) => WalletChoice::Open(self.selected), + None => WalletChoice::Create, + } + } +} + +/// Marker column in cells: `> ` when focused, ` ` otherwise. +const WALLET_MARK_W: usize = 2; +/// Identity column in cells: an 8-character prefix plus the ellipsis — 11 +/// cells under `ONIONWIRE_ASCII`, where the ellipsis is three dots, so that is +/// the width every column is padded to whatever the chrome is doing. +const WALLET_ID_W: usize = 11; +/// Locator column in cells, measured the same way as the identity column. +const WALLET_LOC_W: usize = 11; +/// Creation-day column in cells: `2026-09-21` is 10, and `unknown` is 7. +const WALLET_SINCE_W: usize = 10; +/// Gap between two columns. +const WALLET_GAP: usize = 2; +/// Widest name column. The name is the flexible column and it is capped so the +/// trailing columns stay a table and not a 150-cell walk: every row pads to the +/// same column starts, which is what makes the rows scan as a grid. +const WALLET_NAME_W: usize = 28; +/// Cells the trailing columns need, marker included. +const WALLET_FIXED_W: usize = WALLET_MARK_W + + (WALLET_GAP + WALLET_ID_W) + + (WALLET_GAP + WALLET_LOC_W) + + (WALLET_GAP + WALLET_SINCE_W); + +/// `2026-09-21` for a unix second (UTC), or `unknown` when there is no usable +/// timestamp. Hand-rolled: this crate has no date dependency, and the screen +/// needs exactly one calendar date. +/// +/// Days-to-civil (Howard Hinnant's algorithm) — no leap-year table, no crate. +pub fn format_day_utc(secs: i64) -> String { + if secs <= 0 { + return "unknown".to_string(); + } + let z = secs.div_euclid(86_400) + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!("{year:04}-{month:02}-{day:02}") +} + +/// An identifying prefix of untrusted text: the first `keep` characters, closed +/// with the chrome's ellipsis, fitted into `cells`. +fn wallet_prefix(raw: &str, keep: usize, cells: usize) -> String { + let clean = menu_cell_text(raw); + let head: String = clean.chars().take(keep).collect(); + fit_cells(&format!("{head}{}", ellipsis()), cells) +} + +/// One laid-out grid line: marker, name, then whichever of the three trailing +/// columns fit. +/// +/// Trailing columns are **dropped** when the pane is too narrow, never wrapped, +/// so no row can overrun the pane — the same discipline as the payments grid, +/// and it holds below the 80-column floor too. +#[allow(clippy::too_many_arguments)] +fn wallet_grid_line( + w: usize, + marker: &str, + name: &str, + id: &str, + loc: &str, + since: &str, + marker_style: Style, + name_style: Style, + col_style: Style, +) -> Line<'static> { + let mut spans = vec![Span::styled(marker.to_string(), marker_style)]; + let inner = w.saturating_sub(cell_width(marker)); + let name_w = inner.saturating_sub(WALLET_FIXED_W).min(WALLET_NAME_W); + if name_w == 0 { + // Not even a name fits: the identity is the most identifying thing left. + spans.push(Span::styled( + fit_cells(&menu_cell_text(id), inner.max(1)), + col_style, + )); + return Line::from(spans); + } + spans.push(Span::styled( + pad_right(&fit_cells(name, name_w), name_w), + name_style, + )); + let mut used = name_w; + for (col_w, text) in [ + (WALLET_ID_W, id), + (WALLET_LOC_W, loc), + (WALLET_SINCE_W, since), + ] { + // An empty tail means the row has no more columns to give (the create + // row), and a column that does not fit takes the rest of them with it. + if text.is_empty() || inner < used + WALLET_GAP + col_w { + break; + } + spans.push(Span::raw(" ".repeat(WALLET_GAP))); + spans.push(Span::styled( + pad_right(&fit_cells(text, col_w), col_w), + col_style, + )); + used += WALLET_GAP + col_w; + } + Line::from(spans) +} + +/// The selected row's full identity and locator. The rows carry prefixes, which +/// is what makes the list scannable; the full values are what a user actually +/// verifies, so the strip under the table spells them out. +fn wallet_detail_lines(w: usize, row: &WalletRow) -> Vec> { + let mut out = vec![Line::default()]; + for (label, value) in [ + ("id", menu_cell_text(&row.identity_pubkey)), + ("onion", menu_cell_text(&row.onion_locator)), + ] { + let text = if value.trim().is_empty() { + "(none)".to_string() + } else { + value + }; + out.push(Line::from(vec![ + Span::styled(format!(" {label:<5} "), style_dim()), + Span::styled(fit_cells(&text, w.saturating_sub(9).max(1)), style_text()), + ])); + } + out +} + +/// The wallet selection body as styled lines for a `width` × `height` **inner** +/// pane. +/// +/// Fixed shape at the bottom: a blank, then the `create new wallet` row — the +/// one item that is not a wallet, always last, so the eye always knows where the +/// way out of an empty list is. The table above it windows and says how many +/// rows are out of view rather than dropping them silently. +pub fn wallet_select_lines(width: u16, height: u16, s: &WalletSelectState) -> Vec> { + let w = width as usize; + let h = height as usize; + let mut out: Vec> = Vec::new(); + + // The table is drawn only when there is a table to draw; empty, failed and + // in-flight reads say what they are instead of showing bare column heads. + let table = !s.rows.is_empty(); + if table { + out.push(wallet_grid_line( + w, + " ", + "name", + "identity", + "locator", + "since", + Style::default(), + style_dim(), + style_dim(), + )); + } else { + let (head, head_style, sub) = if let Some(err) = &s.error { + ( + "could not read saved wallets", + style_alert(), + menu_cell_text(err), + ) + } else if s.reading { + ( + "reading saved wallets", + style_dim(), + "one moment".to_string(), + ) + } else { + ( + "no saved wallets yet", + style_dim(), + "create one to get an identity and an onion address".to_string(), + ) + }; + out.push(Line::from(Span::styled( + fit_cells(&format!(" {head}"), w.max(1)), + head_style, + ))); + out.push(Line::from(Span::styled( + fit_cells(&format!(" {sub}"), w.max(1)), + style_dim(), + ))); + } + + // The full-value strip only where it cannot wrap, and its three cells are + // reserved whether or not the selection is a wallet, so the marker moving + // down to the create row never shifts the rows above it. + let strip = w >= 75 && h >= 14; + let strip_h = if strip { 3 } else { 0 }; + // One blank + the create row at the bottom. + let tail_h = 2; + let budget = h.saturating_sub(out.len() + strip_h + tail_h); + + if table { + let total = s.rows.len(); + let selected = s.selected.min(total - 1); + let windowed = total > budget && budget >= 5; + let visible = if windowed { + budget - 2 + } else { + budget.max(1).min(total) + }; + let start = if total <= visible { + 0 + } else { + selected.saturating_sub(visible - 1).min(total - visible) + }; + let end = (start + visible).min(total); + if windowed && start > 0 { + out.push(Line::from(Span::styled( + fit_cells(&format!(" {} {start} above", ellipsis()), w.max(1)), + style_dim(), + ))); + } + for (i, row) in s.rows.iter().enumerate().take(end).skip(start) { + // No row carries the marker when the selection has walked past the + // last wallet onto the create row. + let selected = s.selected < total && i == s.selected; + // A NULL label reads as a placeholder, and a wallet whose onion + // service is not published yet has no locator at all — both are + // states the row names, not blanks. + let name = { + let clean = menu_cell_text(&row.name); + if clean.trim().is_empty() { + "(unlabelled)".to_string() + } else { + clean + } + }; + let id = { + let clean = menu_cell_text(&row.identity_pubkey); + if clean.trim().is_empty() { + "-".to_string() + } else { + wallet_prefix(&clean, 8, WALLET_ID_W) + } + }; + let loc = { + let clean = menu_cell_text(&row.onion_locator); + if clean.trim().is_empty() { + "-".to_string() + } else { + wallet_prefix(&clean, 8, WALLET_LOC_W) + } + }; + out.push(wallet_grid_line( + w, + if selected { "> " } else { " " }, + &name, + &id, + &loc, + &format_day_utc(row.created_at), + if selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + Style::default() + }, + if selected { + style_text().add_modifier(Modifier::BOLD) + } else { + style_text() + }, + style_dim(), + )); + } + if windowed && end < total { + out.push(Line::from(Span::styled( + fit_cells(&format!(" {} {} below", ellipsis(), total - end), w.max(1)), + style_dim(), + ))); + } + } + + if strip { + let detail = if !table { + Vec::new() + } else { + s.selected_row() + .map(|row| wallet_detail_lines(w, row)) + .unwrap_or_default() + }; + // Reserved either way: the block is the same height whichever item the + // marker is on. + for i in 0..strip_h { + out.push(detail.get(i).cloned().unwrap_or_default()); + } + } + + // The create row closes the list, one blank line under the table, and the + // panel below it stays empty — the same top-packed shape as the F9 menu, so + // the eye finds the table at the top of every full-screen panel. + out.push(Line::default()); + let create_selected = s.rows.get(s.selected).is_none(); + out.push(wallet_grid_line( + w, + if create_selected { "> " } else { " " }, + "+ create new wallet", + "", + "", + "", + if create_selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + Style::default() + }, + if create_selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + style_text() + }, + style_dim(), + )); + out +} + +/// The body as plain text, for width/needle assertions. +pub fn wallet_select_text(width: u16, height: u16, s: &WalletSelectState) -> String { + wallet_select_lines(width, height, s) + .iter() + .map(|line| { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::() + }) + .collect::>() + .join("\n") +} + +/// Block title: the count is the reason the screen exists, so it is stated. +pub fn wallet_select_title(s: &WalletSelectState) -> String { + if s.rows.is_empty() { + "(o) wallets".to_string() + } else { + format!("(o) wallets {} {} saved", "\u{b7}", s.rows.len()) + } +} + +/// Wallet selection: a full screen like the F9 menu, with the same single +/// status line. `footer` is an already-built `status_footer` row. +pub fn draw_wallet_select(f: &mut Frame, s: &WalletSelectState, footer: &str) { + let area = f.area(); + let rows = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area); + f.render_widget( + Paragraph::new(wallet_select_lines( + rows[0].width.saturating_sub(2), + rows[0].height.saturating_sub(2), + s, + )) + .block(themed_block(&wallet_select_title(s))), + rows[0], + ); + f.render_widget( + Paragraph::new(fit_cells(footer, area.width as usize)).style(style_dim()), + rows[1], + ); +} + +/// The hint line the wallet selection screen prints, single-sourced for the +/// same reason as [`peer_payments_footer_hint`]: a frame-dump fixture must not +/// hand-copy it, or the dump shows a footer the app never renders. +pub fn wallet_select_footer_hint() -> &'static str { + WALLET_SELECT_FOOTER_HINT +} + +const WALLET_SELECT_FOOTER_HINT: &str = "Esc back j k select Enter open ? help"; + +/// The sub-line the screen prints when the wallet store has not been wired into +/// the app yet (see [`WalletRow`]): the list is genuinely unreadable, which is +/// not the same state as "no saved wallets". +pub const SELECT_UNAVAILABLE: &str = "the wallet store is not wired up yet"; + /// OSC 52 clipboard write for `text`: the terminal copies it, so no crate and /// no clipboard daemon are involved and it still works over SSH. A terminal /// that does not implement OSC 52 ignores the sequence. @@ -4651,6 +5228,26 @@ mod function_key_tests { } } + /// The wallet list names `Esc`, `j k` and `Enter`, no function key — so it + /// must not quietly answer one. Copy and behaviour have to agree in both + /// directions, or a key that works on every other screen becomes a surprise + /// here. + #[test] + fn the_wallet_select_screen_answers_no_function_key_it_does_not_name() { + let screen = Screen::WalletSelect { + state: WalletSelectState::default(), + }; + let hint = wallet_select_footer_hint(); + for number in [2u8, 3, 4, 5, 6, 8, 9] { + let named = hint.contains(&format!("F{number}")); + assert_eq!( + function_key_for(&screen, KeyCode::F(number)).is_some(), + named, + "F{number} and the hint disagree: {hint:?}" + ); + } + } + /// A screen that names no function key keeps the key to itself: the /// composer's `F`-less screens must not steal F-keys they never advertise. #[test] diff --git a/tests/tui_select.rs b/tests/tui_select.rs new file mode 100644 index 0000000..7447ec1 --- /dev/null +++ b/tests/tui_select.rs @@ -0,0 +1,475 @@ +//! Wallet selection screen (`F6` → `w`). +//! +//! The screen lists the persisted wallets and, last, the `create new wallet` +//! row. Assertions measure in terminal **cells** (`cell_width`, which goes +//! through `Span::width`) and accept either ellipsis form because +//! `ascii_chrome()` follows `NO_COLOR` / `ONIONWIRE_ASCII` and the TUI test +//! binaries run in parallel. + +use onionwire::tui::{ + TorPhase, WalletChoice, WalletRow, WalletSelectState, cell_width, draw_wallet_select, + format_day_utc, status_footer_phased, wallet_select_footer_hint, wallet_select_lines, + wallet_select_text, +}; +use ratatui::Terminal; +use ratatui::backend::TestBackend; + +const FP: &str = "abcdef0123456789deadbeefcafebabe"; +const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; +const ID_A: &str = "ab12cd34ef5678901234567890abcdef1234567890abcdef1234567890abcd"; +const ID_B: &str = "ff00aa11bb22cc33dd44ee55ff6677889900aabbccddeeff0011223344556677"; +const ONION_A: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx"; +const ONION_B: &str = "zyxwvutsrqponmlkjihgfedcba765432zyxwvutsrqponmlkjihgfedcba"; + +fn row(name: &str, id: &str, onion: &str, created_at: i64) -> WalletRow { + WalletRow { + name: name.into(), + identity_pubkey: id.into(), + onion_locator: onion.into(), + created_at, + } +} + +/// Two saved wallets plus the create row: the shape the screen opens on. +fn two_wallets() -> WalletSelectState { + WalletSelectState::from_rows(vec![ + row("lance", ID_A, ONION_A, 1_789_963_705), + row("cold", ID_B, ONION_B, 1_756_320_000), + ]) +} + +/// The row count is the wallet count **plus the create row**, which is always +/// the last item: Enter on it starts the creation flow, not a wallet load. +#[test] +fn selection_walks_every_row_and_ends_on_create() { + let mut st = two_wallets(); + assert_eq!( + st.choice(), + WalletChoice::Open(0), + "opens on the first wallet" + ); + + st.select_next(); + assert_eq!(st.choice(), WalletChoice::Open(1)); + st.select_next(); + assert_eq!( + st.choice(), + WalletChoice::Create, + "the create row is the last item in the list" + ); + + // Past the end is a no-op, not a panic: the bottom of the list is Create. + st.select_next(); + assert_eq!(st.choice(), WalletChoice::Create); + + st.select_prev(); + assert_eq!(st.choice(), WalletChoice::Open(1)); + st.select_prev(); + st.select_prev(); + assert_eq!( + st.choice(), + WalletChoice::Open(0), + "top of the list is sticky" + ); +} + +/// With no saved wallets the screen still has exactly one item — Create — so +/// Enter can never be a dead key on a first run. +#[test] +fn empty_state_still_offers_create() { + let st = WalletSelectState::default(); + assert_eq!(st.choice(), WalletChoice::Create); + assert!(st.selected_row().is_none()); +} + +/// A read that failed is not an empty list: the state says so. +#[test] +fn error_state_is_not_an_empty_list() { + let st = WalletSelectState::error("store lock poisoned".into()); + assert!(st.error.is_some()); + assert_eq!(st.choice(), WalletChoice::Create); +} + +/// The card's four fields, plus the create row, on the body at the 80-column +/// floor: name, identity prefix, locator prefix, creation date. +#[test] +fn wallet_select_lists_every_required_field() { + let body = wallet_select_text(78, 21, &two_wallets()); + for needle in [ + "name", // column header + "identity", // column header + "locator", // column header + "since", // column header + "lance", + "cold", // names + "ab12cd34", // identity prefix + "ff00aa11", // identity prefix of the second wallet + "abcdefgh", // locator prefix + "zyxwvuts", // locator prefix of the second wallet + "2026-09-21", // creation date + "2025-08-27", // creation date of the second wallet + "create new wallet", // the always-last row + ] { + assert!(body.contains(needle), "missing {needle:?}:\n{body}"); + } + // A prefix is a prefix: the row prints an identifying start, not the whole + // key (the full value belongs to the detail strip under the table). + let lance_row = body + .lines() + .find(|l| l.contains("lance")) + .expect("lance row"); + assert!( + !lance_row.contains(ID_A), + "a row printed the whole identity: {lance_row:?}" + ); + // Truncation is disclosed with the chrome's ellipsis (… or ...). + assert!( + body.contains('…') || body.contains("..."), + "no truncation marker on a prefix:\n{body}" + ); +} + +/// The create row is last, and the marker is on the selection — one marker +/// only, whichever row is focused. +#[test] +fn wallet_select_marks_exactly_one_row_and_puts_create_last() { + let mut st = two_wallets(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!(marked[0].contains("lance"), "{:?}", marked[0]); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row is not last:\n{body}" + ); + + st.select_next(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!(marked[0].contains("cold"), "{:?}", marked[0]); + + // The bottom of the list is the create row and it takes the marker too. + st.select_next(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!( + marked[0].contains("create new wallet"), + "the marker never reached the create row: {:?}", + marked[0] + ); +} + +/// A wallet with no label still identifies itself: the primary cell is a +/// placeholder, the row keeps its identity, and an unknown creation time is a +/// word, not a blank or a zero. +#[test] +fn wallet_select_names_an_unlabelled_wallet_and_an_unknown_date() { + let st = WalletSelectState::from_rows(vec![row("", ID_B, ONION_B, 0)]); + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("(unlabelled)"), + "a NULL label left the primary cell empty:\n{body}" + ); + assert!( + body.contains("ff00aa11"), + "an unlabelled wallet lost its identity:\n{body}" + ); + assert!( + body.contains("unknown"), + "an unknown creation date is blank:\n{body}" + ); + assert!( + !body.contains("1970-01-01"), + "epoch rendered as a date:\n{body}" + ); +} + +/// A wallet whose onion service has not been published yet has no locator. That +/// is a state, not an error: the cell says so and the row stays readable. +#[test] +fn wallet_select_renders_an_unpublished_locator_as_a_placeholder() { + let st = WalletSelectState::from_rows(vec![row("fresh", ID_A, "", 1_789_963_705)]); + let body = wallet_select_text(78, 21, &st); + let row_line = body + .lines() + .find(|l| l.contains("fresh")) + .expect("wallet row"); + assert!( + row_line.contains("2026-09-21"), + "an empty locator pushed the row out of shape: {row_line:?}" + ); + assert!( + row_line.contains(" - "), + "an unpublished locator has no placeholder: {row_line:?}" + ); + assert!( + !body.to_lowercase().contains("error") && !body.to_lowercase().contains("failed"), + "an unpublished locator read as a failure:\n{body}" + ); +} + +/// Empty, failed and in-flight reads are three different states, and none of +/// them is a blank pane. All three still offer the create row. +#[test] +fn wallet_select_words_the_empty_error_and_reading_states() { + let empty = wallet_select_text(78, 21, &WalletSelectState::default()); + assert!(empty.contains("no saved wallets"), "\n{empty}"); + assert!(empty.contains("create new wallet"), "\n{empty}"); + + let failed = wallet_select_text( + 78, + 21, + &WalletSelectState::error("store lock poisoned".into()), + ); + assert!(failed.contains("could not read"), "\n{failed}"); + assert!(failed.contains("store lock poisoned"), "\n{failed}"); + assert!(failed.contains("create new wallet"), "\n{failed}"); + // A failed read must not read as "you have no wallets". + assert!(!failed.contains("no saved wallets"), "\n{failed}"); + + let reading = wallet_select_text(78, 21, &WalletSelectState::reading()); + assert!(reading.contains("reading"), "\n{reading}"); + assert!(reading.contains("create new wallet"), "\n{reading}"); +} + +/// The whole point of a prefix is that the row cannot outgrow the pane: a row +/// with a name wide enough to swallow the table still truncates in cells. +#[test] +fn wallet_select_truncates_a_wide_name_in_cells() { + let st = WalletSelectState::from_rows(vec![row( + "私のウォレットはとても長い名前を持っています", + ID_A, + ONION_A, + 1_789_963_705, + )]); + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("私の"), + "a CJK name was dropped entirely:\n{body}" + ); + assert!( + body.contains('…') || body.contains("..."), + "a long name was clipped without an ellipsis:\n{body}" + ); + for line in body.lines() { + assert!( + cell_width(line) <= 78, + "line wider than the pane: {} cells: {line:?}", + cell_width(line) + ); + } +} + +/// Every body line fits the pane it was laid out for, from well under the +/// 80-column floor to 200 — trailing columns drop, nothing wraps. +#[test] +fn wallet_select_columns_drop_before_they_wrap() { + for w in 20u16..=200 { + for state in [ + two_wallets(), + WalletSelectState::default(), + WalletSelectState::error("store lock poisoned".into()), + WalletSelectState::reading(), + ] { + for line in wallet_select_lines(w, 21, &state) { + let width: usize = line + .spans + .iter() + .map(|s| cell_width(s.content.as_ref())) + .sum(); + assert!(width <= w as usize, "width {w}: {width} cells: {line:?}"); + } + } + } +} + +/// A long list windows and says how many rows are out of view; the create row +/// is never the row that falls off. +#[test] +fn wallet_select_windows_a_long_list_and_keeps_create_visible() { + let rows: Vec = (0..40) + .map(|i| row(&format!("w{i:02}"), ID_A, ONION_A, 1_789_963_705)) + .collect(); + let mut st = WalletSelectState::from_rows(rows); + let body = wallet_select_text(78, 21, &st); + assert!(body.contains("below"), "window not disclosed:\n{body}"); + assert!( + body.contains("w00"), + "the first row is not on screen:\n{body}" + ); + assert!(!body.contains("w39"), "\n{body}"); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row was pushed off the pane:\n{body}" + ); + + for _ in 0..39 { + st.select_next(); + } + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("w39"), + "the last row never came into view:\n{body}" + ); + assert!(body.contains("above"), "window not disclosed:\n{body}"); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row was pushed off the pane:\n{body}" + ); + assert_eq!(st.choice(), WalletChoice::Open(39)); +} + +/// The screen is not a sink for peer bytes: a label is untrusted display data. +#[test] +fn wallet_select_hostile_label_cannot_reach_the_terminal() { + let hostile = "safe\u{1b}[31mred\u{7}\u{202e}\u{2066}\u{9b}\nrow\ttab"; + let st = WalletSelectState::from_rows(vec![row(hostile, ID_A, ONION_A, 1_789_963_705)]); + for (w, h) in [(80u16, 24u16), (120, 40)] { + let screen = render(w, h, &st); + for (what, ch) in [ + ("ESC", '\u{1b}'), + ("BEL", '\u{7}'), + ("C1", '\u{9b}'), + ("bidi", '\u{202e}'), + ("bidi isolate", '\u{2066}'), + ] { + assert!(!screen.contains(ch), "{w}x{h}: {what} reached the frame"); + } + assert!(screen.contains("safe"), "{w}x{h}:\n{screen}"); + } + let body = wallet_select_text(78, 21, &st); + assert!(body.contains("safe[31mred"), "\n{body}"); + assert_eq!( + body.lines().filter(|l| l.contains("safe[31mred")).count(), + 1, + "the hostile label split or duplicated a row:\n{body}" + ); +} + +/// Days from unix seconds, UTC, without a date crate — including a leap day and +/// the epoch, which reads as "unknown" rather than 1970-01-01. +#[test] +fn format_day_utc_covers_the_calendar_edges() { + for (secs, want) in [ + (0i64, "unknown"), + (-1, "unknown"), + (1, "1970-01-01"), + (86_400, "1970-01-02"), + (951_782_400, "2000-02-29"), + (1_700_000_000, "2023-11-14"), + (1_789_963_705, "2026-09-21"), + ] { + assert_eq!(format_day_utc(secs), want, "{secs}"); + } +} + +/// The app renders this screen's one status line with `status_footer_phased` +/// and `footer_hints`; the fixture does the same, so a dumped frame can never +/// show a footer the app does not draw. +fn render(w: u16, h: u16, st: &WalletSelectState) -> String { + let backend = TestBackend::new(w, h); + let mut terminal = Terminal::new(backend).expect("terminal"); + let footer = status_footer_phased( + w, + FP, + ONION, + Some(TorPhase::Ready), + None, + wallet_select_footer_hint(), + ); + terminal + .draw(|f| draw_wallet_select(f, st, &footer)) + .expect("draw"); + let buf = terminal.backend().buffer(); + let mut screen = String::new(); + for y in 0..h { + for x in 0..w { + screen.push_str(buf[(x, y)].symbol()); + } + screen.push('\n'); + } + screen +} + +#[test] +fn wallet_select_frame_shows_the_shipped_footer() { + let shipped = status_footer_phased( + 80, + FP, + ONION, + Some(TorPhase::Ready), + None, + wallet_select_footer_hint(), + ); + let frame = render(80, 24, &two_wallets()); + let last = frame.lines().nth(23).unwrap_or_default(); + assert_eq!( + last.trim_end(), + shipped.trim_end(), + "the dumped frame's footer is not the one the app renders" + ); +} + +#[test] +fn wallet_select_frames_fit_at_the_three_sizes() { + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + let screen = render(w, h, &two_wallets()); + for needle in [ + "(o) wallets", + "2 saved", + "lance", + "2026-09-21", + "create new wallet", + "? help", + ] { + assert!( + screen.contains(needle), + "{w}x{h} missing {needle:?}:\n{screen}" + ); + } + for line in screen.lines() { + assert!( + cell_width(line) <= w as usize, + "line wider than {w} at {w}x{h}: {line:?}" + ); + } + let lines = wallet_select_lines(w - 2, h - 3, &two_wallets()); + assert!( + lines.len() <= (h - 3) as usize, + "body needs {} rows, {w}x{h} shows {}", + lines.len(), + h - 3 + ); + } + // 200x60 fits the whole identity and locator in the detail strip. + let wide = render(200, 60, &two_wallets()); + assert!( + wide.contains(ID_A), + "200x60 truncated the identity:\n{wide}" + ); + assert!( + wide.contains(ONION_A), + "200x60 truncated the locator:\n{wide}" + ); +} + +#[test] +fn wallet_select_frame_dumps() { + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + println!("===== WALLETS {w}x{h} ====="); + print!("{}", render(w, h, &two_wallets())); + println!("===== WALLETS (empty) {w}x{h} ====="); + print!("{}", render(w, h, &WalletSelectState::default())); + println!("===== WALLETS (failed read) {w}x{h} ====="); + print!( + "{}", + render( + w, + h, + &WalletSelectState::error("store lock poisoned".into()) + ) + ); + } +} From 0043fa0b34827de84f7fe446eccac97c709b04eb Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 21 Sep 2026 10:57:55 -0400 Subject: [PATCH 09/78] node: remember a created wallet in the store's catalogue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A wallet created in-app was never remembered: `Node::wallet_create` called the RPC and returned the seed, and the wallet file name was the one hardcoded `wallet::DEFAULT_WALLET_FILENAME` ("onionwire"). A second create reused that name, so the RPC refused it (or opened the first wallet's file) and no row was ever written — the "cannot create a new wallet, and nothing survives a restart" report. Creation and import now go through the catalogue (t_64c9ba3c's `Store::{create_wallet,list_wallets}`): - each create/import gets its own file name, `onionwire-` for the first `n` the catalogue does not hold, so several wallets coexist; - the stored row (id, identity, locator, file, created_at) is returned: `Node::wallet_create` -> `CreatedWallet` (row + the one-time seed, with a redacting `Debug`), `Node::wallet_restore` -> `WalletRecord`; - `Node::list_wallets` reads the catalogue without dialing; - the child config is re-pointed at the new file (read-modify-write, so the sealed RPC creds survive) — a row the child never opens would still be a broken wallet. The SDK keeps its UniFFI signature (`create_wallet -> String` seed, `import_wallet -> ()`), so no Kotlin change: it unwraps `.seed`. TDD: 5 new `src/node.rs` cases (row + list, two wallets + reopen, import, wallet-off empty list, child re-pointed) over a loopback wallet-RPC mock. `cargo test --locked` exit 0, `cargo clippy --locked --all-targets -- -D warnings` clean, and the same two commands are clean in `crates/onionwire-sdk`. --- crates/onionwire-sdk/src/lib.rs | 13 +- src/node.rs | 258 ++++++++++++++++++++++++++++++-- src/tui.rs | 6 +- 3 files changed, 262 insertions(+), 15 deletions(-) diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 154b602..4040664 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -587,20 +587,27 @@ impl Wire { /// Create a new spend-capable wallet. Returns the 25-word seed once so the /// UI can show a backup screen. The user does not paste a key on this path. /// Requires `ONIONWIRE_WALLET_RPC` pointed at a `--wallet-dir` RPC. + /// + /// The core also records the new wallet in its catalogue (`Node::wallet_create` + /// returns the stored row); the seed is what this surface carries. pub async fn create_wallet(&self, password: String) -> WResult { - self.node()? + Ok(self + .node()? .wallet_create(&password) .await - .map_err(WireError::new) + .map_err(WireError::new)? + .seed) } /// Import a wallet from an existing 25-word seed. This is the only path - /// that takes a user-supplied secret. + /// that takes a user-supplied secret. Like a create, the core records the + /// imported wallet in its catalogue. pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> { self.node()? .wallet_restore(&password, &seed) .await .map_err(WireError::new) + .map(|_| ()) } /// Start the app-owned wallet child (`monero-wallet-rpc`, plus `monerod` for diff --git a/src/node.rs b/src/node.rs index fcc8015..120696b 100644 --- a/src/node.rs +++ b/src/node.rs @@ -28,7 +28,9 @@ use crate::ratchet::{RatchetKeyPair, RatchetState}; use crate::ratelimit::TokenBucket; use crate::sanitize; use crate::session::{self, Keys}; -use crate::store::{Friend, FriendProfile, Message, Payment, PaymentWrite, Store}; +use crate::store::{ + Friend, FriendProfile, Message, NewWallet, Payment, PaymentWrite, Store, WalletRecord, +}; use crate::wallet::{self, ChainNetwork, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus}; use crate::wallet_child::{ChildConfig, WalletChild, WalletChildState, WalletChildStatus}; @@ -80,6 +82,29 @@ impl Drop for WorkerHandle { } } +/// A wallet just created on the wallet RPC and recorded in the store's +/// catalogue: the row is what makes it survive a restart, and the seed is the +/// one-time backup the UI shows before the wallet is used. The caller owns +/// wiping `seed` (the TUI moves it straight into a `Zeroizing`). +pub struct CreatedWallet { + /// The stored catalogue row, with the id and `created_at` the store + /// assigned. `wallet_filename` is the file this wallet lives in. + pub record: WalletRecord, + /// The 25-word seed, returned once by the create path. + pub seed: String, +} + +/// Hand-written so a stray `{:?}` cannot print the seed: the record is the +/// wallet, the mnemonic is the money. +impl std::fmt::Debug for CreatedWallet { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CreatedWallet") + .field("record", &self.record) + .field("seed", &"") + .finish() + } +} + pub struct Node { home: PathBuf, store: Arc>, @@ -1167,27 +1192,106 @@ impl Node { Ok(rows.into_iter().take(cap).collect()) } - /// Create a new spend-capable wallet. Returns the seed once for backup. - /// The user never pastes a key on this path. - pub async fn wallet_create(&self, password: &str) -> Result { + /// Create a new spend-capable wallet and record it in the catalogue. The + /// user never pastes a key on this path. + /// + /// The wallet file gets its own name ([`Self::next_wallet_filename`]): + /// `wallet_filename` is UNIQUE, so a second create that reused the old + /// hardcoded name would open the first wallet's file — or be refused by the + /// RPC outright, which is the "cannot create a new wallet" failure. The + /// stored row is what makes the wallet survive a restart; the wallet dir is + /// not scanned. + pub async fn wallet_create(&self, password: &str) -> Result { let w = self.wallet_snapshot(); if !w.configured() { return Err(wallet::NOT_CONFIGURED_MSG.into()); } - w.create_wallet(wallet::DEFAULT_WALLET_FILENAME, password) + let filename = self.next_wallet_filename()?; + let seed = w + .create_wallet(&filename, password) .await - .map_err(|e| e.to_string()) + .map_err(|e| e.to_string())?; + let record = self + .record_wallet(&filename) + .map_err(|e| format!("wallet {filename} created but not remembered: {e}"))?; + self.point_child_at(&filename).map_err(|e| { + format!("wallet {filename} created but the child is not pointed at it: {e}") + })?; + Ok(CreatedWallet { record, seed }) } /// Import a wallet from an existing 25-word seed. This is the only path - /// that takes a user-supplied secret. - pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<(), String> { + /// that takes a user-supplied secret — and, like a create, it is remembered + /// in the catalogue under its own file name. + pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result { let w = self.wallet_snapshot(); if !w.configured() { return Err(wallet::NOT_CONFIGURED_MSG.into()); } - w.restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed) + let filename = self.next_wallet_filename()?; + w.restore_wallet(&filename, password, seed) .await + .map_err(|e| e.to_string())?; + let record = self + .record_wallet(&filename) + .map_err(|e| format!("wallet {filename} imported but not remembered: {e}"))?; + self.point_child_at(&filename).map_err(|e| { + format!("wallet {filename} imported but the child is not pointed at it: {e}") + })?; + Ok(record) + } + + /// Every wallet this install remembers, oldest first. A store read: it must + /// work with no wallet RPC configured, and it never dials. + pub fn list_wallets(&self) -> Result, String> { + self.store + .lock() + .map_err(|e| e.to_string())? + .list_wallets() + .map_err(|e| e.to_string()) + } + + /// The file name a wallet created now should live in. `wallet_filename` is + /// UNIQUE and the catalogue is the only directory the app has, so this is + /// `-` for the first `n` the catalogue does not already hold. + fn next_wallet_filename(&self) -> Result { + let taken = self.list_wallets()?; + for n in 1.. { + let candidate = format!("{}-{}", wallet::DEFAULT_WALLET_FILENAME, n); + if !taken.iter().any(|w| w.wallet_filename == candidate) { + return Ok(candidate); + } + } + unreachable!("an unused wallet file name always exists") + } + + /// Point the wallet child at a wallet file. A read-modify-write of the + /// sealed record, so the generated RPC creds and every other setting are + /// kept. A running child is not restarted: the change applies on the next + /// `start_wallet_child`. + fn point_child_at(&self, filename: &str) -> Result<(), String> { + let mut cfg = self.wallet_child_config(); + if cfg.wallet_filename == filename { + return Ok(()); + } + cfg.wallet_filename = filename.to_string(); + self.set_wallet_child_config(&cfg) + } + + /// Add a freshly created wallet file to the catalogue: this node's identity + /// (several wallets may share one) and the onion it is reachable at right + /// now (a locator, and empty until the HS publishes). + fn record_wallet(&self, filename: &str) -> Result { + let new = NewWallet { + name: None, + identity_pubkey: self.identity_pk(), + onion_locator: self.onion(), + wallet_filename: filename.to_string(), + }; + self.store + .lock() + .map_err(|e| e.to_string())? + .create_wallet(&new) .map_err(|e| e.to_string()) } @@ -2964,4 +3068,140 @@ mod tests { } assert!(gone, "shutdown must not leave the wallet child behind"); } + + /// A loopback wallet RPC for the setup path: a per-socket digest challenge, + /// then the method's own result. `create_wallet` and + /// `restore_deterministic_wallet` both answer `{}`; only the seed backup + /// query has a body worth reading. + async fn mock_wallet_setup() -> Wallet { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind mock wallet"); + let port = listener.local_addr().expect("mock wallet addr").port(); + let reply: Arc String + Send + Sync> = Arc::new(|req: &str| { + if req.contains("query_key") { + r#"{"jsonrpc":"2.0","id":"0","result":{"key":"lumber tacit lemon ivory risk"}}"# + .to_string() + } else { + r#"{"jsonrpc":"2.0","id":"0","result":{}}"#.to_string() + } + }); + tokio::spawn(serve_mock_rpc(listener, reply)); + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") + } + + /// The reported bug: a created wallet was never remembered, because the + /// creation path never reached the store's catalogue. + #[tokio::test] + async fn creating_a_wallet_records_it_in_the_catalogue() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("bob"); + let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await); + + let created = node.wallet_create("hunter2").await.expect("create wallet"); + + assert!(created.record.id > 0, "the store assigns the row id"); + assert_eq!(created.record.wallet_filename, "onionwire-1"); + assert_eq!(created.record.identity_pubkey, node.identity_pk()); + assert_eq!(created.record.onion_locator, "test.onion"); + assert_eq!(created.seed, "lumber tacit lemon ivory risk"); + assert_eq!( + node.list_wallets().expect("list wallets"), + vec![created.record], + "the wallet just created is the catalogue" + ); + } + + /// The second half of the bug: a second create reused the one hardcoded file + /// name, so the RPC refused it — and nothing was remembered across a restart. + #[tokio::test] + async fn a_second_wallet_gets_its_own_file_and_both_survive_a_reopen() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("bob"); + let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await); + + let first = node.wallet_create("p1").await.expect("first wallet"); + let second = node.wallet_create("p1").await.expect("second wallet"); + + assert_ne!( + first.record.wallet_filename, second.record.wallet_filename, + "a second wallet must not reuse the first one's file" + ); + drop(node); + let reopened = Store::open_at_with_passphrase(&home, PASS).expect("reopen store"); + assert_eq!( + reopened.list_wallets().expect("list wallets").len(), + 2, + "both wallets are remembered across a restart" + ); + } + + /// Import is a creation path too: it takes the same hardcoded name today. + #[tokio::test] + async fn importing_a_wallet_records_it_in_the_catalogue() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node_with_wallet( + &dir.path().join("bob"), + Arc::new(NoDial), + mock_wallet_setup().await, + ); + + let imported = node + .wallet_restore("hunter2", "lumber tacit lemon ivory risk") + .await + .expect("restore wallet"); + + assert_eq!(imported.wallet_filename, "onionwire-1"); + assert_eq!( + node.list_wallets().expect("list wallets").len(), + 1, + "an imported wallet is remembered too" + ); + } + + /// A catalogue row the child never opens is still a broken wallet: the + /// child's stored config defaults to `onionwire`, which no created wallet + /// uses any more. + #[tokio::test] + async fn creating_a_wallet_points_the_child_at_its_own_file() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node_with_wallet( + &dir.path().join("bob"), + Arc::new(NoDial), + mock_wallet_setup().await, + ); + + let first = node.wallet_create("p1").await.expect("first wallet"); + assert_eq!( + node.wallet_child_config().wallet_filename, + first.record.wallet_filename, + "the child must open the wallet that was just created" + ); + + let second = node.wallet_create("p1").await.expect("second wallet"); + assert_eq!( + node.wallet_child_config().wallet_filename, + second.record.wallet_filename + ); + assert_eq!( + node.list_wallets().expect("list wallets")[0].wallet_filename, + first.record.wallet_filename, + "the first wallet keeps its own file" + ); + } + + /// The catalogue is a store fact, not a wallet-RPC fact: listing must work + /// with no wallet configured, and creating must still refuse without one. + #[tokio::test] + async fn a_wallet_off_install_lists_an_empty_catalogue() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + + assert!(node.list_wallets().expect("list wallets").is_empty()); + let err = node + .wallet_create("hunter2") + .await + .expect_err("no wallet RPC"); + assert!(err.contains("ONIONWIRE_WALLET_RPC"), "{err}"); + } } diff --git a/src/tui.rs b/src/tui.rs index a72d071..b14994c 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -2263,9 +2263,9 @@ impl App { return Ok(()); } match self.rt.block_on(self.node.wallet_create(pass.as_str())) { - Ok(seed) => { + Ok(created) => { self.screen = Screen::WalletSetup(WalletSetup::CreateSeed { - seed: Zeroizing::new(seed), + seed: Zeroizing::new(created.seed), typed: String::new(), }); } @@ -2338,7 +2338,7 @@ impl App { .block_on(self.node.wallet_restore(pass.as_str(), seed.as_str())); seed.zeroize(); match result { - Ok(()) => { + Ok(_) => { self.status_note = Some("wallet imported".into()); return self.open_wallet(); } From d96de1d7f0f01427f1a43cb0e0e5f0e8a327b82c Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 21 Sep 2026 10:41:53 -0400 Subject: [PATCH 10/78] tui: wallet selection screen (F6 -> w) with create as the last row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Screen::WalletSelect: a table of saved wallets — name, identity prefix, locator prefix, creation day — the selected row's full identity and locator under it, and a `+ create new wallet` row as the last item. j/k or arrows move, Enter takes the choice, Esc back. Empty, failed and in-flight reads each get their own copy; a wallet with a NULL label, no published locator or no usable timestamp reads `(unlabelled)` / `-` / `unknown` rather than blank. Presentation only. Rows are plain display data (WalletRow) built by the caller; the render path never reads the store, and the selection is by row index because two records may share an identity key. Loading a chosen record into the session is the wallet-store integration step, so the F6 `w` entry opens the screen on its unavailable state until that accessor lands, and the create row works today either way. Evidence: tests/tui_select.rs (16 tests) drives the real draw path through TestBackend at 80x24, 120x40 and 200x60, pins the dumped frame's footer to status_footer_phased(..., wallet_select_footer_hint()), asserts exactly one focus marker, a cell-width line budget from 20 to 200 columns, the window disclosure with the create row always visible, hostile labels (ESC/BEL/C1/ bidi/newline/tab) and the crate-local UTC date formatter. (cherry picked from commit 99a4ab640e91841aedf4dcb88bc326e91252daa5) --- docs/TUI.md | 23 +- src/tui.rs | 599 +++++++++++++++++++++++++++++++++++++++++++- tests/tui_select.rs | 475 +++++++++++++++++++++++++++++++++++ 3 files changed, 1095 insertions(+), 2 deletions(-) create mode 100644 tests/tui_select.rs diff --git a/docs/TUI.md b/docs/TUI.md index 9c52c70..7b64afd 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -23,6 +23,7 @@ ASCII chrome. | `Profile` | `/profile` | Edit name, bio, optional Monero address | | `ConfirmKeys` / `Passphrase` | `/backup`, `/restore` | Type `BACKUP`/`RESTORE`, then passphrase | | `Wallet` | `F6` | Receive QR, balance, transfers, child, chain source | +| `WalletSelect` | `F6` `w` | Saved wallets, pick one or create one | | `WalletSetup` | `F6` `c` / `i`, or `/wallet create` / `import` | Spend warning, seed, import | | `WalletsSettings` | `F9` or `/settings` | Discovery menu (does not replace F-keys) | | `PeerPayments` | F9 then `p` | Peer-scoped `/pay` / `/tip` history | @@ -109,12 +110,13 @@ Pane-specific (`pane_footer_hints`): Footer: ``` -c create i import r qr s/x child 1 pruned 2 full 3 testnet Esc back ? help +c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help ``` | Key | Effect | |---|---| | `r` or Enter | Toggle receive-address QR | +| `w` | Saved wallets (`WalletSelect`) | | `c` | Create wallet (`SPEND` then seed once, type `SEEN`) | | `i` | Import 25-word seed | | `s` | Start app-owned wallet child | @@ -133,6 +135,24 @@ feature name. Create/import require the wallet RPC started with `--wallet-dir`. Filename: `onionwire`. Seed is never collected on the composer. +## Saved wallets (`F6` then `w`) + +`WalletSelect`. One row per persisted wallet — name, identity prefix, locator +prefix, creation day — plus the selected row's full identity and locator under +the table. `j`/`k` or arrows select, Enter opens the selection, Esc back to +Main. Footer: `Esc back j k select Enter open ? help`. + +The last item is **not** a wallet: `+ create new wallet` starts the same create +flow as `F6` `c`, so an empty list still has a way forward. An unlabelled wallet +(`NULL` in the store) reads `(unlabelled)`; a wallet whose onion service is not +published yet reads `-`; an unknown creation time reads `unknown`. A read that +failed is named on the screen — that is a different state from `no saved wallets +yet`, and the two never share copy. + +Rows are plain display data (`WalletRow`), built by the caller from +`Store::list_wallets`; the render path never reads the store. Selection is by +row index, not by identity key (two records may share one). + ## Wallets & settings (`F9` / `/settings`) Discovery layer, not a replacement. Function keys stay live on this screen. @@ -180,4 +200,5 @@ Floor **80×24**. Target **120×40**. Frame dumps: ``` cargo test --locked --test tui_spec -- --nocapture dump_spec_frames cargo test --locked --test tui_spec -- --nocapture wallets_settings_menu_frame_dumps +cargo test --locked --test tui_select -- --nocapture wallet_select_frame_dumps ``` diff --git a/src/tui.rs b/src/tui.rs index b14994c..ca4d672 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1288,6 +1288,12 @@ enum Screen { PeerPayments { state: PeerPaymentsState, }, + /// F6 → `w`: pick a saved wallet, or create one. The rows are a snapshot + /// like the other two, and the `create new wallet` row is part of the list + /// rather than a separate key. + WalletSelect { + state: WalletSelectState, + }, Quit { prompt: QuitPrompt, }, @@ -1425,6 +1431,9 @@ impl App { let mut open_payments = false; let mut payments_back = false; let mut payments_move = 0i32; + let mut select_back = false; + let mut select_move = 0i32; + let mut select_enter = false; // The function-key shortcuts stay live on the WALLETS & SETTINGS screen // and the peer history too: the settings screen's whole point is naming @@ -1666,6 +1675,9 @@ impl App { Screen::Wallet { .. } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Char('r') | KeyCode::Enter => self.wallet_toggle_qr(), + // `w` is the wallet list: the F6 screen is about the wallet you + // are on, and this is how you get off it. + KeyCode::Char('w') => self.open_wallet_select(), KeyCode::Char('s') => self.wallet_child_start(), KeyCode::Char('x') => self.wallet_child_stop(), KeyCode::Char('p') => self.wallet_child_probe(), @@ -1698,6 +1710,13 @@ impl App { KeyCode::Down | KeyCode::Char('j') => payments_move = 1, _ => {} }, + Screen::WalletSelect { .. } => match key.code { + KeyCode::Esc => select_back = true, + KeyCode::Up | KeyCode::Char('k') => select_move = -1, + KeyCode::Down | KeyCode::Char('j') => select_move = 1, + KeyCode::Enter => select_enter = true, + _ => {} + }, Screen::Quit { prompt } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Enter => match prompt.on_char('\n') { @@ -1729,6 +1748,22 @@ impl App { if payments_back { self.screen = Screen::Main; } + if select_move != 0 + && let Screen::WalletSelect { state } = &mut self.screen + { + if select_move < 0 { + state.select_prev(); + } else { + state.select_next(); + } + } + if select_back { + // A full surface like the F9 menu: Esc leaves it for the main view. + self.screen = Screen::Main; + } + if select_enter { + self.choose_wallet()?; + } if open_payments { self.open_peer_payments()?; } @@ -2037,6 +2072,45 @@ impl App { Ok(()) } + /// Enter on the wallet selection screen: `create new wallet` starts the + /// existing creation flow, and a wallet row is a choice the app has to + /// resolve. + /// + /// Resolving a row into the session is the wallet-store integration step: + /// the record's identity and locator have to be read back and loaded, and + /// `Node` has no wallet-record accessor yet. Until that lands the choice is + /// reported instead of silently dropped — an Enter that does nothing is + /// worse than one that says what is missing. + fn choose_wallet(&mut self) -> Result<(), String> { + let Screen::WalletSelect { state } = &self.screen else { + return Ok(()); + }; + match state.choice() { + WalletChoice::Create => { + self.screen = Screen::WalletSetup(WalletSetup::CreateWarn { + typed: String::new(), + }); + } + WalletChoice::Open(_) => { + self.status_note = Some("wallet switching is not wired up yet".into()); + } + } + Ok(()) + } + + /// F6 `w`: the wallet selection screen. + /// + /// The rows come from the wallet store; reading them is the integration + /// card's step (`Store::list_wallets`), and the render path never touches + /// the store. Until that accessor exists the screen opens on its + /// unavailable state, which says so — the `create new wallet` row at the + /// bottom works either way. + fn open_wallet_select(&mut self) { + self.screen = Screen::WalletSelect { + state: WalletSelectState::error(SELECT_UNAVAILABLE.to_string()), + }; + } + /// `c` on the WALLETS & SETTINGS menu: copy the receive address through the /// terminal's own clipboard (OSC 52 — no crate, and it survives SSH). The /// address never touches a file. @@ -2578,6 +2652,17 @@ impl App { ); draw_peer_payments(f, state, &footer) } + Screen::WalletSelect { state } => { + let footer = status_footer_phased( + f.area().width, + &self.me_fp, + &self.me_onion, + Some(TorPhase::of(self.node.tor_state())), + self.status_note.as_deref(), + footer_hints(&self.screen), + ); + draw_wallet_select(f, state, &footer) + } } if self.help_open { draw_text_overlay(f, "? help", help_overlay_text()); @@ -3193,7 +3278,7 @@ match screen { }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", Screen::Wallet { .. } => { - "c create i import r qr s/x child 1 pruned 2 full 3 testnet Esc back ? help" + "c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help" } Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => { @@ -3203,6 +3288,7 @@ match screen { Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help", Screen::WalletsSettings { .. } => wallets_settings_footer_hint(), Screen::PeerPayments { .. } => peer_payments_footer_hint(), + Screen::WalletSelect { .. } => wallet_select_footer_hint(), Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help", } } @@ -4351,6 +4437,497 @@ pub fn draw_peer_payments(f: &mut Frame, state: &PeerPaymentsState, footer: &str ); } +/// One persisted wallet, display-ready. +/// +/// Plain data on purpose: the render path never reads the store, so the screen +/// takes rows the caller built. `name`, `identity_pubkey` and `onion_locator` +/// are untrusted display data (a label the user typed), sanitized at draw time. +/// +/// The store's `WalletRecord` maps onto this like so — +/// `name: r.name.unwrap_or_default()` (a blank label is the placeholder +/// `(unlabelled)` on screen), `identity_pubkey: hex(r.identity_pubkey)` (the +/// column is `[u8; 32]`, so it is encoded here as text), `onion_locator: +/// r.onion_locator` (empty until the HS is published — that renders as `-`), +/// `created_at: r.created_at`. `wallet_filename` is deliberately not carried: +/// it is not on the screen, and the render path has no business with a path. +/// +/// Selection is by **row index**, never by identity: two records may share an +/// identity key, so `WalletChoice::Open` names a position, not a wallet. +#[derive(Clone, Debug, Default)] +pub struct WalletRow { + /// User-given label. Empty means unlabelled (`NULL` in the store) and the + /// row says so rather than leaving the primary cell blank. + pub name: String, + /// The wallet's identity public key, hex. + pub identity_pubkey: String, + /// The wallet's v3 onion locator, without the `.onion` suffix. Empty until + /// the service is published. + pub onion_locator: String, + /// Creation time, unix seconds UTC. `0` (or negative) means unknown. + pub created_at: i64, +} + +/// What Enter does on the selection screen. +/// +/// The index is into the state's `rows` (display order), never into the store's +/// ids: the render path does not know them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WalletChoice { + /// Open the wallet at this index. + Open(usize), + /// The `create new wallet` row — the last item in the list. + Create, +} + +/// What the wallet selection screen draws. +/// +/// One item in the list is not a wallet: the `create new wallet` row, always +/// last, so Enter on it can start the creation flow instead of loading a +/// record. `selected` indexes rows **plus** that trailing row, which is why +/// `rows.len()` is a legal index and `choice()` reads it as `Create`. +/// +/// `error` is display-ready and only set when the read itself failed — an +/// account with no saved wallets is an empty list, not an error. +#[derive(Clone, Debug, Default)] +pub struct WalletSelectState { + pub rows: Vec, + pub selected: usize, + /// The read is in flight. The create row is still listed: it does not + /// depend on the store, so Enter stays live while the list loads. + pub reading: bool, + /// Why the list could not be read, display-ready. + pub error: Option, +} + +impl WalletSelectState { + /// The list a read returned. An empty list is the first-run state. + pub fn from_rows(rows: Vec) -> Self { + Self { + rows, + selected: 0, + reading: false, + error: None, + } + } + + /// The read is in flight. Nothing is listed yet, so the selection sits on + /// the create row. + pub fn reading() -> Self { + Self { + rows: Vec::new(), + selected: 0, + reading: true, + error: None, + } + } + + /// The read failed. This is not "no wallets": the screen says so. + pub fn error(why: String) -> Self { + Self { + rows: Vec::new(), + selected: 0, + reading: false, + error: Some(why), + } + } + + /// Move down one item. The bottom is the create row and is sticky. + pub fn select_next(&mut self) { + self.selected = (self.selected + 1).min(self.rows.len()); + } + + /// Move up one item. The top is the first wallet (or create) and is sticky. + pub fn select_prev(&mut self) { + self.selected = self.selected.saturating_sub(1); + } + + /// The row under the marker, `None` on the create row. + pub fn selected_row(&self) -> Option<&WalletRow> { + self.rows.get(self.selected) + } + + /// What Enter means right now. One past the last wallet — and the only + /// item of an empty or failed list — is `Create`. + pub fn choice(&self) -> WalletChoice { + match self.rows.get(self.selected) { + Some(_) => WalletChoice::Open(self.selected), + None => WalletChoice::Create, + } + } +} + +/// Marker column in cells: `> ` when focused, ` ` otherwise. +const WALLET_MARK_W: usize = 2; +/// Identity column in cells: an 8-character prefix plus the ellipsis — 11 +/// cells under `ONIONWIRE_ASCII`, where the ellipsis is three dots, so that is +/// the width every column is padded to whatever the chrome is doing. +const WALLET_ID_W: usize = 11; +/// Locator column in cells, measured the same way as the identity column. +const WALLET_LOC_W: usize = 11; +/// Creation-day column in cells: `2026-09-21` is 10, and `unknown` is 7. +const WALLET_SINCE_W: usize = 10; +/// Gap between two columns. +const WALLET_GAP: usize = 2; +/// Widest name column. The name is the flexible column and it is capped so the +/// trailing columns stay a table and not a 150-cell walk: every row pads to the +/// same column starts, which is what makes the rows scan as a grid. +const WALLET_NAME_W: usize = 28; +/// Cells the trailing columns need, marker included. +const WALLET_FIXED_W: usize = WALLET_MARK_W + + (WALLET_GAP + WALLET_ID_W) + + (WALLET_GAP + WALLET_LOC_W) + + (WALLET_GAP + WALLET_SINCE_W); + +/// `2026-09-21` for a unix second (UTC), or `unknown` when there is no usable +/// timestamp. Hand-rolled: this crate has no date dependency, and the screen +/// needs exactly one calendar date. +/// +/// Days-to-civil (Howard Hinnant's algorithm) — no leap-year table, no crate. +pub fn format_day_utc(secs: i64) -> String { + if secs <= 0 { + return "unknown".to_string(); + } + let z = secs.div_euclid(86_400) + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!("{year:04}-{month:02}-{day:02}") +} + +/// An identifying prefix of untrusted text: the first `keep` characters, closed +/// with the chrome's ellipsis, fitted into `cells`. +fn wallet_prefix(raw: &str, keep: usize, cells: usize) -> String { + let clean = menu_cell_text(raw); + let head: String = clean.chars().take(keep).collect(); + fit_cells(&format!("{head}{}", ellipsis()), cells) +} + +/// One laid-out grid line: marker, name, then whichever of the three trailing +/// columns fit. +/// +/// Trailing columns are **dropped** when the pane is too narrow, never wrapped, +/// so no row can overrun the pane — the same discipline as the payments grid, +/// and it holds below the 80-column floor too. +#[allow(clippy::too_many_arguments)] +fn wallet_grid_line( + w: usize, + marker: &str, + name: &str, + id: &str, + loc: &str, + since: &str, + marker_style: Style, + name_style: Style, + col_style: Style, +) -> Line<'static> { + let mut spans = vec![Span::styled(marker.to_string(), marker_style)]; + let inner = w.saturating_sub(cell_width(marker)); + let name_w = inner.saturating_sub(WALLET_FIXED_W).min(WALLET_NAME_W); + if name_w == 0 { + // Not even a name fits: the identity is the most identifying thing left. + spans.push(Span::styled( + fit_cells(&menu_cell_text(id), inner.max(1)), + col_style, + )); + return Line::from(spans); + } + spans.push(Span::styled( + pad_right(&fit_cells(name, name_w), name_w), + name_style, + )); + let mut used = name_w; + for (col_w, text) in [ + (WALLET_ID_W, id), + (WALLET_LOC_W, loc), + (WALLET_SINCE_W, since), + ] { + // An empty tail means the row has no more columns to give (the create + // row), and a column that does not fit takes the rest of them with it. + if text.is_empty() || inner < used + WALLET_GAP + col_w { + break; + } + spans.push(Span::raw(" ".repeat(WALLET_GAP))); + spans.push(Span::styled( + pad_right(&fit_cells(text, col_w), col_w), + col_style, + )); + used += WALLET_GAP + col_w; + } + Line::from(spans) +} + +/// The selected row's full identity and locator. The rows carry prefixes, which +/// is what makes the list scannable; the full values are what a user actually +/// verifies, so the strip under the table spells them out. +fn wallet_detail_lines(w: usize, row: &WalletRow) -> Vec> { + let mut out = vec![Line::default()]; + for (label, value) in [ + ("id", menu_cell_text(&row.identity_pubkey)), + ("onion", menu_cell_text(&row.onion_locator)), + ] { + let text = if value.trim().is_empty() { + "(none)".to_string() + } else { + value + }; + out.push(Line::from(vec![ + Span::styled(format!(" {label:<5} "), style_dim()), + Span::styled(fit_cells(&text, w.saturating_sub(9).max(1)), style_text()), + ])); + } + out +} + +/// The wallet selection body as styled lines for a `width` × `height` **inner** +/// pane. +/// +/// Fixed shape at the bottom: a blank, then the `create new wallet` row — the +/// one item that is not a wallet, always last, so the eye always knows where the +/// way out of an empty list is. The table above it windows and says how many +/// rows are out of view rather than dropping them silently. +pub fn wallet_select_lines(width: u16, height: u16, s: &WalletSelectState) -> Vec> { + let w = width as usize; + let h = height as usize; + let mut out: Vec> = Vec::new(); + + // The table is drawn only when there is a table to draw; empty, failed and + // in-flight reads say what they are instead of showing bare column heads. + let table = !s.rows.is_empty(); + if table { + out.push(wallet_grid_line( + w, + " ", + "name", + "identity", + "locator", + "since", + Style::default(), + style_dim(), + style_dim(), + )); + } else { + let (head, head_style, sub) = if let Some(err) = &s.error { + ( + "could not read saved wallets", + style_alert(), + menu_cell_text(err), + ) + } else if s.reading { + ( + "reading saved wallets", + style_dim(), + "one moment".to_string(), + ) + } else { + ( + "no saved wallets yet", + style_dim(), + "create one to get an identity and an onion address".to_string(), + ) + }; + out.push(Line::from(Span::styled( + fit_cells(&format!(" {head}"), w.max(1)), + head_style, + ))); + out.push(Line::from(Span::styled( + fit_cells(&format!(" {sub}"), w.max(1)), + style_dim(), + ))); + } + + // The full-value strip only where it cannot wrap, and its three cells are + // reserved whether or not the selection is a wallet, so the marker moving + // down to the create row never shifts the rows above it. + let strip = w >= 75 && h >= 14; + let strip_h = if strip { 3 } else { 0 }; + // One blank + the create row at the bottom. + let tail_h = 2; + let budget = h.saturating_sub(out.len() + strip_h + tail_h); + + if table { + let total = s.rows.len(); + let selected = s.selected.min(total - 1); + let windowed = total > budget && budget >= 5; + let visible = if windowed { + budget - 2 + } else { + budget.max(1).min(total) + }; + let start = if total <= visible { + 0 + } else { + selected.saturating_sub(visible - 1).min(total - visible) + }; + let end = (start + visible).min(total); + if windowed && start > 0 { + out.push(Line::from(Span::styled( + fit_cells(&format!(" {} {start} above", ellipsis()), w.max(1)), + style_dim(), + ))); + } + for (i, row) in s.rows.iter().enumerate().take(end).skip(start) { + // No row carries the marker when the selection has walked past the + // last wallet onto the create row. + let selected = s.selected < total && i == s.selected; + // A NULL label reads as a placeholder, and a wallet whose onion + // service is not published yet has no locator at all — both are + // states the row names, not blanks. + let name = { + let clean = menu_cell_text(&row.name); + if clean.trim().is_empty() { + "(unlabelled)".to_string() + } else { + clean + } + }; + let id = { + let clean = menu_cell_text(&row.identity_pubkey); + if clean.trim().is_empty() { + "-".to_string() + } else { + wallet_prefix(&clean, 8, WALLET_ID_W) + } + }; + let loc = { + let clean = menu_cell_text(&row.onion_locator); + if clean.trim().is_empty() { + "-".to_string() + } else { + wallet_prefix(&clean, 8, WALLET_LOC_W) + } + }; + out.push(wallet_grid_line( + w, + if selected { "> " } else { " " }, + &name, + &id, + &loc, + &format_day_utc(row.created_at), + if selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + Style::default() + }, + if selected { + style_text().add_modifier(Modifier::BOLD) + } else { + style_text() + }, + style_dim(), + )); + } + if windowed && end < total { + out.push(Line::from(Span::styled( + fit_cells(&format!(" {} {} below", ellipsis(), total - end), w.max(1)), + style_dim(), + ))); + } + } + + if strip { + let detail = if !table { + Vec::new() + } else { + s.selected_row() + .map(|row| wallet_detail_lines(w, row)) + .unwrap_or_default() + }; + // Reserved either way: the block is the same height whichever item the + // marker is on. + for i in 0..strip_h { + out.push(detail.get(i).cloned().unwrap_or_default()); + } + } + + // The create row closes the list, one blank line under the table, and the + // panel below it stays empty — the same top-packed shape as the F9 menu, so + // the eye finds the table at the top of every full-screen panel. + out.push(Line::default()); + let create_selected = s.rows.get(s.selected).is_none(); + out.push(wallet_grid_line( + w, + if create_selected { "> " } else { " " }, + "+ create new wallet", + "", + "", + "", + if create_selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + Style::default() + }, + if create_selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + style_text() + }, + style_dim(), + )); + out +} + +/// The body as plain text, for width/needle assertions. +pub fn wallet_select_text(width: u16, height: u16, s: &WalletSelectState) -> String { + wallet_select_lines(width, height, s) + .iter() + .map(|line| { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::() + }) + .collect::>() + .join("\n") +} + +/// Block title: the count is the reason the screen exists, so it is stated. +pub fn wallet_select_title(s: &WalletSelectState) -> String { + if s.rows.is_empty() { + "(o) wallets".to_string() + } else { + format!("(o) wallets {} {} saved", "\u{b7}", s.rows.len()) + } +} + +/// Wallet selection: a full screen like the F9 menu, with the same single +/// status line. `footer` is an already-built `status_footer` row. +pub fn draw_wallet_select(f: &mut Frame, s: &WalletSelectState, footer: &str) { + let area = f.area(); + let rows = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area); + f.render_widget( + Paragraph::new(wallet_select_lines( + rows[0].width.saturating_sub(2), + rows[0].height.saturating_sub(2), + s, + )) + .block(themed_block(&wallet_select_title(s))), + rows[0], + ); + f.render_widget( + Paragraph::new(fit_cells(footer, area.width as usize)).style(style_dim()), + rows[1], + ); +} + +/// The hint line the wallet selection screen prints, single-sourced for the +/// same reason as [`peer_payments_footer_hint`]: a frame-dump fixture must not +/// hand-copy it, or the dump shows a footer the app never renders. +pub fn wallet_select_footer_hint() -> &'static str { + WALLET_SELECT_FOOTER_HINT +} + +const WALLET_SELECT_FOOTER_HINT: &str = "Esc back j k select Enter open ? help"; + +/// The sub-line the screen prints when the wallet store has not been wired into +/// the app yet (see [`WalletRow`]): the list is genuinely unreadable, which is +/// not the same state as "no saved wallets". +pub const SELECT_UNAVAILABLE: &str = "the wallet store is not wired up yet"; + /// OSC 52 clipboard write for `text`: the terminal copies it, so no crate and /// no clipboard daemon are involved and it still works over SSH. A terminal /// that does not implement OSC 52 ignores the sequence. @@ -4651,6 +5228,26 @@ mod function_key_tests { } } + /// The wallet list names `Esc`, `j k` and `Enter`, no function key — so it + /// must not quietly answer one. Copy and behaviour have to agree in both + /// directions, or a key that works on every other screen becomes a surprise + /// here. + #[test] + fn the_wallet_select_screen_answers_no_function_key_it_does_not_name() { + let screen = Screen::WalletSelect { + state: WalletSelectState::default(), + }; + let hint = wallet_select_footer_hint(); + for number in [2u8, 3, 4, 5, 6, 8, 9] { + let named = hint.contains(&format!("F{number}")); + assert_eq!( + function_key_for(&screen, KeyCode::F(number)).is_some(), + named, + "F{number} and the hint disagree: {hint:?}" + ); + } + } + /// A screen that names no function key keeps the key to itself: the /// composer's `F`-less screens must not steal F-keys they never advertise. #[test] diff --git a/tests/tui_select.rs b/tests/tui_select.rs new file mode 100644 index 0000000..7447ec1 --- /dev/null +++ b/tests/tui_select.rs @@ -0,0 +1,475 @@ +//! Wallet selection screen (`F6` → `w`). +//! +//! The screen lists the persisted wallets and, last, the `create new wallet` +//! row. Assertions measure in terminal **cells** (`cell_width`, which goes +//! through `Span::width`) and accept either ellipsis form because +//! `ascii_chrome()` follows `NO_COLOR` / `ONIONWIRE_ASCII` and the TUI test +//! binaries run in parallel. + +use onionwire::tui::{ + TorPhase, WalletChoice, WalletRow, WalletSelectState, cell_width, draw_wallet_select, + format_day_utc, status_footer_phased, wallet_select_footer_hint, wallet_select_lines, + wallet_select_text, +}; +use ratatui::Terminal; +use ratatui::backend::TestBackend; + +const FP: &str = "abcdef0123456789deadbeefcafebabe"; +const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; +const ID_A: &str = "ab12cd34ef5678901234567890abcdef1234567890abcdef1234567890abcd"; +const ID_B: &str = "ff00aa11bb22cc33dd44ee55ff6677889900aabbccddeeff0011223344556677"; +const ONION_A: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx"; +const ONION_B: &str = "zyxwvutsrqponmlkjihgfedcba765432zyxwvutsrqponmlkjihgfedcba"; + +fn row(name: &str, id: &str, onion: &str, created_at: i64) -> WalletRow { + WalletRow { + name: name.into(), + identity_pubkey: id.into(), + onion_locator: onion.into(), + created_at, + } +} + +/// Two saved wallets plus the create row: the shape the screen opens on. +fn two_wallets() -> WalletSelectState { + WalletSelectState::from_rows(vec![ + row("lance", ID_A, ONION_A, 1_789_963_705), + row("cold", ID_B, ONION_B, 1_756_320_000), + ]) +} + +/// The row count is the wallet count **plus the create row**, which is always +/// the last item: Enter on it starts the creation flow, not a wallet load. +#[test] +fn selection_walks_every_row_and_ends_on_create() { + let mut st = two_wallets(); + assert_eq!( + st.choice(), + WalletChoice::Open(0), + "opens on the first wallet" + ); + + st.select_next(); + assert_eq!(st.choice(), WalletChoice::Open(1)); + st.select_next(); + assert_eq!( + st.choice(), + WalletChoice::Create, + "the create row is the last item in the list" + ); + + // Past the end is a no-op, not a panic: the bottom of the list is Create. + st.select_next(); + assert_eq!(st.choice(), WalletChoice::Create); + + st.select_prev(); + assert_eq!(st.choice(), WalletChoice::Open(1)); + st.select_prev(); + st.select_prev(); + assert_eq!( + st.choice(), + WalletChoice::Open(0), + "top of the list is sticky" + ); +} + +/// With no saved wallets the screen still has exactly one item — Create — so +/// Enter can never be a dead key on a first run. +#[test] +fn empty_state_still_offers_create() { + let st = WalletSelectState::default(); + assert_eq!(st.choice(), WalletChoice::Create); + assert!(st.selected_row().is_none()); +} + +/// A read that failed is not an empty list: the state says so. +#[test] +fn error_state_is_not_an_empty_list() { + let st = WalletSelectState::error("store lock poisoned".into()); + assert!(st.error.is_some()); + assert_eq!(st.choice(), WalletChoice::Create); +} + +/// The card's four fields, plus the create row, on the body at the 80-column +/// floor: name, identity prefix, locator prefix, creation date. +#[test] +fn wallet_select_lists_every_required_field() { + let body = wallet_select_text(78, 21, &two_wallets()); + for needle in [ + "name", // column header + "identity", // column header + "locator", // column header + "since", // column header + "lance", + "cold", // names + "ab12cd34", // identity prefix + "ff00aa11", // identity prefix of the second wallet + "abcdefgh", // locator prefix + "zyxwvuts", // locator prefix of the second wallet + "2026-09-21", // creation date + "2025-08-27", // creation date of the second wallet + "create new wallet", // the always-last row + ] { + assert!(body.contains(needle), "missing {needle:?}:\n{body}"); + } + // A prefix is a prefix: the row prints an identifying start, not the whole + // key (the full value belongs to the detail strip under the table). + let lance_row = body + .lines() + .find(|l| l.contains("lance")) + .expect("lance row"); + assert!( + !lance_row.contains(ID_A), + "a row printed the whole identity: {lance_row:?}" + ); + // Truncation is disclosed with the chrome's ellipsis (… or ...). + assert!( + body.contains('…') || body.contains("..."), + "no truncation marker on a prefix:\n{body}" + ); +} + +/// The create row is last, and the marker is on the selection — one marker +/// only, whichever row is focused. +#[test] +fn wallet_select_marks_exactly_one_row_and_puts_create_last() { + let mut st = two_wallets(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!(marked[0].contains("lance"), "{:?}", marked[0]); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row is not last:\n{body}" + ); + + st.select_next(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!(marked[0].contains("cold"), "{:?}", marked[0]); + + // The bottom of the list is the create row and it takes the marker too. + st.select_next(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!( + marked[0].contains("create new wallet"), + "the marker never reached the create row: {:?}", + marked[0] + ); +} + +/// A wallet with no label still identifies itself: the primary cell is a +/// placeholder, the row keeps its identity, and an unknown creation time is a +/// word, not a blank or a zero. +#[test] +fn wallet_select_names_an_unlabelled_wallet_and_an_unknown_date() { + let st = WalletSelectState::from_rows(vec![row("", ID_B, ONION_B, 0)]); + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("(unlabelled)"), + "a NULL label left the primary cell empty:\n{body}" + ); + assert!( + body.contains("ff00aa11"), + "an unlabelled wallet lost its identity:\n{body}" + ); + assert!( + body.contains("unknown"), + "an unknown creation date is blank:\n{body}" + ); + assert!( + !body.contains("1970-01-01"), + "epoch rendered as a date:\n{body}" + ); +} + +/// A wallet whose onion service has not been published yet has no locator. That +/// is a state, not an error: the cell says so and the row stays readable. +#[test] +fn wallet_select_renders_an_unpublished_locator_as_a_placeholder() { + let st = WalletSelectState::from_rows(vec![row("fresh", ID_A, "", 1_789_963_705)]); + let body = wallet_select_text(78, 21, &st); + let row_line = body + .lines() + .find(|l| l.contains("fresh")) + .expect("wallet row"); + assert!( + row_line.contains("2026-09-21"), + "an empty locator pushed the row out of shape: {row_line:?}" + ); + assert!( + row_line.contains(" - "), + "an unpublished locator has no placeholder: {row_line:?}" + ); + assert!( + !body.to_lowercase().contains("error") && !body.to_lowercase().contains("failed"), + "an unpublished locator read as a failure:\n{body}" + ); +} + +/// Empty, failed and in-flight reads are three different states, and none of +/// them is a blank pane. All three still offer the create row. +#[test] +fn wallet_select_words_the_empty_error_and_reading_states() { + let empty = wallet_select_text(78, 21, &WalletSelectState::default()); + assert!(empty.contains("no saved wallets"), "\n{empty}"); + assert!(empty.contains("create new wallet"), "\n{empty}"); + + let failed = wallet_select_text( + 78, + 21, + &WalletSelectState::error("store lock poisoned".into()), + ); + assert!(failed.contains("could not read"), "\n{failed}"); + assert!(failed.contains("store lock poisoned"), "\n{failed}"); + assert!(failed.contains("create new wallet"), "\n{failed}"); + // A failed read must not read as "you have no wallets". + assert!(!failed.contains("no saved wallets"), "\n{failed}"); + + let reading = wallet_select_text(78, 21, &WalletSelectState::reading()); + assert!(reading.contains("reading"), "\n{reading}"); + assert!(reading.contains("create new wallet"), "\n{reading}"); +} + +/// The whole point of a prefix is that the row cannot outgrow the pane: a row +/// with a name wide enough to swallow the table still truncates in cells. +#[test] +fn wallet_select_truncates_a_wide_name_in_cells() { + let st = WalletSelectState::from_rows(vec![row( + "私のウォレットはとても長い名前を持っています", + ID_A, + ONION_A, + 1_789_963_705, + )]); + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("私の"), + "a CJK name was dropped entirely:\n{body}" + ); + assert!( + body.contains('…') || body.contains("..."), + "a long name was clipped without an ellipsis:\n{body}" + ); + for line in body.lines() { + assert!( + cell_width(line) <= 78, + "line wider than the pane: {} cells: {line:?}", + cell_width(line) + ); + } +} + +/// Every body line fits the pane it was laid out for, from well under the +/// 80-column floor to 200 — trailing columns drop, nothing wraps. +#[test] +fn wallet_select_columns_drop_before_they_wrap() { + for w in 20u16..=200 { + for state in [ + two_wallets(), + WalletSelectState::default(), + WalletSelectState::error("store lock poisoned".into()), + WalletSelectState::reading(), + ] { + for line in wallet_select_lines(w, 21, &state) { + let width: usize = line + .spans + .iter() + .map(|s| cell_width(s.content.as_ref())) + .sum(); + assert!(width <= w as usize, "width {w}: {width} cells: {line:?}"); + } + } + } +} + +/// A long list windows and says how many rows are out of view; the create row +/// is never the row that falls off. +#[test] +fn wallet_select_windows_a_long_list_and_keeps_create_visible() { + let rows: Vec = (0..40) + .map(|i| row(&format!("w{i:02}"), ID_A, ONION_A, 1_789_963_705)) + .collect(); + let mut st = WalletSelectState::from_rows(rows); + let body = wallet_select_text(78, 21, &st); + assert!(body.contains("below"), "window not disclosed:\n{body}"); + assert!( + body.contains("w00"), + "the first row is not on screen:\n{body}" + ); + assert!(!body.contains("w39"), "\n{body}"); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row was pushed off the pane:\n{body}" + ); + + for _ in 0..39 { + st.select_next(); + } + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("w39"), + "the last row never came into view:\n{body}" + ); + assert!(body.contains("above"), "window not disclosed:\n{body}"); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row was pushed off the pane:\n{body}" + ); + assert_eq!(st.choice(), WalletChoice::Open(39)); +} + +/// The screen is not a sink for peer bytes: a label is untrusted display data. +#[test] +fn wallet_select_hostile_label_cannot_reach_the_terminal() { + let hostile = "safe\u{1b}[31mred\u{7}\u{202e}\u{2066}\u{9b}\nrow\ttab"; + let st = WalletSelectState::from_rows(vec![row(hostile, ID_A, ONION_A, 1_789_963_705)]); + for (w, h) in [(80u16, 24u16), (120, 40)] { + let screen = render(w, h, &st); + for (what, ch) in [ + ("ESC", '\u{1b}'), + ("BEL", '\u{7}'), + ("C1", '\u{9b}'), + ("bidi", '\u{202e}'), + ("bidi isolate", '\u{2066}'), + ] { + assert!(!screen.contains(ch), "{w}x{h}: {what} reached the frame"); + } + assert!(screen.contains("safe"), "{w}x{h}:\n{screen}"); + } + let body = wallet_select_text(78, 21, &st); + assert!(body.contains("safe[31mred"), "\n{body}"); + assert_eq!( + body.lines().filter(|l| l.contains("safe[31mred")).count(), + 1, + "the hostile label split or duplicated a row:\n{body}" + ); +} + +/// Days from unix seconds, UTC, without a date crate — including a leap day and +/// the epoch, which reads as "unknown" rather than 1970-01-01. +#[test] +fn format_day_utc_covers_the_calendar_edges() { + for (secs, want) in [ + (0i64, "unknown"), + (-1, "unknown"), + (1, "1970-01-01"), + (86_400, "1970-01-02"), + (951_782_400, "2000-02-29"), + (1_700_000_000, "2023-11-14"), + (1_789_963_705, "2026-09-21"), + ] { + assert_eq!(format_day_utc(secs), want, "{secs}"); + } +} + +/// The app renders this screen's one status line with `status_footer_phased` +/// and `footer_hints`; the fixture does the same, so a dumped frame can never +/// show a footer the app does not draw. +fn render(w: u16, h: u16, st: &WalletSelectState) -> String { + let backend = TestBackend::new(w, h); + let mut terminal = Terminal::new(backend).expect("terminal"); + let footer = status_footer_phased( + w, + FP, + ONION, + Some(TorPhase::Ready), + None, + wallet_select_footer_hint(), + ); + terminal + .draw(|f| draw_wallet_select(f, st, &footer)) + .expect("draw"); + let buf = terminal.backend().buffer(); + let mut screen = String::new(); + for y in 0..h { + for x in 0..w { + screen.push_str(buf[(x, y)].symbol()); + } + screen.push('\n'); + } + screen +} + +#[test] +fn wallet_select_frame_shows_the_shipped_footer() { + let shipped = status_footer_phased( + 80, + FP, + ONION, + Some(TorPhase::Ready), + None, + wallet_select_footer_hint(), + ); + let frame = render(80, 24, &two_wallets()); + let last = frame.lines().nth(23).unwrap_or_default(); + assert_eq!( + last.trim_end(), + shipped.trim_end(), + "the dumped frame's footer is not the one the app renders" + ); +} + +#[test] +fn wallet_select_frames_fit_at_the_three_sizes() { + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + let screen = render(w, h, &two_wallets()); + for needle in [ + "(o) wallets", + "2 saved", + "lance", + "2026-09-21", + "create new wallet", + "? help", + ] { + assert!( + screen.contains(needle), + "{w}x{h} missing {needle:?}:\n{screen}" + ); + } + for line in screen.lines() { + assert!( + cell_width(line) <= w as usize, + "line wider than {w} at {w}x{h}: {line:?}" + ); + } + let lines = wallet_select_lines(w - 2, h - 3, &two_wallets()); + assert!( + lines.len() <= (h - 3) as usize, + "body needs {} rows, {w}x{h} shows {}", + lines.len(), + h - 3 + ); + } + // 200x60 fits the whole identity and locator in the detail strip. + let wide = render(200, 60, &two_wallets()); + assert!( + wide.contains(ID_A), + "200x60 truncated the identity:\n{wide}" + ); + assert!( + wide.contains(ONION_A), + "200x60 truncated the locator:\n{wide}" + ); +} + +#[test] +fn wallet_select_frame_dumps() { + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + println!("===== WALLETS {w}x{h} ====="); + print!("{}", render(w, h, &two_wallets())); + println!("===== WALLETS (empty) {w}x{h} ====="); + print!("{}", render(w, h, &WalletSelectState::default())); + println!("===== WALLETS (failed read) {w}x{h} ====="); + print!( + "{}", + render( + w, + h, + &WalletSelectState::error("store lock poisoned".into()) + ) + ); + } +} From 89867248485a3f25a5a560ba456afc394c5014ac Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 21 Sep 2026 11:43:07 -0400 Subject: [PATCH 11/78] tui: read the wallet list from the store and load the chosen wallet MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The selection screen shipped as presentation only: `F6 w` opened its unavailable state, the rows were never read, and Enter on a wallet said switching was not wired up. The catalogue, the create path and the screen all existed; nothing joined them. - `App::open_wallet_select` builds its rows from `Node::list_wallets` at the moment the screen opens (never cached from startup), and a failed read is the screen's own error state rather than "no saved wallets". - `App::choose_wallet` resolves `WalletChoice::Open(index)` against the catalogue as it is now — the index is a position, and two saved wallets may share an identity key — then loads it. `+ create new wallet` still starts the existing create flow. - `Node::open_wallet(filename)` is the load: it refuses a file the catalogue does not hold, re-points the sealed wallet-child record with a read-modify-write (the generated RPC creds survive), and restarts a running child onto the new file. An idle child takes the change on its next start. - `App::new` starts on the selection screen when the catalogue is non-empty and on the create flow when it is empty, so a restart lands on the wallets it remembers and a first run has no dead empty list. - The stored identity/locator stay catalogue columns: a locator rotates (F4) and identity is the roster key the node already holds, so the live header keeps reading them from the node. - `SELECT_UNAVAILABLE` is gone with the state it described; docs/TUI.md now describes the wired behaviour. Tests (both new): `Node::open_wallet` over an offline node — the chosen file, the creds kept across the read-modify-write, the choice surviving a reopen, and a non-catalogue file refused; and the app path in src/tui.rs over a real store-backed node — start screen both ways, catalogue mapping, row index over a shared identity, the create row, and a wallet recorded after startup appearing the next time the list opens. --- docs/TUI.md | 17 +++- src/node.rs | 166 +++++++++++++++++++++++++++++- src/tui.rs | 285 +++++++++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 439 insertions(+), 29 deletions(-) diff --git a/docs/TUI.md b/docs/TUI.md index 7b64afd..a763944 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -150,9 +150,24 @@ failed is named on the screen — that is a different state from `no saved walle yet`, and the two never share copy. Rows are plain display data (`WalletRow`), built by the caller from -`Store::list_wallets`; the render path never reads the store. Selection is by +`Node::list_wallets`; the render path never reads the store. Selection is by row index, not by identity key (two records may share one). +The list is read when the screen opens — from the start screen and from +`F6` `w` — so a wallet created or imported in this session is offered the next +time the screen opens, with no restart. Enter on a wallet row re-points the +app-owned wallet child at that row's `wallet_filename` (`Node::open_wallet`, +a read-modify-write of the sealed record, so the generated RPC creds survive); +a running child is restarted onto the new file, and an idle one picks the +change up on its next start. + +**Start screen.** An install with at least one saved wallet opens on +`WalletSelect`; a fresh install (empty catalogue) opens on the create flow +(`WalletSetup::CreateWarn`), so the first run has no dead empty list. The +stored identity and locator are catalogue columns, not session state: a locator +rotates (`F4`) and identity is the roster key the node already holds, so the +live header keeps reading them from the node. + ## Wallets & settings (`F9` / `/settings`) Discovery layer, not a replacement. Function keys stay live on this screen. diff --git a/src/node.rs b/src/node.rs index 120696b..fef5b8f 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1251,6 +1251,37 @@ impl Node { .map_err(|e| e.to_string()) } + /// Switch the wallet child to a catalogue wallet's file. + /// + /// The catalogue is the only directory this app has, so a file it does not + /// hold is refused instead of pointing a spend-capable child at a path. A + /// running child is restarted onto the new file; an idle one is only + /// re-pointed, and the change applies on the next `start_wallet_child`. The + /// write is a read-modify-write, so the generated RPC creds survive. + pub fn open_wallet(&self, filename: &str) -> Result<(), String> { + if !self + .list_wallets()? + .iter() + .any(|w| w.wallet_filename == filename) + { + return Err(format!("no saved wallet in {filename}")); + } + let running = self + .wallet_child + .lock() + .map_err(|e| e.to_string())? + .as_ref() + .is_some_and(|child| child.wallet_rpc_running()); + if running { + self.stop_wallet_child()?; + } + self.point_child_at(filename)?; + if running { + self.start_wallet_child()?; + } + Ok(()) + } + /// The file name a wallet created now should live in. `wallet_filename` is /// UNIQUE and the catalogue is the only directory the app has, so this is /// `-` for the first `n` the catalogue does not already hold. @@ -1990,7 +2021,42 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool { } #[cfg(test)] -mod tests { +/// A catalogue row written straight into the store, for tests that need a saved +/// wallet without a wallet RPC. +pub(crate) fn test_record_wallet(store: &Store, file: &str, label: &str) { + let identity_pubkey: [u8; 32] = store + .self_identity() + .expect("self identity") + .identity_pk + .try_into() + .expect("32-byte identity"); + store + .create_wallet(&NewWallet { + name: (!label.trim().is_empty()).then(|| label.to_string()), + identity_pubkey, + onion_locator: format!("{file}.onion"), + wallet_filename: file.to_string(), + }) + .expect("create wallet"); +} + +/// A real `Node` with no Tor and a seeded wallet catalogue, for the TUI's own +/// tests: `App` reads the catalogue, and the only public `Node` constructor +/// bootstraps Tor. `wallets` is `(file name, label)` — a blank label is stored +/// as `NULL`, like a wallet created without one. +#[cfg(test)] +pub(crate) fn test_node_with_wallets(home: &Path, wallets: &[(&str, &str)]) -> Arc { + { + let store = Store::open_at_with_passphrase(home, tests::PASS).expect("open store"); + for (file, label) in wallets { + test_record_wallet(&store, file, label); + } + } + Arc::new(tests::offline_node(home, Arc::new(tests::NoDial))) +} + +#[cfg(test)] +pub(crate) mod tests { use super::*; use crate::wallet_child::DEFAULT_MONEROD_RPC_PORT; use std::pin::Pin; @@ -2002,11 +2068,11 @@ mod tests { use tokio::io::AsyncRead as TokioRead; use tokio::io::AsyncWrite as TokioWrite; - const PASS: &str = "node-ratchet-test-pass"; + pub(crate) const PASS: &str = "node-ratchet-test-pass"; /// Never dials: every send queues, which is what leaves the encoded frame /// visible on the outbox row. - struct NoDial; + pub(crate) struct NoDial; impl crate::outbox::Deliverer for NoDial { fn deliver<'a>( @@ -2063,7 +2129,7 @@ mod tests { /// are the only public constructors and both bootstrap Tor and publish an /// onion service, so this is the only way to drive the shipped send and /// receive path offline. - fn offline_node(home: &Path, deliverer: Arc) -> Node { + pub(crate) fn offline_node(home: &Path, deliverer: Arc) -> Node { offline_node_with_wallet(home, deliverer, Wallet::disabled()) } @@ -3204,4 +3270,96 @@ mod tests { .expect_err("no wallet RPC"); assert!(err.contains("ONIONWIRE_WALLET_RPC"), "{err}"); } + + /// Switching wallets is a catalogue read plus a child re-point: the chosen + /// row's file name is what the child opens, and the generated RPC creds in + /// the same sealed record survive the read-modify-write. + #[tokio::test] + async fn open_wallet_points_the_child_at_the_chosen_file_and_keeps_the_creds() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("bob"); + let node = offline_node(&home, Arc::new(NoDial)); + { + let store = node.store.lock().unwrap(); + store + .save_wallet_child( + r#"{"user":"owuser","pass":"ow-secret-pass-xyz","wallet_filename":"onionwire"}"#, + ) + .unwrap(); + for file in ["onionwire", "onionwire-1"] { + store + .create_wallet(&NewWallet { + name: None, + identity_pubkey: [7u8; 32], + onion_locator: "abcd.onion".into(), + wallet_filename: file.to_string(), + }) + .unwrap(); + } + } + + node.open_wallet("onionwire-1") + .expect("open a saved wallet"); + assert_eq!( + node.wallet_child_config().wallet_filename, + "onionwire-1", + "the child must open the wallet that was chosen" + ); + let sealed = node + .store + .lock() + .unwrap() + .load_wallet_child() + .unwrap() + .expect("sealed record"); + assert!( + sealed.contains("ow-secret-pass-xyz"), + "the re-point dropped the generated creds: {sealed}" + ); + assert!( + sealed.contains("\"user\":\"owuser\""), + "the re-point dropped the generated creds: {sealed}" + ); + + // A restart re-reads the record, so the choice is remembered. + drop(node); + let restarted = offline_node(&home, Arc::new(NoDial)); + assert_eq!( + restarted.wallet_child_config().wallet_filename, + "onionwire-1", + "the chosen wallet must survive a restart" + ); + } + + /// The catalogue is the only directory the app has, so a file it does not + /// hold is refused instead of pointing a spend-capable child at a path. + #[tokio::test] + async fn open_wallet_refuses_a_file_the_catalogue_does_not_hold() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + { + let store = node.store.lock().unwrap(); + store + .save_wallet_child(r#"{"user":"owuser","pass":"p","wallet_filename":"onionwire"}"#) + .unwrap(); + store + .create_wallet(&NewWallet { + name: None, + identity_pubkey: [7u8; 32], + onion_locator: String::new(), + wallet_filename: "onionwire".to_string(), + }) + .unwrap(); + } + + let err = node + .open_wallet("onionwire-9") + .expect_err("not a saved wallet"); + assert!(err.contains("no saved wallet"), "{err}"); + assert_eq!( + node.wallet_child_config().wallet_filename, + "onionwire", + "a refused switch must leave the child where it was" + ); + } } diff --git a/src/tui.rs b/src/tui.rs index ca4d672..8251985 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -17,7 +17,9 @@ use crate::node::Node; use crate::outbox::DEFAULT_MAX_ATTEMPTS; use crate::qr::{self, QrPayload}; use crate::sanitize; -use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment}; +use crate::store::{ + Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment, WalletRecord, +}; use crate::wallet::{self, ChainNetwork, ChainSource}; const C_ACCENT: Color = Color::Rgb(232, 165, 75); @@ -1348,12 +1350,27 @@ fn function_key_for(screen: &Screen, code: KeyCode) -> Option { impl App { fn new(node: Arc, rt: tokio::runtime::Handle) -> Result { let friends = node.list_friends()?; + // First run is the create flow, not an empty list to pick from; an + // install that already has wallets starts on the list, so a restart + // lands on the wallets it remembers. A catalogue that cannot be read is + // the screen's own error state (the create row still works there). + let screen = match node.list_wallets() { + Ok(rows) if rows.is_empty() => Screen::WalletSetup(WalletSetup::CreateWarn { + typed: String::new(), + }), + Ok(rows) => Screen::WalletSelect { + state: WalletSelectState::from_rows(wallet_rows(rows)), + }, + Err(e) => Screen::WalletSelect { + state: WalletSelectState::error(e), + }, + }; Ok(Self { me_fp: to_hex(&node.identity_pk()), me_onion: node.onion(), node, rt, - screen: Screen::Main, + screen, friends, selected: 0, alert: None, @@ -2073,14 +2090,14 @@ impl App { } /// Enter on the wallet selection screen: `create new wallet` starts the - /// existing creation flow, and a wallet row is a choice the app has to - /// resolve. + /// existing creation flow, and a wallet row switches the wallet child to + /// that row's file. /// - /// Resolving a row into the session is the wallet-store integration step: - /// the record's identity and locator have to be read back and loaded, and - /// `Node` has no wallet-record accessor yet. Until that lands the choice is - /// reported instead of silently dropped — an Enter that does nothing is - /// worse than one that says what is missing. + /// `WalletChoice::Open` carries a **row index**, so it is resolved against + /// the catalogue as it is now, not against anything the screen cached: two + /// saved wallets may share an identity key, and only the position (then the + /// row's own `wallet_filename`) names one. A list that changed under the + /// screen is reported rather than silently opening the wrong wallet. fn choose_wallet(&mut self) -> Result<(), String> { let Screen::WalletSelect { state } = &self.screen else { return Ok(()); @@ -2091,24 +2108,52 @@ impl App { typed: String::new(), }); } - WalletChoice::Open(_) => { - self.status_note = Some("wallet switching is not wired up yet".into()); + WalletChoice::Open(index) => { + let opened = self.select_wallet(index); + match opened { + Ok(label) => { + self.status_note = Some(format!("opened wallet {label}")); + self.screen = Screen::Main; + } + Err(e) => self.alert = Some(e), + } } } Ok(()) } - /// F6 `w`: the wallet selection screen. + /// Load the catalogue row at `index` into the session: point the wallet + /// child at that wallet's file (and restart it if it was running), then read + /// the list back so the screen never shows a stale catalogue. /// - /// The rows come from the wallet store; reading them is the integration - /// card's step (`Store::list_wallets`), and the render path never touches - /// the store. Until that accessor exists the screen opens on its - /// unavailable state, which says so — the `create new wallet` row at the - /// bottom works either way. + /// The stored identity and locator are not pushed into the session: they are + /// the identity/locator *at creation* (a locator rotates, and the identity is + /// the roster key this node already holds), so the live values keep coming + /// from the node. Returns the label to report. + fn select_wallet(&mut self, index: usize) -> Result { + let row = self + .node + .list_wallets()? + .into_iter() + .nth(index) + .ok_or_else(|| "the saved wallets changed — reopen the list".to_string())?; + self.node.open_wallet(&row.wallet_filename)?; + Ok(wallet_label(&row)) + } + + /// F6 `w`: the wallet selection screen, read from the catalogue now. + /// + /// The rows come from the wallet store ([`Node::list_wallets`]) at the + /// moment the screen opens — never cached from startup — so a wallet created + /// in this session shows up on the next look. A read that fails is the + /// screen's own error state, which is not the same word as "no saved + /// wallets": the `create new wallet` row stays reachable either way. fn open_wallet_select(&mut self) { - self.screen = Screen::WalletSelect { - state: WalletSelectState::error(SELECT_UNAVAILABLE.to_string()), + let state = match self.node.list_wallets() { + Ok(records) => WalletSelectState::from_rows(wallet_rows(records)), + Err(e) => WalletSelectState::error(e), }; + self.screen = Screen::WalletSelect { state }; } /// `c` on the WALLETS & SETTINGS menu: copy the receive address through the @@ -4556,6 +4601,37 @@ impl WalletSelectState { } } +/// Catalogue rows, display-ready and in store order (oldest first). +/// +/// The mapping is the one documented on [`WalletRow`]: a `NULL` label is the +/// empty string (the screen says `(unlabelled)`), the identity column is +/// `[u8; 32]` and is hex-encoded here, the locator passes through (empty until +/// the HS publishes), and `created_at` is unix seconds. `wallet_filename` is +/// not carried: it is not on the screen. The rows stay index-aligned with the +/// catalogue, which is how [`WalletChoice::Open`] resolves. +pub fn wallet_rows(records: Vec) -> Vec { + records + .into_iter() + .map(|r| WalletRow { + name: r.name.unwrap_or_default(), + identity_pubkey: to_hex(&r.identity_pubkey), + onion_locator: r.onion_locator, + created_at: r.created_at, + }) + .collect() +} + +/// What to call a saved wallet in a status line: its label, or the file when it +/// has none (a blank label is stored as `NULL`). +fn wallet_label(r: &WalletRecord) -> String { + r.name + .as_deref() + .map(str::trim) + .filter(|n| !n.is_empty()) + .unwrap_or(&r.wallet_filename) + .to_string() +} + /// Marker column in cells: `> ` when focused, ` ` otherwise. const WALLET_MARK_W: usize = 2; /// Identity column in cells: an 8-character prefix plus the ellipsis — 11 @@ -4923,11 +4999,6 @@ pub fn wallet_select_footer_hint() -> &'static str { const WALLET_SELECT_FOOTER_HINT: &str = "Esc back j k select Enter open ? help"; -/// The sub-line the screen prints when the wallet store has not been wired into -/// the app yet (see [`WalletRow`]): the list is genuinely unreadable, which is -/// not the same state as "no saved wallets". -pub const SELECT_UNAVAILABLE: &str = "the wallet store is not wired up yet"; - /// OSC 52 clipboard write for `text`: the terminal copies it, so no crate and /// no clipboard daemon are involved and it still works over SSH. A terminal /// that does not implement OSC 52 ignores the sequence. @@ -5333,3 +5404,169 @@ mod passphrase_buffer_tests { ); } } + +/// The wallet selection screen against a real store-backed node: the rows come +/// from the catalogue, a choice loads that wallet, and the start screen depends +/// on whether any wallet is remembered. +#[cfg(test)] +mod wallet_store_tests { + use super::*; + use crate::node::{test_node_with_wallets, test_record_wallet}; + + const PASS: &str = crate::node::tests::PASS; + + /// A real node (no Tor) over a seeded catalogue, plus the runtime the app + /// holds a handle to. `wallets` is `(file name, label)`; a blank label is a + /// wallet with no name, like one created from the app. + fn app(home: &std::path::Path, wallets: &[(&str, &str)]) -> (App, tokio::runtime::Runtime) { + let rt = tokio::runtime::Runtime::new().expect("tokio runtime"); + // The offline node's unbootstrapped Arti client needs a runtime context + // to be built (the same reason the node tests are `#[tokio::test]`). + let _guard = rt.enter(); + let node = test_node_with_wallets(home, wallets); + let app = App::new(node, rt.handle().clone()).expect("app"); + (app, rt) + } + + fn select_rows(app: &App) -> Vec { + let Screen::WalletSelect { state } = &app.screen else { + panic!("not on the wallet selection screen"); + }; + state + .rows + .iter() + .map(|r| r.name.clone()) + .collect::>() + } + + /// Nothing remembered means there is no list to choose from: the first run + /// goes straight to the existing creation flow. + #[test] + fn an_install_with_no_wallet_starts_on_the_create_flow() { + let dir = tempfile::tempdir().unwrap(); + let (app, _rt) = app(&dir.path().join("home"), &[]); + assert!( + matches!( + app.screen, + Screen::WalletSetup(WalletSetup::CreateWarn { .. }) + ), + "a first run must start on the create flow" + ); + } + + /// A restart lands on the wallets it remembers, and each row carries the + /// catalogue's own fields (label, hex identity, locator, creation time). + #[test] + fn an_install_with_wallets_starts_on_the_list_read_from_the_catalogue() { + let dir = tempfile::tempdir().unwrap(); + let (app, _rt) = app( + &dir.path().join("home"), + &[("onionwire", "lance"), ("onionwire-1", "")], + ); + let Screen::WalletSelect { state } = &app.screen else { + panic!("saved wallets must start on the selection screen"); + }; + assert!(state.error.is_none(), "{:?}", state.error); + assert!(!state.reading); + assert_eq!( + state.rows.len(), + 2, + "two saved wallets, plus the create row" + ); + assert_eq!(state.rows[0].name, "lance"); + assert_eq!(state.rows[1].name, ""); + assert_eq!( + state.rows[0].identity_pubkey, + to_hex(&app.node.identity_pk()) + ); + assert_eq!(state.rows[0].identity_pubkey.len(), 64, "hex, not bytes"); + assert_eq!(state.rows[0].onion_locator, "onionwire.onion"); + assert!(state.rows[0].created_at > 0, "creation time is real"); + assert_eq!(state.choice(), WalletChoice::Open(0)); + } + + /// The choice is a row index into a list whose records may share an + /// identity key, so the second row must open the second wallet's file. + #[test] + fn choosing_a_row_opens_that_wallets_file_not_the_first_identity_match() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, _rt) = app( + &dir.path().join("home"), + &[("onionwire", "lance"), ("onionwire-1", "cold")], + ); + { + let Screen::WalletSelect { state } = &mut app.screen else { + panic!("not on the selection screen"); + }; + state.select_next(); + assert_eq!(state.choice(), WalletChoice::Open(1)); + } + + app.choose_wallet().expect("choosing a saved wallet"); + + assert!( + matches!(app.screen, Screen::Main), + "a loaded wallet returns to the main view" + ); + assert_eq!( + app.node.wallet_child_config().wallet_filename, + "onionwire-1", + "the child must open the wallet under the marker" + ); + assert_eq!(app.status_note.as_deref(), Some("opened wallet cold")); + } + + /// The last item is not a wallet: Enter on it starts the creation flow. + #[test] + fn the_create_row_starts_the_creation_flow() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, _rt) = app(&dir.path().join("home"), &[("onionwire", "lance")]); + { + let Screen::WalletSelect { state } = &mut app.screen else { + panic!("not on the selection screen"); + }; + state.select_next(); + assert_eq!(state.choice(), WalletChoice::Create); + } + app.choose_wallet().expect("choosing create"); + assert!(matches!( + app.screen, + Screen::WalletSetup(WalletSetup::CreateWarn { .. }) + )); + } + + /// The list is read when the screen opens, never cached from startup, so a + /// wallet recorded in this session is offered the next time — that is what + /// makes a create show up without a restart. + #[test] + fn a_wallet_recorded_after_startup_appears_the_next_time_the_list_opens() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("home"); + let (mut app, _rt) = app(&home, &[]); + assert!(matches!(app.screen, Screen::WalletSetup(_))); + assert!( + app.node.list_wallets().expect("list wallets").is_empty(), + "nothing to list yet" + ); + + { + // The create path writes exactly this row (a `wallets` entry keyed + // on the file it just made). + let store = + crate::store::Store::open_at_with_passphrase(&home, PASS).expect("open store"); + test_record_wallet(&store, "onionwire-1", "fresh"); + } + + // F6 `w`. + app.open_wallet_select(); + assert_eq!(select_rows(&app), vec!["fresh".to_string()]); + + // And switching to it works from the screen the user is looking at. + app.choose_wallet().expect("open the new wallet"); + assert_eq!( + app.node.wallet_child_config().wallet_filename, + "onionwire-1" + ); + assert_eq!(app.status_note.as_deref(), Some("opened wallet fresh")); + } +} From 5f19a56be34dc22115ceed123a6396c1420e3ecd Mon Sep 17 00:00:00 2001 From: sirius Date: Tue, 22 Sep 2026 00:25:33 -0400 Subject: [PATCH 12/78] sdk: expose the wallet catalogue, the open wallet's keys, and the self profile The Android wallet/profile screens had nothing to call: the core could list wallets, switch the child onto one, read its keys and read/write the self profile, but none of it crossed UniFFI. Core: - Wallet::keys() -> WalletKeys { view_key, spend_key: Option }: two query_key calls against the file the RPC has open. A view-only wallet's -29 is spend_key: None, not an error. WalletKeys' Debug redacts both halves. - Node::wallet_keys() mirrors wallet_create/wallet_seed; refuses locally when no wallet is configured. - Node::active_wallet_filename() -> Option: the file the child is pointed at, None until wallet-child settings exist, so a client can mark the open row. SDK (UniFFI): - records WalletRow / WalletKeys / SelfProfile, and Wire::{wallets, open_wallet, active_wallet_filename, wallet_keys, self_profile, set_self_profile, push_self_profile}. - The rule the clients must express is in the docs: the seed and the private keys come from the OPEN wallet, so there is deliberately no accessor that reads another saved wallet's secrets without opening it. docs/WALLET.md (catalogue + 'secrets belong to the open wallet'), docs/THREAT_MODEL.md (the new on-demand-display exposure surface) and the SDK README are updated in the same commit. --- crates/onionwire-sdk/README.md | 18 ++ crates/onionwire-sdk/src/lib.rs | 385 +++++++++++++++++++++++++++++++- docs/THREAT_MODEL.md | 26 +++ docs/WALLET.md | 32 +++ src/node.rs | 124 ++++++++++ src/wallet.rs | 60 +++++ tests/wallet.rs | 142 ++++++++++++ 7 files changed, 784 insertions(+), 3 deletions(-) diff --git a/crates/onionwire-sdk/README.md b/crates/onionwire-sdk/README.md index 1cd7124..9635337 100644 --- a/crates/onionwire-sdk/README.md +++ b/crates/onionwire-sdk/README.md @@ -104,6 +104,24 @@ val msgs: List = wire.messages(friend.pubkeyHex) // 5. Locator rotation. Do NOT wire this to a single tap — the app that embeds // the SDK owns the typed confirmation. val out: RotateOutcome = wire.rotateOnion() // out.notified / out.friends + +// 6. Saved wallets, and which one is open. +val wallets: List = wire.wallets() // a store read: never dials +val active: String? = wire.activeWalletFilename() // the open file, or null +val open = wallets.firstOrNull { it.walletFilename == active } +wire.openWallet("onionwire-2") // may restart a running wallet child; a name + // outside the catalogue is refused +val keys: WalletKeys = wire.walletKeys() // the OPEN wallet's private keys +// keys.spendKey == null -> a view-only wallet (the RPC's -29 watch-only answer). +// That is not an error. The seed (`walletSeed()`) and these keys always belong +// to `activeWalletFilename()`: to show another wallet's backup, open it first. +// Both are spend secrets — show them from an explicit user action only, never +// log them, never persist them. + +// 7. Your own profile (nickname, bio, Monero address). +val me: SelfProfile = wire.selfProfile() +wire.setSelfProfile("ada", "on the wire", "4AdUnd...") // validated on write +wire.pushSelfProfile(friend.pubkeyHex) // signed `prf`, one-shot and fail-closed ``` All peer references are lowercase hex strings so nothing Rust-shaped leaks into diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index d17f7f3..11ca267 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -28,14 +28,14 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, OnceLock}; -use onionwire::Message; use onionwire::hs::TorState as CoreTorState; use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node}; use onionwire::outbox::{DEFAULT_MAX_ATTEMPTS, OutboxEntry, OutboxStatus}; use onionwire::pay; use onionwire::qr; -use onionwire::wallet::{ChainNetwork, ChainSource}; +use onionwire::wallet::{ChainNetwork, ChainSource, WalletKeys as CoreWalletKeys}; use onionwire::wallet_child::{ChildConfig, WalletChildState}; +use onionwire::{FriendProfile, Message, WalletRecord}; uniffi::setup_scaffolding!(); @@ -540,6 +540,128 @@ impl Wire { .collect()) } + // ---- Wallet catalogue, the open wallet, and its secrets ---- + + /// Every wallet this install remembers, oldest first. + /// + /// A store read: it never dials the wallet RPC or the chain, so it works + /// with the wallet child stopped or never configured. "No wallets" is an + /// empty list, never an error. `WireError.Stopped` after `shutdown`; + /// `WireError.Failed` only when the store itself cannot be read. + /// + /// The Kotlin binding is `Wire.wallets()`. + pub async fn wallets(&self) -> WResult> { + let rows = self.node()?.list_wallets().map_err(WireError::new)?; + Ok(rows.iter().map(wallet_row).collect()) + } + + /// Point the wallet child at a catalogue wallet's file: afterwards the + /// balance, transfers, seed and keys this surface reports are that + /// wallet's. + /// + /// **It may restart a running wallet child.** A live child is stopped and + /// started again onto the new file, which is what makes the change take + /// effect immediately — and why this call is slow (a `.onion` source waits + /// for its SOCKS listener, an in-process chain daemon for its RPC). An idle + /// child is only re-pointed: nothing is spawned, and the change applies at + /// the next [`Wire::start_wallet_child`]. + /// + /// A `filename` the catalogue does not hold is **refused**: the catalogue is + /// the only directory this app keeps wallets in, and a spend-capable child + /// is never pointed at a path a caller invented. Get the name from + /// [`Wire::wallets`]. `WireError.Stopped` after `shutdown`. + pub async fn open_wallet(&self, filename: String) -> WResult<()> { + self.node()?.open_wallet(&filename).map_err(WireError::new) + } + + /// The wallet file the child is currently pointed at, or `None` when no + /// wallet-child settings were ever stored (a fresh install has no open + /// wallet). + /// + /// A picker marks the open row with + /// `row.wallet_filename == active`; every other row means "open it first to + /// see its seed or keys", because the seed and the private keys always come + /// from the file the child has **open**. The value can name a file that is + /// not in the catalogue (an install whose wallet predates it) — that is "no + /// open wallet row", not an error. + /// + /// It never dials and never spawns. `WireError.Stopped` after `shutdown`. + pub async fn active_wallet_filename(&self) -> WResult> { + self.node()? + .active_wallet_filename() + .map_err(WireError::new) + } + + /// The private view key and spend key of the wallet file the child has + /// **open** (`query_key`). This is a dial to the wallet child's loopback + /// RPC, so call it from an explicit user action, not from a refresh loop. + /// + /// `spend_key` is `None` for a view-only wallet: the RPC answers `-29` + /// ("Cannot retrieve spend key") and that is the wallet's own answer, not a + /// failure, so it is not surfaced as one. `WireError.Failed` when no wallet + /// is configured or the child is not answering; `WireError.Stopped` after + /// `shutdown`. + /// + /// The values are spend secrets: show them, never log them, never persist + /// them. `WalletKeys`'s `Debug` redacts both. + pub async fn wallet_keys(&self) -> WResult { + let keys = self.node()?.wallet_keys().await.map_err(WireError::new)?; + Ok(keys_record(keys)) + } + + // ---- This identity's own profile ---- + + /// This identity's own profile (nickname, bio, Monero address) as stored. + /// + /// A store read: never dials. It is the local copy — what friends show for + /// you only changes once [`Wire::push_self_profile`] reaches them. + /// `WireError.Stopped` after `shutdown`. + pub async fn self_profile(&self) -> WResult { + let p = self.node()?.self_profile().map_err(WireError::new)?; + Ok(self_profile_record(&p)) + } + + /// Replace this identity's own profile. + /// + /// Validated before it is written, so a rejected edit leaves the stored + /// profile untouched: a nickname over 64 characters, a bio over 512, or a + /// non-empty address that fails the Monero checksum (the same check `/pay` + /// and `/tip` use) is refused with `WireError.Failed`. An empty address is + /// allowed. + /// + /// It does not tell anyone. Friends still see the previous profile until + /// [`Wire::push_self_profile`] is sent to them. `WireError.Stopped` after + /// `shutdown`. + pub async fn set_self_profile( + &self, + display_name: String, + bio: String, + xmr_addr: String, + ) -> WResult<()> { + self.node()? + .set_self_profile(&display_name, &bio, &xmr_addr) + .map_err(WireError::new) + } + + /// Send this identity's signed profile to one friend, so the nickname and + /// address they show for you are current. + /// + /// One-shot and fail closed: a peer whose onion is down means this fails + /// and **nothing is queued** — no retry, no outbox row (profiles are not + /// chat). Send it again when they are reachable. + /// + /// `pubkey_hex` is the friend's identity pubkey, the encoding + /// [`FriendInfo::pubkey_hex`] carries; an unparseable hex is + /// `WireError.Failed` before anything is dialled. `WireError.Stopped` after + /// `shutdown`. + pub async fn push_self_profile(&self, pubkey_hex: String) -> WResult<()> { + let pk = unhex(&pubkey_hex)?; + self.node()? + .push_self_profile(&pk) + .await + .map_err(WireError::new) + } + /// Send an invoice to a friend: sign an invoice for my receive address and send /// the frame one-shot. Peer onion down → this fails; invoices are not queued. /// @@ -1018,6 +1140,39 @@ fn outbox_row(entry: &OutboxEntry) -> OutboxRow { } } +/// `WalletRecord` → the picker row. `wallet_filename` is the file name only +/// (never a path): the core resolves it inside `$ONIONWIRE_HOME/wallet`. +fn wallet_row(w: &WalletRecord) -> WalletRow { + WalletRow { + id: w.id, + name: w.name.clone(), + wallet_filename: w.wallet_filename.clone(), + onion_locator: w.onion_locator.clone(), + identity_pubkey_hex: hex(&w.identity_pubkey), + created_at: w.created_at, + } +} + +/// The core's key record → the SDK's, with the secrets carried across verbatim +/// (this is a display path; nothing here logs or stores them). +fn keys_record(keys: CoreWalletKeys) -> WalletKeys { + WalletKeys { + view_key: keys.view_key, + spend_key: keys.spend_key, + } +} + +/// `FriendProfile` → the profile screen's record. `updated_at` is deliberately +/// not carried: the SDK surface has no use for it, and a client that wants +/// "did my push land" compares the fields it set. +fn self_profile_record(p: &FriendProfile) -> SelfProfile { + SelfProfile { + display_name: p.display_name.clone(), + bio: p.bio.clone(), + xmr_addr: p.xmr_addr.clone(), + } +} + /// A Monero transfer row for the wallet screen. /// /// `amount` is formatted XMR (not raw piconero) — the SDK formats it from the @@ -1029,6 +1184,71 @@ pub struct TransferRow { pub address: String, } +/// One row of the saved-wallet catalogue, for the wallet picker. +/// +/// Mirrors the core's `WalletRecord`, with the identity pubkey as hex. `id` is +/// the `wallets.id` row id, `wallet_filename` is the file inside +/// `$ONIONWIRE_HOME/wallet` and is what [`Wire::open_wallet`] takes, and the +/// rows come back oldest-first so a list is stable between calls. +/// +/// `identity_pubkey_hex` is the identity this wallet belongs to and is **not** +/// unique; `onion_locator` is a locator that may be empty or stale. Never key a +/// selection, or the roster, on the locator. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct WalletRow { + pub id: i64, + /// The user's label for this wallet. `None` when it was never named, and + /// never an empty string. + pub name: Option, + pub wallet_filename: String, + pub onion_locator: String, + /// The owning identity's ed25519 pubkey, hex — the same encoding + /// [`FriendInfo::pubkey_hex`] carries. + pub identity_pubkey_hex: String, + /// Unix seconds, assigned by the store when the row was created. + pub created_at: i64, +} + +/// The private keys of the **open** wallet file, for a backup screen. +/// +/// Both values are spend secrets: show them only from an explicit user action, +/// never log them, and never persist them. `Debug` is hand-written to redact +/// them so a stray `{:?}` cannot leak a key into a log. +#[derive(Clone, PartialEq, Eq, uniffi::Record)] +pub struct WalletKeys { + /// The open wallet file's private view key. + pub view_key: String, + /// The open wallet file's private spend key, or `None` for a view-only + /// wallet. `None` is the wallet's own answer — it has no spend key — and + /// not a failure. + pub spend_key: Option, +} + +/// Hand-written so a stray `{:?}` cannot print a private key. +impl std::fmt::Debug for WalletKeys { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("WalletKeys") + .field("view_key", &"") + .field("spend_key", &self.spend_key.as_ref().map(|_| "")) + .finish() + } +} + +/// This identity's own profile, as the profile screen reads and edits it. +/// +/// It is what friends are shown for this identity once it has been pushed; +/// nothing here is secret (an empty `xmr_addr` is allowed, a non-empty one is +/// validated). +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SelfProfile { + pub display_name: String, + pub bio: String, + /// This identity's Monero address. May be empty. When non-empty the core + /// refuses to store it unless it passes the same address check `/pay` and + /// `/tip` use. + pub xmr_addr: String, +} + /// Where the app-owned wallet child gets its chain from. Mirrors the core's /// `ChainSource`: nothing is implied — `Remote` is a daemon the user supplied. #[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] @@ -1341,8 +1561,8 @@ mod tests { //! handle, which is what a shut-down node must guarantee. A `Wire` with no //! node is exactly the state `shutdown()` leaves behind. use super::*; - use onionwire::Store; use onionwire::outbox::OutboxStatus; + use onionwire::{NewWallet, Store}; use std::path::PathBuf; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -2105,4 +2325,163 @@ mod tests { let err = block_on(stopped_wire().wallet_child_refresh()).expect_err("must fail"); assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); } + + // ---- wallet catalogue, the open wallet, its keys, and the self profile ---- + + #[test] + fn wallets_on_a_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().wallets()).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn open_wallet_on_a_stopped_handle_is_stopped_error() { + let err = + block_on(stopped_wire().open_wallet("onionwire".to_string())).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn active_wallet_filename_on_a_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().active_wallet_filename()).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn wallet_keys_on_a_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().wallet_keys()).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn self_profile_on_a_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().self_profile()).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn set_self_profile_on_a_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().set_self_profile( + "nick".to_string(), + String::new(), + String::new(), + )) + .expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn push_self_profile_on_a_stopped_handle_is_stopped_error() { + // Valid 32-byte hex, so the hex parse cannot be the thing that failed: + // the handle is. + let err = + block_on(stopped_wire().push_self_profile("11".repeat(32))).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn push_self_profile_rejects_a_pubkey_that_is_not_hex_before_any_work() { + let err = + block_on(stopped_wire().push_self_profile("nope".to_string())).expect_err("must fail"); + // The hex check runs first, so this is `Failed`, not `Stopped`. + assert!(matches!(err, WireError::Failed { .. }), "got {err:?}"); + } + + /// The picker row is the catalogue row, row for row: same id, same file + /// name, same label, and the pubkey as hex. A Kotlin picker keys on + /// `wallet_filename` for [`Wire::open_wallet`], so it has to be exact. + #[test] + fn wallet_rows_carry_the_catalogue_verbatim() { + let home = temp_home(); + let store = Store::open_at_with_passphrase(&home, "wallet-catalogue-pass").unwrap(); + let named = store + .create_wallet(&NewWallet { + name: Some("savings".to_string()), + identity_pubkey: [0xab; 32], + onion_locator: "peer.onion".to_string(), + wallet_filename: "onionwire-1".to_string(), + }) + .unwrap(); + let unnamed = store + .create_wallet(&NewWallet { + name: None, + identity_pubkey: [0xab; 32], + onion_locator: String::new(), + wallet_filename: "onionwire-2".to_string(), + }) + .unwrap(); + + let rows: Vec = store + .list_wallets() + .unwrap() + .iter() + .map(wallet_row) + .collect(); + + assert_eq!(rows.len(), 2, "both wallets are listed"); + assert_eq!(rows[0].id, named.id); + assert_eq!(rows[0].name.as_deref(), Some("savings")); + assert_eq!(rows[0].wallet_filename, "onionwire-1"); + assert_eq!(rows[0].onion_locator, "peer.onion"); + assert_eq!(rows[0].identity_pubkey_hex, "ab".repeat(32)); + assert_eq!(rows[0].created_at, named.created_at); + // A wallet created without a label is `None`, never an empty string. + assert_eq!(rows[1].id, unnamed.id); + assert_eq!(rows[1].name, None); + // The locator is a locator: it may be empty, and it is not an identity. + assert_eq!(rows[1].onion_locator, ""); + + std::fs::remove_dir_all(&home).ok(); + } + + #[test] + fn keys_mapping_carries_both_halves_and_the_view_only_answer() { + let both = keys_record(CoreWalletKeys { + view_key: "view-material".to_string(), + spend_key: Some("spend-material".to_string()), + }); + assert_eq!(both.view_key, "view-material"); + assert_eq!(both.spend_key.as_deref(), Some("spend-material")); + + let view_only = keys_record(CoreWalletKeys { + view_key: "view-material".to_string(), + spend_key: None, + }); + assert_eq!(view_only.view_key, "view-material"); + assert_eq!(view_only.spend_key, None); + } + + /// These two are spend secrets: the record the Kotlin side receives must not + /// print them through `Debug`, or a `{:?}` in a crash log leaks a key. + #[test] + fn wallet_keys_debug_never_prints_a_private_key() { + let keys = keys_record(CoreWalletKeys { + view_key: "VIEWKEYMATERIAL".to_string(), + spend_key: Some("SPENDKEYMATERIAL".to_string()), + }); + let printed = format!("{keys:?}"); + assert!( + !printed.contains("VIEWKEYMATERIAL"), + "view key leaked: {printed}" + ); + assert!( + !printed.contains("SPENDKEYMATERIAL"), + "spend key leaked: {printed}" + ); + assert!(printed.contains("redacted"), "got {printed}"); + } + + #[test] + fn self_profile_mapping_carries_the_three_editable_fields() { + let core = FriendProfile { + display_name: "nick".to_string(), + bio: "bio".to_string(), + xmr_addr: String::new(), + updated_at: 1_700_000_000, + }; + let got = self_profile_record(&core); + assert_eq!(got.display_name, "nick"); + assert_eq!(got.bio, "bio"); + assert_eq!(got.xmr_addr, ""); + } } diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 9781368..b3a7a44 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -249,6 +249,32 @@ the app does not pick a public remote node for them. Remote daemons are untrusted (`--trusted-daemon` off). Setup, view-only vs spend, and RPC credentials: [WALLET.md](WALLET.md). +## The recovery phrase and the private keys are displayable on demand + +Both clients can show the **open** wallet's recovery phrase (`query_key +mnemonic`) and its private view and spend keys (`query_key view_key` / +`spend_key`), from an explicit user action. That is new exposure the threat model +did not previously enumerate: the phone screen — and the Linux TUI window — is +now one of the places a spending secret can be read from. + +- The values come from the wallet file the child has **open**. There is no path + that reads another saved wallet's secret without opening it first, and none + that reads a wallet file directly: the RPC is the only source. +- They are never logged, never written to the store or any other file, and never + placed in an error string; the records that carry them (`WalletKeys`) redact + themselves under `Debug`. They exist in process memory only while a screen + shows them. +- They are shown only from an explicit user action, never on a refresh path. +- What this does **not** stop: a shoulder-surfer, a screen recorder, a + screenshot, or a malicious app with screen-capture permission. Whoever reads + the screen gets the keys; a view-only wallet leaks only the view key + (`spend_key` is `None`), but a spend-capable one leaks everything the file can + spend. +- The spend-authority warning above still applies and is now easier to reach: + the seed that makes a wallet spend-capable can be photographed off the device. + Treat any screen that shows a seed or a private key the way you treat the + wallet file itself. + ## Backup file is the identity `/backup` writes the identity and Noise static secrets. Treat the file like `onionwire.db`. Restore overwrites self keys and does **not** rewrite the friends table. diff --git a/docs/WALLET.md b/docs/WALLET.md index 054c48c..8b0255a 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -203,6 +203,36 @@ launches the node *and* the wallet child. `wallet_status()` carries Monero ships **no Android binaries**. Any vendored blob's provenance doc must say so. Cross-compiled is not device-proven. See `android/MONERO_BINARIES.md`. +### The wallet catalogue, and which wallet is open + +`wallets()` lists every wallet this install remembers (oldest first), each row +carrying the `wallet_filename` the child opens, its label, the owning identity +pubkey as hex, and the locator. `active_wallet_filename()` returns the file the +child is **currently pointed at** (or `None` on a fresh install), so a picker can +mark the open row. `open_wallet(filename)` switches to a catalogue row: a +running child is stopped and restarted onto the new file, an idle one is only +re-pointed (the change applies at the next `start_wallet_child`), and a file the +catalogue does not hold is refused — the catalogue is the only directory this app +keeps wallets in. + +## Secrets belong to the open wallet + +The seed (`wallet_seed()`, `query_key mnemonic`) and the private keys +(`wallet_keys()` → `query_key view_key` / `query_key spend_key`) are answered by +the wallet file the child has **open**, so they always belong to the row +`active_wallet_filename()` names. There is deliberately no accessor that reads +another saved wallet's seed or keys without opening it: show a backups screen, +then `open_wallet(...)` the row — the UI must say *which* wallet it is showing. +`WalletKeys.spend_key` is `None` for a view-only wallet (the RPC's `-29`), which +is an answer, not an error. + +Both values are spend secrets. They are displayable on demand in the TUI and in +the Android app, are never logged, never written to the store or to disk, and +never put into an error string (the core's `WalletKeys` `Debug` redacts them). +The exposure this creates is enumerated in +[THREAT_MODEL.md](THREAT_MODEL.md), "The recovery phrase and the private keys +are displayable on demand". + ## Create vs import `/wallet create` (`F6` then `c`) → `create_wallet`, then seed **once** @@ -263,6 +293,8 @@ Restore from a height at or before the first incoming transaction. | Profile `xmr_addr` fallback when RPC is down | works | works | | `/tip ` (`transfer`) | **cannot work** | works | | OnionWire copies your spend key into its own process | never | never (it stays in the wallet file / RPC) | +| Show the backup (seed via `query_key mnemonic`) | **no seed to show** (the RPC answers `-29`) | works | +| Show the private keys (`wallet_keys`) | view key only, `spend_key` is `None` | view + spend key | `ONIONWIRE_WALLET_NO_SPEND=1` refuses `/tip` before RPC with: diff --git a/src/node.rs b/src/node.rs index bbd0d24..923d3ca 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1232,6 +1232,43 @@ impl Node { w.mnemonic().await.map_err(|e| e.to_string()) } + /// The private view key and, when the wallet can spend, the private spend + /// key of the wallet file the child currently has **open** (`query_key`). + /// + /// Secrets therefore belong to the open wallet: viewing another saved + /// wallet's keys means opening it first. A view-only wallet answers `None` + /// for `spend_key` instead of an error (the RPC's `-29`). An unconfigured + /// wallet is refused locally, before any dial; a configured but unreachable + /// child surfaces the RPC error. + /// + /// The values are spend secrets: never log them and never persist them. + pub async fn wallet_keys(&self) -> Result { + let w = self.wallet_snapshot(); + if !w.configured() { + return Err(wallet::NOT_CONFIGURED_MSG.into()); + } + w.keys().await.map_err(|e| e.to_string()) + } + + /// The wallet file the child is currently pointed at, so a client can mark + /// the open row in the catalogue. `None` when no wallet-child settings have + /// ever been stored (a fresh install): a receive-only install has no open + /// wallet file, and the child never points at one until a wallet is created, + /// imported, or opened. + /// + /// The name is what the child would spawn with, not a message from the + /// running process, and it may not match a catalogue row (an install whose + /// wallet predates the catalogue). Match it against + /// [`Node::list_wallets`] rather than assuming it is there. + pub fn active_wallet_filename(&self) -> Result, String> { + let store = self.store.lock().map_err(|e| e.to_string())?; + let Some(raw) = store.load_wallet_child().map_err(|e| e.to_string())? else { + return Ok(None); + }; + let cfg = ChildConfig::from_record(&raw).map_err(|e| e.to_string())?; + Ok(cfg.map(|cfg| cfg.wallet_filename)) + } + /// Import a wallet from an existing 25-word seed. This is the only path /// that takes a user-supplied secret — and, like a create, it is remembered /// in the catalogue under its own file name. @@ -3374,4 +3411,91 @@ pub(crate) mod tests { "a refused switch must leave the child where it was" ); } + + /// The active wallet is a child-config fact, not a catalogue fact: a row in + /// the catalogue that the child was never pointed at is not open, and a + /// fresh install has no open wallet at all. + #[tokio::test] + async fn active_wallet_filename_is_none_until_the_child_has_been_pointed() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + + assert_eq!( + node.active_wallet_filename().expect("read"), + None, + "a fresh install has no open wallet file" + ); + + // A record written before the settings were persisted (creds, no + // source block) is not an open wallet either. + node.store + .lock() + .unwrap() + .save_wallet_child(r#"{"user":"owuser","pass":"ow-pass"}"#) + .unwrap(); + assert_eq!( + node.active_wallet_filename().expect("read"), + None, + "a creds-only record does not name a wallet file" + ); + + test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings"); + assert_eq!( + node.active_wallet_filename().expect("read"), + None, + "a catalogue row alone does not open the wallet" + ); + + node.open_wallet("onionwire-1") + .expect("open a saved wallet"); + assert_eq!( + node.active_wallet_filename().expect("read").as_deref(), + Some("onionwire-1"), + "the open wallet is the file the child was pointed at" + ); + } + + /// No wallet, no dial: the refusal is the configured-guard copy, not a + /// connection error, and it happens before any socket is opened. + #[tokio::test] + async fn wallet_keys_without_a_wallet_refuses_without_dialing() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + let err = node.wallet_keys().await.expect_err("no wallet configured"); + assert_eq!(err, wallet::NOT_CONFIGURED_MSG); + } + + /// The node-level path a Kotlin caller takes: two `query_key` calls against + /// the open wallet's RPC, with the view-only `-29` arriving as + /// `spend_key: None` rather than as an error. + #[tokio::test] + async fn wallet_keys_of_a_view_only_wallet_returns_no_spend_key() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind mock wallet"); + let port = listener.local_addr().expect("mock wallet addr").port(); + let reply: Arc String + Send + Sync> = Arc::new(|req: &str| { + if req.contains("spend_key") { + r#"{"jsonrpc":"2.0","id":"0","error":{"code":-29,"message":"The wallet is watch-only. Cannot retrieve spend key."}}"# + .to_string() + } else { + r#"{"jsonrpc":"2.0","id":"0","result":{"key":"aabbccdd"}}"#.to_string() + } + }); + tokio::spawn(serve_mock_rpc(listener, reply)); + + let dir = tempfile::tempdir().unwrap(); + let node = offline_node_with_wallet( + &dir.path().join("bob"), + Arc::new(NoDial), + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url"), + ); + + let keys = node.wallet_keys().await.expect("keys"); + assert_eq!(keys.view_key, "aabbccdd"); + assert_eq!( + keys.spend_key, None, + "the RPC's -29 is the wallet's answer, not a failure" + ); + } } diff --git a/src/wallet.rs b/src/wallet.rs index e4437da..787ee90 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -349,6 +349,27 @@ impl std::fmt::Debug for Endpoint { } } +/// The private keys of the wallet file the RPC currently has open. +/// +/// `view_key` is the private view key; `spend_key` is the private spend key and +/// is `None` — not an error — for a view-only wallet, which has no spend key to +/// hand out. Both are secrets: never log them, never persist them, and never put +/// them in an error string. +pub struct WalletKeys { + pub view_key: String, + pub spend_key: Option, +} + +/// Hand-written so a stray `{:?}` cannot print a private key. +impl std::fmt::Debug for WalletKeys { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("WalletKeys") + .field("view_key", &"") + .field("spend_key", &self.spend_key.as_ref().map(|_| "")) + .finish() + } +} + #[derive(Debug, Clone)] pub struct Wallet { endpoint: Option, @@ -807,6 +828,45 @@ impl Wallet { json_str(&v, "key") } + /// The wallet file's private keys, as the RPC reports them: `query_key` + /// `view_key` and `query_key` `spend_key`. + /// + /// Both come from the wallet file the child currently has **open** — this is + /// not a "read any saved wallet's keys" accessor, and it cannot be: the RPC + /// only ever answers for its open file. + /// + /// A view-only wallet has no spend key: its `query_key spend_key` answers + /// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (-29), which maps to + /// `spend_key: None` rather than an error, matching the `-29` view-only + /// detection the transfer probe already uses. Refuses locally, before any + /// dial, when the wallet is not configured. + /// + /// The two values are spend secrets: never log them, never store them, never + /// put them in an error string. [`WalletKeys`]'s `Debug` redacts both. + pub async fn keys(&self) -> Result { + if !self.configured() { + return Err(Error(NOT_CONFIGURED_MSG.into())); + } + let v = self + .rpc("query_key", serde_json::json!({"key_type": "view_key"})) + .await?; + let view_key = json_str(&v, "key")?; + // Asked second and separately: on a view-only wallet this is the call + // that carries the `-29`, and `None` is the honest answer there. + let spend_key = match self + .rpc("query_key", serde_json::json!({"key_type": "spend_key"})) + .await + { + Ok(v) => Some(json_str(&v, "key")?), + Err(e) if e.to_string() == VIEW_ONLY_MSG => None, + Err(e) => return Err(e), + }; + Ok(WalletKeys { + view_key, + spend_key, + }) + } + /// Import an existing wallet from its 25-word seed. This is the only path /// that takes a user-supplied secret. pub async fn restore_wallet(&self, filename: &str, password: &str, seed: &str) -> Result<()> { diff --git a/tests/wallet.rs b/tests/wallet.rs index 9c8649b..0724779 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -1,5 +1,6 @@ //! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod. +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use ed25519_dalek::SigningKey; @@ -893,6 +894,147 @@ fn mnemonic_on_an_unconfigured_wallet_is_a_refusal_not_a_dial() { assert_eq!(err.to_string(), NOT_CONFIGURED_MSG); } +/// The two private keys come from the open wallet file, in two `query_key` +/// calls: `view_key` first (always available), `spend_key` second (absent on a +/// view-only wallet). A wallet that can spend answers both. +#[tokio::test] +async fn keys_returns_the_view_and_spend_keys_of_the_open_wallet() { + const VIEW: &str = "0f0e0d0c0b0a09080706050403020100"; + const SPEND: &str = "0102030405060708090a0b0c0d0e0f10"; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let calls = Arc::new(AtomicUsize::new(0)); + let seen = Arc::clone(&calls); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(move |method: &str| match method { + "query_key" => match seen.fetch_add(1, Ordering::SeqCst) { + 0 => rpc_result(&format!(r#"{{"key":"{VIEW}"}}"#)), + _ => rpc_result(&format!(r#"{{"key":"{SPEND}"}}"#)), + }, + other => panic!("keys must only ask query_key, saw {other}"), + }), + None, + None, + )); + let keys = recording_wallet(port).keys().await.expect("keys"); + assert_eq!(keys.view_key, VIEW); + assert_eq!(keys.spend_key.as_deref(), Some(SPEND)); + assert_eq!(calls.load(Ordering::SeqCst), 2, "one call per key"); +} + +/// A view-only wallet has no spend key: the RPC answers `-29` +/// (`WALLET_RPC_ERROR_CODE_WATCH_ONLY`). That is the wallet's answer, so it must +/// come back as `spend_key: None` — not as an error, which would leave the +/// backup screen unable to show the view key. +#[tokio::test] +async fn keys_of_a_view_only_wallet_have_no_spend_key_and_no_error() { + const VIEW: &str = "aabbccddeeff00112233445566778899"; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let calls = Arc::new(AtomicUsize::new(0)); + let seen = Arc::clone(&calls); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(move |method: &str| match method { + "query_key" => match seen.fetch_add(1, Ordering::SeqCst) { + 0 => rpc_result(&format!(r#"{{"key":"{VIEW}"}}"#)), + _ => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."), + }, + other => panic!("keys must only ask query_key, saw {other}"), + }), + None, + None, + )); + let keys = recording_wallet(port) + .keys() + .await + .expect("a view-only wallet"); + assert_eq!(keys.view_key, VIEW); + assert_eq!( + keys.spend_key, None, + "view-only means no spend key to hand out" + ); +} + +/// Any *other* RPC failure is a real failure: a view-only `-29` is the only +/// error `keys` turns into `None`. +#[tokio::test] +async fn keys_surfaces_an_rpc_error_that_is_not_the_view_only_answer() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let calls = Arc::new(AtomicUsize::new(0)); + let seen = Arc::clone(&calls); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(move |_: &str| { + if seen.fetch_add(1, Ordering::SeqCst) == 0 { + rpc_result(r#"{"key":"aabbccdd"}"#) + } else { + rpc_error(-1, "wallet file is not open") + } + }), + None, + None, + )); + let err = recording_wallet(port) + .keys() + .await + .expect_err("a spend-key error that is not -29 must not read as view-only"); + let msg = err.to_string(); + assert!(msg.contains("wallet file is not open"), "got {err}"); + assert!(!msg.contains("secret"), "password leaked: {err}"); +} + +/// No endpoint, no dial: the refusal is the configured-guard copy the rest of +/// the wallet uses, not a connection error. +#[test] +fn keys_on_an_unconfigured_wallet_is_a_refusal_not_a_dial() { + let w = Wallet::disabled(); + let err = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(w.keys()) + .unwrap_err(); + assert_eq!(err.to_string(), NOT_CONFIGURED_MSG); +} + +/// The keys are spend secrets. `WalletKeys` is the value the whole path carries, +/// so its `Debug` must not print either key — a stray `{:?}` in a log is how a +/// key leaks. +#[test] +fn wallet_keys_debug_never_prints_a_private_key() { + let keys = wallet::WalletKeys { + view_key: "VIEWKEYMATERIAL".to_string(), + spend_key: Some("SPENDKEYMATERIAL".to_string()), + }; + let printed = format!("{keys:?}"); + assert!( + !printed.contains("VIEWKEYMATERIAL"), + "view key leaked: {printed}" + ); + assert!( + !printed.contains("SPENDKEYMATERIAL"), + "spend key leaked: {printed}" + ); + assert!(printed.contains("redacted"), "got {printed}"); + + let only_view = wallet::WalletKeys { + view_key: "VIEWKEYMATERIAL".to_string(), + spend_key: None, + }; + let printed = format!("{only_view:?}"); + assert!( + !printed.contains("VIEWKEYMATERIAL"), + "view key leaked: {printed}" + ); + assert!( + printed.contains("None"), + "a view-only wallet must read as None: {printed}" + ); +} + /// Answers the Digest challenge, then holds the reply for `delay`. Lets a test /// prove which call classes get which budget. async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) { From b6447f76d6c7a2ae49f629338bd09b539c8432a9 Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 22 Sep 2026 00:28:39 -0400 Subject: [PATCH 13/78] android: collapse the roster identity block into a dropdown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The identity card's full fingerprint wraps to several lines on a phone and pushes the friend list off the first screen. Collapse it: one line by default (label + `shortId(fingerprint)` + chevron), the full fingerprint and the full onion behind a tap, in the order they already had. The `sdk …` line and `keepAliveNote` stay outside the disclosure — the keep-alive denial is the only place that note appears, so hanging it off a collapsed block would hide it. `shortId` is a pure top-level function (`head … tail`, unchanged when the value is no longer than the abbreviation, empty stays empty) so the collapsed line is a slice of the value shown expanded, not a parallel encoding. The expand state is `rememberSaveable`: a rotation keeps what the user chose, and nothing about it belongs in the store. RosterIdTest covers the abbreviation on the JVM (7 cases: the 64-hex fingerprint, the head/tail boundary, custom head/tail, shorter-than-input, empty, single-char ellipsis). --- .../siriusdevops/onionwire/ui/RosterScreen.kt | 53 ++++++++++-- .../siriusdevops/onionwire/ui/RosterIdTest.kt | 84 +++++++++++++++++++ 2 files changed, 132 insertions(+), 5 deletions(-) create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/ui/RosterIdTest.kt diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt index ed641dc..b3903cd 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt @@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Card @@ -27,6 +28,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -51,6 +53,10 @@ fun RosterScreen( onOpenWallet: () -> Unit, ) { var confirmWipe by remember { mutableStateOf(false) } + // Closed by default; `rememberSaveable` so a rotation keeps whatever the + // user chose instead of snapping back to (or away from) the summary. + // Nothing about this is worth persisting to the store. + var identityExpanded by rememberSaveable { mutableStateOf(false) } Scaffold( // The content root below consumes systemBars ∪ ime itself (see @@ -79,11 +85,33 @@ fun RosterScreen( ), ) { Column(Modifier.padding(12.dp)) { - Label("YOU (stable forever)") - Mono(fingerprint) - Spacer(Modifier.height(10.dp)) - Label("ONION (locator — rotates)") - Mono(onion) + // The disclosure header. Collapsed, this one line *is* the + // identity block: the label, the abbreviated fingerprint, + // and a chevron saying there is more behind it. + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { identityExpanded = !identityExpanded }, + verticalAlignment = Alignment.CenterVertically, + ) { + Label("YOU (stable forever)") + if (!identityExpanded) { + Spacer(Modifier.width(8.dp)) + Mono(shortId(fingerprint)) + } + Spacer(Modifier.weight(1f)) + Text( + if (identityExpanded) "▾" else "▸", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (identityExpanded) { + Mono(fingerprint) + Spacer(Modifier.height(10.dp)) + Label("ONION (locator — rotates)") + Mono(onion) + } Spacer(Modifier.height(10.dp)) Text( "sdk $sdkVersion · identity = ed25519 pubkey", @@ -194,6 +222,21 @@ private fun FriendRow(f: FriendInfo, onClick: () -> Unit) { } } +/** + * The compact stand-in for a long identity string: `head` characters, an + * ellipsis, then `tail` characters. Pure, so the roster's collapsed line and + * its unit test agree on what "short" means. + * + * A string no longer than the abbreviation is returned unchanged — the + * abbreviation must never grow a value, and a short value must never come back + * mangled. Kotlin strings are UTF-16, but these IDs are hex, so `take`/ + * `takeLast` cannot split a surrogate pair here. + */ +fun shortId(id: String, head: Int = 6, tail: Int = 4): String { + if (id.length < head + tail + 1) return id + return id.take(head) + "…" + id.takeLast(tail) +} + @Composable fun Label(text: String) { Text( diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/RosterIdTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/RosterIdTest.kt new file mode 100644 index 0000000..d890fb3 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/RosterIdTest.kt @@ -0,0 +1,84 @@ +package com.siriusdevops.onionwire.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * `shortId`, the roster's collapsed identity line, on the JVM. + * + * The collapsed card shows the fingerprint through this function, and the + * expanded one shows the raw value; the two must never disagree about what the + * fingerprint *is*, so the abbreviation has to be a pure slice of the input + * with nothing invented. Pure logic, no Robolectric — same shape as + * `SeedBackupGateTest` and `WalletChildStatusTextTest`. + */ +class RosterIdTest { + + /** An ed25519 pubkey as the core prints it: 64 lowercase hex characters. */ + private val fingerprint = + "9f2c41ab77de03b5c8e1f0a6d4b39c2e5a7f81c0d3e6b492af17c5d80e3b6a49" + + // --- the long case ------------------------------------------------------- + + @Test + fun a_long_fingerprint_becomes_head_ellipsis_tail() { + assertEquals("9f2c41…6a49", shortId(fingerprint)) + } + + @Test + fun the_abbreviation_is_a_slice_of_the_input_not_a_re_encoding() { + // The head and the tail must be literally the input's own characters: + // a summary that cannot be checked against the full value is worse than + // no summary. + val short = shortId(fingerprint) + assertEquals(fingerprint.take(6), short.substringBefore("…")) + assertEquals(fingerprint.takeLast(4), short.substringAfter("…")) + // Nothing invented to pad the middle: 6 + "…" + 4. + assertEquals(11, short.length) + } + + @Test + fun head_and_tail_are_call_sites_choice() { + assertEquals("9f2c…6a49", shortId(fingerprint, head = 4, tail = 4)) + assertEquals("9f2c41ab77…3b6a49", shortId(fingerprint, head = 10, tail = 6)) + } + + // --- the short case ------------------------------------------------------ + + @Test + fun a_string_shorter_than_head_tail_plus_one_is_returned_unchanged() { + // head + tail + 1 == 11 here, so anything of 10 characters or fewer has + // no middle worth hiding. + assertEquals("abcdefghij", shortId("abcdefghij")) + assertEquals("abc", shortId("abc")) + assertEquals("a", shortId("a")) + } + + @Test + fun the_first_length_that_abbreviates_is_head_tail_plus_one() { + // The boundary, both sides: 10 unchanged, 11 abbreviated to the same + // length with the middle character collapsed. + assertEquals("abcdefghij", shortId("abcdefghij")) + assertEquals("abcdef…hijk", shortId("abcdefghijk")) + } + + // --- the empty case ------------------------------------------------------ + + @Test + fun an_empty_string_stays_empty() { + // `ready.fingerprint` is always populated in practice, but the function + // must not turn "nothing" into "…" on a card that is already on screen. + assertEquals("", shortId("")) + } + + // --- the shape the card relies on --------------------------------------- + + @Test + fun the_ellipsis_is_the_single_character_one() { + // U+2026, not three dots: the collapsed line is monospace and a + // three-dot tail is four cells where the design budgeted one. + assertTrue(shortId(fingerprint).contains("\u2026")) + assertEquals(1, shortId(fingerprint).count { it == '\u2026' }) + } +} From 812c259f460112d4bda06877f20a172311eacec7 Mon Sep 17 00:00:00 2001 From: apk-dev Date: Tue, 22 Sep 2026 01:23:47 -0400 Subject: [PATCH 14/78] android: saved-wallets screen (list, select, back up the open wallet) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The app could hold several wallets and show none of them. Add the screen that lists the store's catalogue, marks the one the wallet child has open, switches to another on a tap, and — for the open one only — shows its recovery phrase and private keys. Everything secret here belongs to the file the child currently has open: `query_key` is answered by that file and no other, so the seed card and the keys card hang off `active_wallet_filename()`, not off a row. On a row that is not the open one both actions are dead and say why ("open this wallet to view its backup") instead of opening it under the user — switching wallets is a deliberate tap, because `open_wallet` stops and restarts a running child. The phrase keeps the existing treatment: the wallet screen's own `SeedBackupCard`, widened from `private` to `internal` rather than copied, so the gate constants are still the one `SeedBackupGate`. The keys card shows the view key always and the spend key when there is one; a view-only wallet says "view-only wallet — no spend key" in words, because `null` is the wallet's own answer and not a failure. Neither value is logged, persisted, tagged, or held in saved state, and both are dropped on dispose. The catalogue is re-read on entry and on Refresh, never cached from app start, so a wallet created on the wallet screen after this one was first opened shows up without restarting the app. An empty catalogue ("No saved wallets yet") and a read failure ("could not read the wallet catalogue" + the core's text) are rendered as the two different states they are. The gate is pure Kotlin in the new file and `WalletManagerTest` covers it on the JVM (17 cases): the row label's name/blank/whitespace fallback, which child states count as readable, and whether the secret actions are offered for a row. --- .../siriusdevops/onionwire/MainActivity.kt | 11 +- .../siriusdevops/onionwire/WireViewModel.kt | 46 ++ .../onionwire/ui/WalletManagerScreen.kt | 584 ++++++++++++++++++ .../siriusdevops/onionwire/ui/WalletScreen.kt | 14 +- .../onionwire/ui/WalletManagerTest.kt | 153 +++++ 5 files changed, 806 insertions(+), 2 deletions(-) create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt index 1d14fa6..200c2b8 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt @@ -29,6 +29,7 @@ import com.siriusdevops.onionwire.ui.RosterScreen import com.siriusdevops.onionwire.ui.RotateScreen import com.siriusdevops.onionwire.ui.ShareInviteScreen import com.siriusdevops.onionwire.ui.UnlockScreen +import com.siriusdevops.onionwire.ui.WalletManagerScreen import com.siriusdevops.onionwire.ui.WalletScreen import com.siriusdevops.onionwire.ui.OnionWireTheme import kotlinx.coroutines.launch @@ -133,7 +134,15 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: Str } composable("wallet") { - WalletScreen(vm = vm, onBack = { nav.popBackStack() }) + WalletScreen( + vm = vm, + onBack = { nav.popBackStack() }, + onOpenWallets = { nav.navigate("wallets") }, + ) + } + + composable("wallets") { + WalletManagerScreen(vm = vm, onBack = { nav.popBackStack() }) } composable( diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 7be3c6a..3c071c8 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -41,6 +41,8 @@ import uniffi.onionwire_sdk.RotateOutcome import uniffi.onionwire_sdk.SendState import uniffi.onionwire_sdk.TransferRow import uniffi.onionwire_sdk.WalletChildStatus +import uniffi.onionwire_sdk.WalletKeys +import uniffi.onionwire_sdk.WalletRow import uniffi.onionwire_sdk.Wire import uniffi.onionwire_sdk.decodeInvite import java.io.File @@ -619,6 +621,50 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { suspend fun walletSeed(): Result = runCatching { requireWire().walletSeed() } + // --- Wallet catalogue, the open wallet, and its secrets ---------------- + // The saved-wallets screen's reads. The catalogue is a store read that + // never dials, so it goes to [Dispatchers.IO] like the other store reads in + // this file — a SQLCipher decrypt on the main thread is an ANR waiting for a + // slow device. + + /** + * Every wallet this install remembers, oldest first. + * + * A store read: it works with the wallet child stopped or never configured, + * and "no wallets" is an empty list rather than a failure — the caller must + * not render the two alike. + */ + suspend fun wallets(): Result> = + withContext(Dispatchers.IO) { runCatching { requireWire().wallets() } } + + /** + * The file name of the wallet the child currently has open, or null when it + * has none. The catalogue's in-use marker is this and nothing else. + */ + suspend fun activeWalletFilename(): Result = + withContext(Dispatchers.IO) { runCatching { requireWire().activeWalletFilename() } } + + /** + * Point the wallet child at a catalogue wallet's file. + * + * Slow on purpose: a live child is stopped and started again onto the new + * file. The core refuses a name the catalogue does not hold, and that + * refusal is surfaced verbatim to the caller. + */ + suspend fun openWallet(filename: String): Result = + withContext(Dispatchers.IO) { runCatching { requireWire().openWallet(filename) } } + + /** + * The **open** wallet's private keys, for the saved-wallets screen. + * + * Both values are spend secrets: only ever called from an explicit tap, + * never logged, never persisted, and dropped when the screen goes. There is + * deliberately no accessor for another catalogue row's keys — the only way + * to read a saved wallet's keys is to open it first. + */ + suspend fun walletKeys(): Result = + withContext(Dispatchers.IO) { runCatching { requireWire().walletKeys() } } + fun spendAuthorityWarning(): String = runCatching { requireWire().spendAuthorityWarning() }.getOrElse { diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt new file mode 100644 index 0000000..d041575 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt @@ -0,0 +1,584 @@ +package com.siriusdevops.onionwire.ui + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.siriusdevops.onionwire.WireViewModel +import kotlinx.coroutines.launch +import uniffi.onionwire_sdk.WalletKeys +import uniffi.onionwire_sdk.WalletRow +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter + +// --------------------------------------------------------------------------- +// The rules this screen renders from, as pure Kotlin so `WalletManagerTest` +// covers them on the JVM without a device. Same shape as `SeedBackupGate` and +// `WalletChildStatusText`: the composables below only lay these decisions out. +// --------------------------------------------------------------------------- + +/** + * A catalogue row's label: the user's name for the wallet, or the file name + * when there is none. + * + * `WalletRow.name` is documented as `None` when the wallet was never named and + * "never an empty string", but a blank string is treated as absent here too — + * a row labelled with spaces is a row the user cannot identify. + */ +internal fun walletRowLabel(name: String?, filename: String): String = + name?.takeIf { it.isNotBlank() } ?: filename + +/** + * A row's creation date, from the store's unix seconds. + * + * `created_at <= 0` is not a date: the store assigns it on insert, so anything + * else is a row that predates that — say so rather than render 1970. + */ +internal fun walletRowDate(createdAt: Long): String { + if (createdAt <= 0L) return "date unknown" + return Instant.ofEpochSecond(createdAt) + .atZone(ZoneId.systemDefault()) + .format(DateTimeFormatter.ISO_LOCAL_DATE) +} + +/** + * Whether the wallet child has a wallet open that the RPC answers for. + * + * The core's `state` is the only honest signal available here: `connecting` + * means its wallet RPC has not answered, `off`/`exited` mean there is no child + * at all, and `syncing`/`ready` mean it answered — the chain being behind is + * irrelevant to whether the open wallet's keys can be read. A `null` state is + * "nothing read yet", which is not readable. + */ +internal fun walletChildReadable(state: String?): Boolean = + state == "ready" || state == "syncing" + +/** + * Whether the open wallet's secrets may be offered for the row named + * [rowFilename]. + * + * Both halves are load-bearing: + * + * - **active**: the seed and the private keys come from `query_key` against + * the file the child currently has open, so they belong to exactly one + * wallet. A non-active row's buttons stay dead instead of quietly opening + * that wallet under the user — switching is a deliberate tap, not a side + * effect of asking for a backup. + * - **readable**: with no child running there is no file open, and + * `wallet_seed()` / `wallet_keys()` can only fail. Offering a button that + * always errors is worse than saying why it is off. + */ +internal fun walletSecretsEnabled( + activeFilename: String?, + rowFilename: String, + walletReadable: Boolean, +): Boolean = walletReadable && activeFilename != null && activeFilename == rowFilename + +/** + * Why the secret actions are off, in words — or `null` when they are on. + * + * The two reasons are different states of the world and are not collapsed: + * "this is not the open wallet" is fixed by tapping the row, "the child is not + * running" is fixed on the wallet screen. The first wording is the card's own. + */ +internal fun walletSecretsBlockedReason( + isActive: Boolean, + walletReadable: Boolean, +): String? = when { + !isActive -> "open this wallet to view its backup" + !walletReadable -> "the wallet child is not running — start it on the wallet screen to read the backup" + else -> null +} + +/** + * The saved-wallet catalogue: every wallet this install remembers, which one is + * open now, and — for that one — its recovery phrase and private keys. + * + * Three properties are deliberate and are the whole point of the screen: + * + * - The catalogue is re-read on entry and on Refresh, never cached from app + * start, so a wallet created on the wallet screen after this screen was + * first opened shows up without restarting the app. + * - A tap opens a row's file through `open_wallet(filename)` and reloads, so + * the in-use marker moves. The core refuses a name outside the catalogue, + * and its refusal is shown verbatim. + * - The secrets belong to the **open** wallet only. They are read on an + * explicit tap, are never shown for a row that is not the open one, and are + * never logged, persisted, put in a `testTag`/`contentDescription`, or held + * in saved state (`remember`, not `rememberSaveable`, and cleared on + * dispose). + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun WalletManagerScreen( + vm: WireViewModel, + onBack: () -> Unit, +) { + val child by vm.walletChild.collectAsStateWithLifecycle() + val scope = rememberCoroutineScope() + + /** `null` is "not read yet"; an empty list is a catalogue with no rows. */ + var rows by remember { mutableStateOf?>(null) } + /** The file name the core reports as open, or null when it reports none. */ + var active by remember { mutableStateOf(null) } + /** A catalogue/active-wallet read failure, distinct from an empty list. */ + var listError by remember { mutableStateOf(null) } + /** A failed open, verbatim from the core. */ + var actionError by remember { mutableStateOf(null) } + /** The file name currently being opened, so the row can say so. */ + var opening by remember { mutableStateOf(null) } + + // The seed on the blocking card, and the typed confirm word. Neither is + // persisted: a spend key lives in this composition and nowhere else. + var seed by remember { mutableStateOf(null) } + var seedConfirm by remember { mutableStateOf("") } + // The open wallet's private keys, only ever set by an explicit tap on + // "Private keys". Null means no card. + var keys by remember { mutableStateOf(null) } + var keysError by remember { mutableStateOf(null) } + + suspend fun reload() { + vm.wallets().fold( + onSuccess = { + rows = it + listError = null + }, + onFailure = { + rows = null + listError = it.message ?: it.toString() + }, + ) + vm.activeWalletFilename().fold( + onSuccess = { active = it }, + onFailure = { + // Same store as the list: a failure here is a read failure, not + // "no wallet is open", and it must not be rendered as one. + active = null + if (listError == null) { + listError = it.message ?: it.toString() + } + }, + ) + } + + /** Open a row's file, then re-read so the in-use marker moves. */ + fun open(filename: String) { + if (opening != null) return + scope.launch { + actionError = null + opening = filename + vm.openWallet(filename).fold( + onSuccess = { reload() }, + onFailure = { actionError = it.message ?: it.toString() }, + ) + opening = null + } + } + + /** + * "Recovery phrase": re-read the open wallet's 25 words and put them on the + * existing blocking card. Same treatment as the wallet screen's "Back up + * seed" — one gate, one card, no second ungated display. + */ + fun showPhrase() { + scope.launch { + actionError = null + vm.walletSeed().fold( + onSuccess = { + seed = it + seedConfirm = "" + }, + onFailure = { actionError = it.message ?: it.toString() }, + ) + } + } + + /** + * "Private keys": read the open wallet's keys once, on this tap. Failure is + * shown where the card would be, so a wallet that cannot answer says so + * instead of looking like an empty one. + */ + fun showKeys() { + scope.launch { + actionError = null + keysError = null + vm.walletKeys().fold( + onSuccess = { keys = it }, + onFailure = { keysError = it.message ?: it.toString() }, + ) + } + } + + LaunchedEffect(Unit) { + // The cached child read never dials, so the screen paints; the live + // probe after it is what tells the truth about whether a wallet is + // open, which is what the secret actions hang on. + vm.paintWalletChildCached() + reload() + vm.refreshWalletChild() + } + + // Nothing here is `rememberSaveable`, so leaving the screen drops the + // composition's state — including the seed and the keys. Dropping the + // reference is the strongest wipe a Kotlin String allows (see + // `SeedBackupCard`); this makes it explicit rather than incidental. + DisposableEffect(Unit) { + onDispose { + seed = null + seedConfirm = "" + keys = null + keysError = null + } + } + + val walletReadable = walletChildReadable(child?.state) + + Scaffold( + // Root owns systemBars ∪ ime, exactly as the wallet screen does (see + // `screenContentInsets`). + contentWindowInsets = WindowInsets(0, 0, 0, 0), + topBar = { + TopAppBar( + title = { Text("Saved wallets") }, + navigationIcon = { + TextButton(onClick = onBack) { Text("Back") } + }, + actions = { + TextButton( + onClick = { + scope.launch { + vm.refreshWalletChild() + reload() + } + }, + ) { Text("Refresh") } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.background, + ), + ) + }, + ) { pad -> + Column( + Modifier + .padding(pad) + .fillMaxSize() + .screenContentInsets() + .verticalScroll(rememberScrollState()), + ) { + // The blocking seed card, when a phrase is on screen: the whole + // body, exactly as on the wallet screen. Done is dead until the + // confirm word is typed, and the app-bar Back still leaves. + val shownSeed = seed + if (shownSeed != null) { + SeedBackupCard( + seed = shownSeed, + typed = seedConfirm, + onTyped = { seedConfirm = it }, + onDone = { + vm.confirmWalletSeed(seedConfirm) + seed = null + seedConfirm = "" + }, + ) + actionError?.let { ErrorText(it) } + return@Column + } + + keys?.let { k -> + PrivateKeysCard( + keys = k, + warning = vm.spendAuthorityWarning(), + onDone = { keys = null }, + ) + } + keysError?.let { message -> + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text("could not read the open wallet's private keys") + Spacer(Modifier.height(4.dp)) + Text(message, style = MaterialTheme.typography.bodySmall) + Spacer(Modifier.height(8.dp)) + TextButton(onClick = { keysError = null }) { Text("Dismiss") } + } + } + } + + actionError?.let { ErrorText(it) } + + val listed = rows + when { + // A read failure is not an empty catalogue, and the two must + // not read alike: one is "the store did not answer", the other + // is "you have no wallets yet". + listError != null -> Column(Modifier.padding(12.dp)) { + Text( + "could not read the wallet catalogue", + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.error, + ) + Spacer(Modifier.height(4.dp)) + Text( + listError ?: "", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + Spacer(Modifier.height(8.dp)) + TextButton(onClick = { scope.launch { reload() } }) { Text("Retry") } + } + + listed == null -> Text( + "loading…", + style = MaterialTheme.typography.bodyMedium, + modifier = Modifier.padding(12.dp), + ) + + listed.isEmpty() -> Column(Modifier.padding(12.dp)) { + Text("No saved wallets yet", style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(4.dp)) + Text( + "Wallets this install remembers show up here. Create or import one " + + "on the wallet screen and it appears on the next look.", + style = MaterialTheme.typography.bodySmall, + ) + Spacer(Modifier.height(8.dp)) + Button(onClick = onBack) { Text("Create or import a wallet") } + } + + else -> { + Text( + "${listed.size} saved ${if (listed.size == 1) "wallet" else "wallets"}", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) + listed.forEach { row -> + val isActive = active != null && active == row.walletFilename + WalletRowCard( + row = row, + isActive = isActive, + secretsEnabled = walletSecretsEnabled( + activeFilename = active, + rowFilename = row.walletFilename, + walletReadable = walletReadable, + ), + blockedReason = walletSecretsBlockedReason( + isActive = isActive, + walletReadable = walletReadable, + ), + opening = opening == row.walletFilename, + onOpen = { open(row.walletFilename) }, + onShowPhrase = { showPhrase() }, + onShowKeys = { showKeys() }, + ) + } + } + } + } + } +} + +/** + * One catalogue row: what it is called, which file it is, when it was created, + * and whether it is the open one. + * + * The open row is not tappable. Re-opening it would stop and restart a running + * wallet child onto the file it already has open — a slow no-op whose only + * effect is to make the screen look like it did something. + */ +@Composable +private fun WalletRowCard( + row: WalletRow, + isActive: Boolean, + secretsEnabled: Boolean, + blockedReason: String?, + opening: Boolean, + onOpen: () -> Unit, + onShowPhrase: () -> Unit, + onShowKeys: () -> Unit, +) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 6.dp) + .then(if (isActive) Modifier else Modifier.clickable(enabled = !opening, onClick = onOpen)), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column(Modifier.padding(12.dp)) { + Row( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + walletRowLabel(row.name, row.walletFilename), + style = MaterialTheme.typography.titleSmall, + ) + when { + isActive -> Text( + "in use", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + ) + opening -> Text( + "opening…", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + else -> Text( + "tap to open", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + Spacer(Modifier.height(4.dp)) + Text( + "file ${row.walletFilename}", + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + ) + Text( + "created ${walletRowDate(row.createdAt)}", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + Spacer(Modifier.height(8.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedButton(onClick = onShowPhrase, enabled = secretsEnabled) { + Text("Recovery phrase") + } + OutlinedButton(onClick = onShowKeys, enabled = secretsEnabled) { + Text("Private keys") + } + } + blockedReason?.let { + Spacer(Modifier.height(4.dp)) + Text( + it, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } +} + +/** + * The open wallet's private keys, shown only after an explicit tap. + * + * The view key is always there; the spend key only when the wallet has one. + * A view-only wallet says so in words — it has no spend key, and rendering + * that as a failure would teach the user to read a normal wallet as a broken + * one. The values are spend secrets: no `testTag`, no `contentDescription`, + * no logging, no persistence, and the card is dropped when the screen goes. + */ +@Composable +private fun PrivateKeysCard( + keys: WalletKeys, + warning: String, + onDone: () -> Unit, +) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text("Private keys of the open wallet", style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(4.dp)) + Text(warning, style = MaterialTheme.typography.bodySmall) + Spacer(Modifier.height(8.dp)) + Text( + "view key", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + keys.viewKey, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + ) + Spacer(Modifier.height(8.dp)) + val spend = keys.spendKey + if (spend != null) { + Text( + "spend key", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + spend, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + ) + } else { + Text( + "view-only wallet — no spend key", + style = MaterialTheme.typography.bodyMedium, + ) + } + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + Button(onClick = onDone) { Text("Done") } + } + } + } +} + +/** A display-ready failure line. Never carries a secret; callers pass errors. */ +@Composable +private fun ErrorText(text: String) { + Text( + text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index ec98015..f6ea31c 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -70,6 +70,7 @@ private enum class SetupKind { Create, Import } fun WalletScreen( vm: WireViewModel, onBack: () -> Unit, + onOpenWallets: () -> Unit, ) { val friends by vm.friends.collectAsStateWithLifecycle() val child by vm.walletChild.collectAsStateWithLifecycle() @@ -161,6 +162,12 @@ fun WalletScreen( navigationIcon = { TextButton(onClick = onBack) { Text("Back") } }, + // The saved-wallet catalogue is its own screen: this one is the + // open wallet, and switching wallets restarts the child, so the + // picker does not belong in this page's scroll. + actions = { + TextButton(onClick = onOpenWallets) { Text("Wallets") } + }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.background, ), @@ -548,9 +555,14 @@ private fun UnbackedSeedCard( * The seed is a Kotlin `String`, so it cannot be wiped in place the way the * TUI's `Zeroizing` is; dropping the reference is the strongest thing * available here. That is another reason it is never written to disk. + * + * `internal` rather than `private`: the saved-wallets screen shows the same + * card for the open wallet's recovery phrase, and a second copy of this gate + * (or of its constants) is the thing that would eventually disagree with this + * one. */ @Composable -private fun SeedBackupCard( +internal fun SeedBackupCard( seed: String, typed: String, onTyped: (String) -> Unit, diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt new file mode 100644 index 0000000..99a35e4 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt @@ -0,0 +1,153 @@ +package com.siriusdevops.onionwire.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The saved-wallets screen's rules, on the JVM. + * + * These are the decisions the screen renders from: what a catalogue row is + * called, whether the child has a wallet open at all, and whether the two + * secret actions may be offered for a given row. Pure logic, so no Robolectric + * and no Compose test dependency — same shape as `SeedBackupGateTest` and + * `WalletChildStatusTextTest`. + */ +class WalletManagerTest { + + private val openFile = "onionwire-main" + private val otherFile = "onionwire-second" + + /** The core's `wallet_status().state` for a child that answered. */ + private val readable = true + + /** No child, or one whose wallet RPC has not answered. */ + private val notReadable = false + + // --- what a row is called ----------------------------------------------- + + @Test + fun a_named_wallet_is_labelled_with_its_name() { + assertEquals("spending", walletRowLabel("spending", openFile)) + } + + @Test + fun an_unnamed_wallet_falls_back_to_its_file_name() { + assertEquals(openFile, walletRowLabel(null, openFile)) + } + + @Test + fun a_blank_name_counts_as_absent() { + // `WalletRow.name` is documented as never an empty string, but a + // whitespace label is a row the user cannot identify either way. + assertEquals(openFile, walletRowLabel("", openFile)) + assertEquals(openFile, walletRowLabel(" ", openFile)) + } + + @Test + fun a_name_is_not_trimmed_out_of_the_label() { + // Only the *blank* case falls back. A name with padding is still the + // user's name and is shown as stored. + assertEquals(" spending ", walletRowLabel(" spending ", openFile)) + } + + // --- is the child reading a wallet at all -------------------------------- + + @Test + fun only_an_answered_wallet_rpc_counts_as_readable() { + // `connecting` is "the RPC has not answered"; `off` and `exited` are + // "there is no child". None of them can answer a key query. + assertTrue(walletChildReadable("ready")) + assertTrue(walletChildReadable("syncing")) + assertFalse(walletChildReadable("connecting")) + assertFalse(walletChildReadable("off")) + assertFalse(walletChildReadable("exited")) + } + + @Test + fun nothing_read_yet_is_not_readable() { + assertFalse(walletChildReadable(null)) + } + + @Test + fun a_behind_chain_still_counts_as_readable() { + // Syncing means the RPC answered: the wallet's keys do not need the + // chain to be caught up. + assertTrue(walletChildReadable("syncing")) + } + + // --- whether the secret actions are offered ------------------------------ + + @Test + fun the_open_wallets_secrets_are_offered() { + assertTrue(walletSecretsEnabled(openFile, openFile, readable)) + } + + @Test + fun another_wallets_secrets_are_not_offered() { + // The seed and the keys come from the file the child has open. A row + // that is not the open one must not read as its own backup. + assertFalse(walletSecretsEnabled(openFile, otherFile, readable)) + } + + @Test + fun nothing_open_means_no_secrets_for_any_row() { + assertFalse(walletSecretsEnabled(null, openFile, readable)) + } + + @Test + fun the_open_wallet_offers_no_secrets_while_the_child_is_not_reading_it() { + // Active but no answer: `wallet_seed()` / `wallet_keys()` can only + // fail, so the buttons stay dead rather than always erroring. + assertFalse(walletSecretsEnabled(openFile, openFile, notReadable)) + assertFalse(walletSecretsEnabled(openFile, otherFile, notReadable)) + assertFalse(walletSecretsEnabled(null, openFile, notReadable)) + } + + // --- and why they are off, in words -------------------------------------- + + @Test + fun an_enabled_row_has_nothing_to_explain() { + assertNull(walletSecretsBlockedReason(isActive = true, walletReadable = readable)) + } + + @Test + fun a_row_that_is_not_open_says_to_open_it() { + val why = walletSecretsBlockedReason(isActive = false, walletReadable = readable) + assertEquals("open this wallet to view its backup", why) + } + + @Test + fun an_open_wallet_with_no_child_says_the_child_is_not_running() { + val why = walletSecretsBlockedReason(isActive = true, walletReadable = notReadable) + assertTrue(why != null && why.contains("not running")) + // The two reasons are different fixes and must not read alike. + assertFalse(why == walletSecretsBlockedReason(isActive = false, walletReadable = readable)) + } + + // --- the created-at column ---------------------------------------------- + + @Test + fun a_stored_created_at_renders_as_a_date() { + // 2021-01-01T00:00:00Z. + val rendered = walletRowDate(1609459200L) + assertTrue("got '$rendered'", Regex("""\d{4}-\d{2}-\d{2}""").matches(rendered)) + } + + @Test + fun a_later_created_at_sorts_after_an_earlier_one() { + // The store hands the rows back oldest-first; the rendered date must + // not invert that order in the list. + assertTrue(walletRowDate(1700000000L) > walletRowDate(1609459200L)) + } + + @Test + fun a_row_with_no_assigned_created_at_says_so() { + // The store assigns `created_at` on insert, so 0 is a row that predates + // that — not 1970, and not "today". + assertEquals("date unknown", walletRowDate(0L)) + assertEquals("date unknown", walletRowDate(-1L)) + } +} From 775f2e88be31b9991d543016d26a6093e111f5b9 Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 22 Sep 2026 02:12:32 -0400 Subject: [PATCH 15/78] =?UTF-8?q?android:=20profile=20screen=20=E2=80=94?= =?UTF-8?q?=20nickname=20+=20Monero=20receiving=20address?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The phone's half of the TUI's `/profile`. A `Profile` action on the roster's app bar opens `ui/ProfileScreen.kt`: nickname, bio, and the Monero address friends pay to, all three loaded from the store and written back through the core's own validation. - The address is checked with `uniffi.onionwire_sdk.checkAddress` *before* the write, so a typo is refused with the typed text still in the field instead of surfacing as a store error afterwards. An empty address is allowed and is labelled with its consequence: with no profile address and no running wallet child the core has nothing to hand a payer. - The bio is carried, not owned: a save that did not touch the field writes back the value read from the store immediately before the write, so a bio set in the TUI cannot be blanked from the phone. - On save the profile is pushed to **every** friend in the roster, one-shot and fail-closed per friend like the TUI's `save_profile`. A push failure is not a save failure: the status line always starts with `profile saved` and names the count, with each failure listed by petname (else shortened fingerprint). Every decision the screen makes is a pure function in the new file, covered by `ProfileDraftTest` (21 cases) on the JVM: the save-button rule (dead until the read lands, dead while the form is unchanged), the address branch, the bio rule, label selection and the status-line aggregation. Verified on AVD ow35 (x86_64 slice, emulator-5560): the roster app bar carries `Profile`; nickname/bio/address survive `am force-stop` + relaunch; an invalid address is refused before the write; a save with an empty roster reports `profile saved`; with one (self-)peer in the roster a save reports `profile saved · sent to 1 friend`, and with the emulator's network cut the same save reports `profile saved · sent to 0 of 1 friend · failed: