Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
agent
a94f071ccb
docs(tui): add payment history after frames to Deliverable 5
All checks were successful
ci / test (pull_request) Successful in 3m59s
ci / sdk (pull_request) Successful in 1m1s
Render command + 80x24 frames for empty, mixed verified/unverified,
detail view with hostile memo sanitized, and ASCII fallback.

Signed-off-by: tui-design <tui-design@hermes>
2026-09-15 21:39:05 -04:00
agent
7f880ede2c
tui(history): add F6 h needle + PR frame dump for hostile memo
All checks were successful
ci / test (pull_request) Successful in 4m1s
ci / sdk (pull_request) Successful in 58s
- Add 'F6 h' to tests/tui_chrome.rs needle list (help_overlay_text already
  documents the history binding; test must assert it)
- Add dump_history_pr_frames to tests/tui_frames.rs: empty, mixed
  verified/unverified list, detail view, and hostile memo (C0 + bidi) at
  80x24 and 120x40

Signed-off-by: tui-design <tui-design@hermes>
2026-09-15 21:37:30 -04:00
agent
b7e3d79777
tui(history): payment history and tx detail screen (card t_935bf84e)
All checks were successful
ci / test (pull_request) Successful in 4m30s
ci / sdk (pull_request) Successful in 1m19s
Add Screen::History with draw_history, history_row_text, history_detail.
- Per-friend payment list: direction marker, amount, verified state, age, txid
- Enter opens detail view; Esc closes
- h key from main + wallet opens history via Node::list_payments
- Empty state: 'no payments with this friend yet'
- ASCII fallback: drops ✓/✗ glyphs, uses words only
- Peer text (memo, address) sanitized via display_text
- Tests: 5 new in tui_spec.rs (row text, detail, empty, ascii), 2 frame dumps in tui_frames.rs

Signed-off-by: tui-design <tui-design@hermes>
2026-09-15 21:29:40 -04:00
agent
eb7e55b65d
fast-forward to latest base 2026-09-15 20:57:11 -04:00
87d4a54c32 Merge pull request 'tui(wallet): chain/daemon honesty, view-only badge, address copy (OSC 52)' (#81) from wt/t_ed79636f into feat/wallet-create-import
Reviewed-on: #81
2026-09-16 00:40:01 +00:00
agent
b9f84e6f4b
fix(tui): replace emoji wallet badges with ASCII glyphs + word
All checks were successful
ci / test (pull_request) Successful in 4m3s
ci / sdk (pull_request) Successful in 59s
- Badge now '[!] view-only — /tip off' / '[ok] spend enabled'
  (never emoji, never colour-only; word carries meaning under NO_COLOR)
- Update test: assert 'view-only' word + ASCII '[!]' glyph present
- Add wallet frame dumps to dump_audit_frames: receive-only,
  local synced, local syncing, remote unreachable, view-only badge,
  QR modal — at 80x24 and 120x40
- Add wallet_screen_no_line_exceeds_frame_at_80_and_120: asserts
  every rendered line stays within frame width (chars_count metric)
- Add wallet_view_only_badge_renders_at_80_and_120: badge present
  and within width at both sizes

Tests: 21 tui_frames, 19 tui_chrome, 23 tui_spec all green
Clippy: clean --locked --all-targets -- -D warnings
2026-09-15 20:04:28 -04:00
agent
310671785b
tui(wallet): chain/daemon honesty, view-only badge, address copy (OSC 52)
All checks were successful
ci / test (pull_request) Successful in 4m34s
ci / sdk (pull_request) Successful in 1m20s
- Screen::Wallet.view wrapped in Box<WalletView> to avoid large_enum_variant
- draw_wallet restructured to Deliverable 5 pane layout: primary, chain,
  history, action row, footer
- View-only wallet shows 'view-only' badge with spend status word
- ChainSource variants render their specific copy (Local/Remote/None)
- DaemonSync.reachable=false renders 'sync: unknown' with no balance claim
- Address copy via OSC 52 escape sequence; 'y' key; fallback hint on screen
- QR modal resized to fit 80x24 without clipping
- wallet_screen_at_with() test helper for copy_note parameter
- 33 new tests covering receive-only, local synced/syncing, remote
  unreachable, view-only badge, QR modal, address copy escape sequence

All 52 TUI tests pass (10 tui_frames + 19 tui_chrome + 23 tui_spec).
Clippy clean on lib and all three test targets.
2026-09-15 19:57:29 -04:00
6ffc475a3f Merge pull request 'docs(tui): add Deliverables 5 (wallet surfaces), 6 (identity v2), and before frames' (#79) from wt/t_c955b280 into feat/wallet-create-import
Reviewed-on: #79
2026-09-15 20:24:28 +00:00
agent
86d4c7997b
docs(tui): add Deliverables 5 (wallet surfaces), 6 (identity v2), and before frames 2026-09-15 16:15:45 -04:00
b20313e65d Merge pull request 'node: read-only Node::list_payments(friend_pk) for the TUI payment history' (#78) from wt/t_6fb6d365 into feat/wallet-create-import
Reviewed-on: #78
2026-09-15 19:27:22 +00:00
rust-dev
fe6465aa6b
node: read-only Node::list_payments(friend_pk) for the TUI payment history
All checks were successful
ci / test (pull_request) Successful in 4m29s
ci / sdk (pull_request) Successful in 1m19s
Re-exposes the existing Store::list_payments as one typed read method so
src/tui.rs can render a friend's payment history without ever touching the
store. Maps the store error to Result<_, String> exactly like the
neighbouring list_messages / wallet_recent_transfers, and returns
store::Payment as-is (id, dir, kind, amount_atomic, address, memo, txid,
verified, created_at).

Read-only: no schema change, no migration, no new frame, no new column, no
docs/PROTOCOL.md change, and no store handle becomes reachable from the TUI.
An unknown friend is empty history (Ok(vec![])), not an error.

Test placement deviates from the card, deliberately: it lives in
src/node.rs's #[cfg(test)] mod tests instead of tests/pay.rs, because Node
has no constructor that avoids Tor (Node::start* is the only public one) and
ingest_receipt is private, so tests/pay.rs cannot build a Node at all. The
test uses an unbootstrapped Arti client plus a null deliverer over a real
encrypted store in a temp dir, writes the outbound row directly and drives
the inbound row through the node's own ingest_receipt.
2026-09-15 15:10:38 -04:00
f678412c68 Merge pull request 'TUI: node control, chain-source picker, honest wallet sync readiness' (#76) from wt/t_09f67bf8 into feat/wallet-create-import
Reviewed-on: #76
2026-09-15 17:01:46 +00:00
agent
cfdfe38536
TUI: node control, chain-source picker, honest wallet sync readiness
All checks were successful
ci / test (pull_request) Successful in 4m28s
ci / sdk (pull_request) Successful in 1m19s
Add the TUI control plane for the wallet child and chain source,
stacked on the wallet-child-lifecycle card:

- Chain-source picker (s): receive-only / local monerod / remote daemon
  with daemon-address entry + trust-shift warning for clearnet hosts
- Node control (n): start/stop the app-owned monero-wallet-rpc child,
  with fail-closed onion+SOCKS guard in the status line
- Wallet screen refreshes after picker/child changes, shows sync progress
  from the daemon and the chain-source/free-space/storage status line
- Honest spend guard: wallet view reflects real WalletStatus + Readiness
  so balance/transfer rendering only claims authority when the daemon is
  reachable, never while the child is silent
- Help overlay + footer hints updated for the new 's'/'n' keys
- Tests: chain-source round-trip through sealed record, saved-source
  starts the child, parse_source handles the 'none' kind
2026-09-15 12:29:16 -04:00
ee5b25488b Merge pull request 'wallet: stored config (F7) + WalletStatus snapshot + pay/tip readiness guard' (#75) from feat/wallet-config-persistence into feat/wallet-create-import
Reviewed-on: #75
2026-09-15 03:49:06 +00:00
rust-dev
d7e91f850a
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
All checks were successful
ci / test (pull_request) Successful in 4m22s
ci / sdk (pull_request) Successful in 1m15s
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:

- `wallet_config` table in the encrypted store (one row; the login is sealed
  with the store data key under `onionwire/wallet-config/v1`, on top of
  SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
  `save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
  redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
  prefers stored config, falls back to env, and refuses to dial a bad stored
  endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
  receive_address }`: `connected` only ever comes from a probe
  (`Wallet::status`, get_address + get_balance); config alone leaves it false.
  `Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
  probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
  error }` for the Test-connection button: same loopback/digest rules, errors
  redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
  `Node::wallet_readiness` (async, block_on-friendly): not configured →
  NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
  dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
  live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
  wallet can be re-pointed mid-session.

Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.

Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
7cd316b65f Merge pull request 'wallet: app-owned child lifecycle + user-chosen ChainSource' (#73) from wt/t_69ce8e46 into feat/wallet-create-import
Reviewed-on: #73
2026-09-15 00:24:31 +00:00
3f62734efd Merge branch 'feat/wallet-create-import' into wt/t_69ce8e46
All checks were successful
ci / test (pull_request) Successful in 3m56s
ci / sdk (pull_request) Successful in 57s
2026-09-15 00:06:12 +00:00
agent
8331a2dde6
wallet: app-owned child lifecycle + user-chosen ChainSource
All checks were successful
ci / test (pull_request) Successful in 4m1s
ci / sdk (pull_request) Successful in 1m2s
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.

- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
  port }. No default remote node; Remote is only constructed from explicit
  user input. A .onion Remote is refused without a SOCKS proxy (separate
  card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
  --rpc-bind-ip 127.0.0.1, a random free loopback port, generated
  --rpc-login, and --wallet-dir /wallet; monerod too for a
  local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
  (wallet_child table, AEAD on top of whole-db encryption), never a
  plaintext file. The Wallet client is built from the generated loopback
  URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
  height>=target_height; can_spend() and can_verify_receipts() gate on it.
  Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
  calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
  because a first sync or a remote daemon outlasts 5s and a 5s cap there
  is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
  configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.

Base: feat/wallet-create-import (PR #66). Do not rebase onto main.

Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 19:57:21 -04:00
agent
2ab4b69574
fix(ci): resolve conflict markers left in scripts/publish-release.sh 2026-09-14 16:57:19 -04:00
13 changed files with 5447 additions and 217 deletions

View file

@ -621,3 +621,452 @@ lands on the row that actually owns the outbox entry.
and footer row is `<=` the terminal width, that the markers render, and that
an over-long message wraps instead of being clipped.
- Dump frames: `cargo test --locked --test tui_spec -- --nocapture dump_spec_frames`.
---
## Deliverable 5 — wallet surfaces (copy + pane structure)
Presentation-only. The base branch already owns the API on the table in plan §1.3. This deliverable names the pane on each wallet-family screen, the primary element, and the exact copy for every non-happy state. The copy table is binding: a later card must render these strings (or their ASCII/word variants), not invent new refusal text.
### Wallet screen (`Screen::Wallet`, `draw_wallet` — `src/tui.rs:3072`)
Layout: vertical 2-line title, a bordered body that fills the middle, 1-line action footer.
```
┌wallet────────────────────────┐
└──────────────────────────────┘
┌──────────────────────────────┐
│address 4AdY… │
│balance not synced — unavailable│
│ │
│chain │
│chain: local monerod … │
│daemon: stopped … │
│sync: unknown — … │
│storage: 412 GB free … │
│not ready: wallet RPC … │
│pruned nodes … │
│ │
│recent transfers │
│ (none shown) │
│ │
│ │
│ │
│ │
└──────────────────────────────┘
s chain n start/stop c create i import r qr
```
Primary: address + balance + chain block. Largest element on screen.
**Copy table** — every state the wallet screen can show (sources verified at base commit `b20313e`):
| State | On-screen copy | Source |
|---|---|---|
| Receive-only / no wallet | address: `no address yet — /profile xmr, or create a wallet`; balance: `not synced — unavailable` | `draw_wallet` empty branch; `wallet_view` not-ready branch |
| Receive-only configured (no daemon) | chain: `chain: receive-only — no daemon, no chain traffic`; daemon: `daemon: not configured — press s to choose a chain source`; readiness: `not ready: no wallet — receive-only until c create / i import` | `chain_view` `ChainSource::None` + `WalletChildState::Off` |
| Local monerod chosen, stopped | `chain: local monerod ({bin}) — chain in {dir}`; `daemon: stopped — press n to start it` | `ChainSource::Local` + `WalletChildState::Stopped` |
| Local monerod running | `daemon: running (child owned by this app)` | `WalletChildState::Running` |
| Remote daemon | `chain: remote daemon {host}:{port}` | `ChainSource::Remote` |
| Daemon unreachable | `sync: unknown — {note}` | `DaemonSync.reachable == false` |
| Daemon reachable, syncing | `sync: syncing — {h}/{target}` | `DaemonSync` height/target |
| Daemon synced | `sync: synced — height {h}` | `DaemonSync.synced()` |
| Sync unknown (never probed) | balance: `not synced — unavailable` (never the real balance) | `wallet_view` `!chain.ready` |
| Balance ready | the real balance line (e.g. `12.5 XMR`) | `wallet_view` `chain.ready` |
| No transfers | ` (none shown)` | `draw_wallet` empty transfers branch |
| View-only | spend badge: `view-only — /tip off` (word + glyph, never color-only) | `WalletConfig.no_spend` / `VIEW_ONLY_MSG` |
| Not configured (wallet screen) | readiness: `not ready: no wallet — receive-only until c create / i import` | `WalletReadiness::NotConfigured.line()` |
| Configured, RPC down | readiness: `not ready: wallet RPC not answering — balance is not authoritative` | `WalletReadiness::NotConnected.line()` |
| Ready | readiness: `ready: wallet synced — spend and receipt verification available` | `WalletReadiness::Ready.line()` |
| `/tip` on view-only | status_note exactly: `wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work` | `wallet::VIEW_ONLY_MSG` |
| `/tip` or `/pay`, not configured | status_note exactly: `wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC` | `wallet::NOT_CONFIGURED_MSG` |
| `/tip` or `/pay`, not connected | status_note exactly: `wallet not connected — check endpoint, login, daemon` | `wallet::NOT_CONNECTED_MSG` |
| Friend has no address (`/tip`) | status_note exactly: `friend has no Monero address — they must /profile` | existing `tip` refusal (src/tui.rs:1738) |
| Address empty (both profile + RPC empty) | status_note: `no receive address — set profile xmr or ONIONWIRE_WALLET RPC` | existing `wallet_receive_address` guard |
Action row (`src/tui.rs:3164`): `s chain n start/stop c create i import r qr`
### Chain setup screen (`Screen::ChainSetup`, `draw_chain_setup` — `src/tui.rs:3170`)
Overlay via `draw_text_overlay`. Three modes:
| Mode | Title | Body | Hint |
|---|---|---|---|
| `Choose` | `chain source` | `where should the chain come from?` + 3 choices (Receive-only / Local monerod / Remote daemon) with detail lines + `receive-only needs no wallet file…` + `Up/Down choose Enter select Esc back` | `ChainChoice::ALL` order; never preselects Remote |
| `RemoteAddr` | `enter daemon address` | `daemon address, as host:port` + `e.g. 127.0.0.1:18081 or yournode.onion:18089` + `> {buf}` + error line or `Enter continues Esc goes back` | parses via `parse_daemon_addr` |
| `RemoteWarn` | `trust shift` | `use {host}:{port} for chain traffic?` + `the daemon operator sees your addresses during sync,` + `and every spend. a remote daemon is untrusted:` + `this app never passes --trusted-daemon.` + `.onion` branch: `this is a .onion host, so Tor would hide the transport.` + `it still does not hide your addresses from the operator.` + `ONION_NO_SOCKS_MSG` | `Enter saves it Esc cancels` |
### Wallet setup screen (`draw_wallet_setup` — `src/tui.rs:3235`)
Five overlays, all via `draw_text_overlay`. The spend-authority warning is `wallet::SPEND_AUTHORITY_WARNING` (exact, `src/wallet.rs:308`).
| Screen | Title | Body | Exit |
|---|---|---|---|
| `CreateWarn` | `create spend wallet` | `SPEND_AUTHORITY_WARNING` + blank + `Type SPEND to confirm Esc to cancel` + `{typed}` | type SPEND / Esc |
| `CreatePass` (1st) | `wallet passphrase` | `set a passphrase for the wallet file` + `Enter continues Esc cancels` | Enter / Esc |
| `CreatePass` (2nd) | `wallet passphrase` | `re-type passphrase` + `Enter submits Esc cancels` | Enter / Esc |
| `CreatePass` mismatch | — | alert: `passphrases do not match` | alert_line |
| `CreateSeed` | `write down this seed` | `{seed}` + blank + `this is shown once. anyone with it can spend.` + `Type SEEN when you have written it down` + `{typed}` | type SEEN / Esc (zeroizes seed on Esc) |
| `ImportSeed` | `import wallet` | `paste the 25-word seed. this is the only path that takes an existing key.` + blank + `{buf}` + blank + `Enter continues Esc cancels` | Enter / Esc |
| `ImportSeed` empty | — | alert: `seed required to import a wallet` | error |
| `ImportPass` (1st) | `wallet passphrase` | `passphrase for the imported wallet file` + `Enter continues Esc cancels` | Enter / Esc |
| `ImportPass` (2nd) | `wallet passphrase` | `re-type passphrase` + `Enter submits Esc cancels` | Enter / Esc |
| `ImportPass` mismatch | — | alert: `passphrases do not match` | alert_line |
| RPC failure | — | alert: the RPC error exactly as returned | error |
### New send/tip flow (`Screen::Send` — **new screen, spec only**)
No screen exists yet in `src/tui.rs`. Primary: recipient + amount field + memo field + resolved atomic value + confirm action. Opens from the wallet screen and from main with a friend selected.
| State | Copy | Source |
|---|---|---|
| No friend selected / empty recipient | action row disabled: `recipient required` | spec |
| Amount unparsed (junk / negative / >8 dp) | field error: `amount: {parse_atomic error}` | `pay::parse_atomic` |
| Amount 0 | field error: `amount must be > 0`; confirm disabled | `pay::parse_atomic` rejection |
| View-only / no-spend refusal | confirm disabled; line exactly: `wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work` | `VIEW_ONLY_MSG` |
| Not configured refusal | confirm disabled; line exactly: `wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC` | `NOT_CONFIGURED_MSG` |
| Friend has no address | line exactly: `friend has no Monero address — they must /profile` | existing `tip` guard |
| Amount too large for RPC | line: the overflow error from `pay::xmr_to_atomic` | `pay::xmr_to_atomic` |
| Address fails checksum | the address-check error verbatim | `pay::check_address` |
| Sending | status_note: `sending` | existing flow |
| Sent | status_note: `tip sent` (tip) / `invoice sent` (pay) | existing |
| Send failed | status_note: `send failed: {short}` (`! ` when colour off) | `short_send_reason` |
| Esc | no side effect; return to wallet screen | spec |
Spend badge visible on this screen (a view-only wallet cannot reach confirm). Same badge as the wallet screen: `view-only — /tip off`.
### New payment history (`Screen::History` — **new screen; API gap**)
`Node::list_payments(friend_pk)` exists at `src/node.rs:520` and returns `Vec<Payment>`. The `Payment` struct (`src/store.rs:94`):
```
pub struct Payment {
pub id: i64, // store row id
pub dir: String, // "in" | "out"
pub kind: String, // "tip" | "invoice" | "payment"
pub amount_atomic: String,
pub address: String,
pub memo: String,
pub txid: Option<String>,
pub verified: bool,
pub created_at: i64, // unix secs
}
```
Row copy (derived from `Payment`):
| State | Copy | Source |
|---|---|---|
| Empty history | `no payments with this friend yet` | spec (designed, never blank) |
| Outbound, verified | `> {amount} XMR ✓ verified {age}` | `pay::atomic_to_xmr_str` + `Payment.verified` |
| Outbound, unverified | `> {amount} XMR unverified {age}` | word + glyph, never color-only |
| Inbound | `< {amount} XMR {verified/unverified} {age}` | `dir == "in"` |
| No txid | line: `awaiting receipt` | `Payment.txid == None` |
| Long memo | wrap or truncate with `…`/`...` after `sanitize::display_text` | sanitize first |
| Hostile memo (control chars + bidi) | sanitized before draw | `sanitize::display_text` |
| Detail view — txid absent | `txid: awaiting receipt` | `Payment.txid == None` |
Amount is displayed via `pay::atomic_to_xmr_str(&t.amount_atomic)` (`src/pay.rs:144`) — never raw piconero.
### New F7 wallet-config screen (`Screen::WalletConfig` — **spec only**)
The base branch owns `WalletConfig` (`src/wallet.rs:57`), `Node::wallet_status()` → `WalletStatus`, `Node::wallet_config()`, `Node::wallet_save_config()`, `Node::wallet_test_connection() -> PingResult` (`src/node.rs:520+`). There is **no** `Screen::WalletConfig` or `draw_wallet_config` in `src/tui.rs` — confirmed by grep. This is the screen to build.
Layout: title `wallet config`, two-column field list, `Test connection` + `Save` at the bottom.
| State | Copy | Source |
|---|---|---|
| Not configured | `wallet not configured — set rpc_url` | spec |
| rpc_url empty, Test pressed | `rpc_url required` | `WalletConfig::from_config` error |
| rpc_login masked (default) | `rpc_login: •••••••` | `WalletConfig::secret()` redaction |
| rpc_login revealed | `rpc_login: {user}:{mask}` | reveal toggle; real password never printed |
| Test connecting | `testing connection …` (no spinner) | `PingResult` in flight |
| Test OK | `connected — {PingResult::line()}` | `PingResult::line()` |
| Test failed | `error: {short}` (sanitized, never the login) | `Wallet::sanitize` / `redact` |
| Save success, not connected | `saved · not connected` | spec |
| Save success, connected | `connected · {PingResult::line()}` | spec |
| Save failure | `error: {short}` | sanitized |
| no_spend off | `spend on — /tip enabled` | word + glyph |
| no_spend on | `view-only — /tip off` | word + glyph |
Masking rule: `WalletConfig::secret()` (`src/wallet.rs:79`) exists for redaction. The fixture password must not appear in any rendered frame, status note, alert, or help string. The toggle is distinguishable in `NO_COLOR` by the word `•••••••` vs the user, not by color alone.
### Copy rules for every wallet surface
1. Refusal text is the existing string from `wallet.rs` / `Node` — never invent a softer version.
2. Spend badge is always word + glyph (`view-only — /tip off`; `spend on`). Never color-only.
3. Addresses from a friend's profile are peer-supplied — pass through `sanitize::display_text` before draw.
4. Memos are peer-supplied — sanitize first, then wrap/truncate with ellipsis.
5. Empty states are designed copy, not blank panes.
6. Fail-closed status notes (`send failed`, `fingerprint mismatch`, view-only refusal) keep the `! ` prefix when colour is off (`src/tui.rs:64`).
---
## Deliverable 6 — visual identity v2
This replaces palette values, glyph fallbacks, spacing, and focus rules. It does **not** add hues. The locked helper names and strings in `tests/tui_chrome.rs` survive.
### Color palette
The palette lives as RGB constants in `src/tui.rs:21-27`, each with an ANSI16 fallback via `style_fg()` / `style_accent()` / `style_highlight()`. `NO_COLOR` (`ColorMode::None`) drops fg entirely and uses bold/reverse for accent/highlight.
| Role | RGB (current) | ANSI16 fallback | `NO_COLOR` treatment | Where |
|---|---|---|---|---|
| accent | `Rgb(232, 165, 75)` | `Yellow` | bold | titles, focus marks, QR border |
| text | `Rgb(196, 214, 176)` | `White` | plain | body copy, chat, address/balance |
| dim | `Rgb(98, 110, 92)` | `DarkGray` | plain | action row, hints, help |
| alert | `Rgb(220, 80, 70)` | `Red` | `! ` prefix | fail-closed, view-only refusal |
| stale | `Rgb(210, 180, 80)` | `Yellow` | plain + `stale` text | stale roster suffix |
| highlight bg | `Rgb(48, 42, 28)` | `Reverse` | reverse | focused roster row |
| border | `Rgb(72, 84, 64)` | `DarkGray` | plain | pane borders |
`style_highlight()` (`src/tui.rs:379`) uses bold + reverse for NO_COLOR. `style_accent()` (`src/tui.rs:351`) uses bold for NO_COLOR. `style_fg()` (`src/tui.rs:343`) drops fg entirely for NO_COLOR.
**No change to these six values on this card.** Deliverable 6 is the *specification* of how they apply to the wallet surfaces — not a recolor.
### Glyph set (use → unicode → ASCII fallback)
| Glyph | Unicode | ASCII | Cell width (unicode) | Where |
|---|---|---|---|---|
| onion / share | `(o)` | `(o)` | 3 | title (locked) |
| focus | `> ` | `> ` | 2 | focused pane title / roster |
| truncate | `…` | `...` | 1 | `truncate_chars` tail |
| box (border) | `─ │ ┌ ┐ └ ┘` | `+ - |` | 1 each | ratatui `Block::borders` |
| alert prefix | `! ` | `! ` | 2 | fail-closed (`src/tui.rs:64`) |
| stale | word `stale` | `stale` | 5 | roster suffix |
| delivered | `✓` | `ok` | 1 | delivery marker |
| queued | `◷` | `queued` (word) | 1 | delivery marker |
| sending | `»` | `sending` (word) | 1 | delivery marker |
| failed | `✗` | `failed` (word) | 1 | delivery marker |
| bullet (masked) | `•` | `·` | 1 | password mask |
Glyphs are never color-only. ASCII mode (triggered by `ONIONWIRE_ASCII=1` or `NO_COLOR=1`) swaps all unicode glyphs per the table. `delivery_glyph()` (`src/tui.rs:138`) and `tests/tui_spec.rs::delivery_markers_have_exercised_ascii_fallbacks` exercise the fallback.
### Spacing unit
**1 cell.** All internal padding is a single space after the label: `address {value}`, `balance {value}`, `chain: {detail}`. A single blank `String::new()` row separates blocks. Pane borders add no inner pad on the title line.
### Focus rules per pane
- Main: roster > chat > composer. Focused title gets `> ` prefix + bold; unfocused gets ` `.
- Wallet: body block (address/balance/chain/transfers) is primary; action row is dim, never bold. No in-body focus — keys drive navigation.
- Overlays (chain setup, wallet setup, send, history, F7): full-screen, Escape returns. The active field gets `> ` prefix.
- Focus is never color-only. `NO_COLOR` keeps bold/reverse and the `> `/` ` prefix.
### Pane structure per wallet-family screen
| Screen | Panes (top → bottom) |
|---|---|
| Wallet (`draw_wallet`) | title `wallet` (2 rows) / body border (fill) / action row (1 row) |
| `draw_wallet` body | address line / balance line / blank / `chain` header / 5 chain lines / PRUNED_NOTE wrapping / blank / `recent transfers` / transfer rows or `(none shown)` / remaining blank |
| Chain setup (`draw_chain_setup`) | single overlay, full-screen |
| Wallet setup (`draw_wallet_setup`) | single overlay, full-screen |
| Send flow | **to spec** — single overlay, full-screen |
| Payment history | **to spec** — single overlay, full-screen |
| F7 config | **to spec** — single overlay, full-screen |
`WALLET_LINE_MAX` = 76 (`src/tui.rs:1169`). Every chain line is `truncate_chars(&line, WALLET_LINE_MAX)` (`src/tui.rs:1373`).
---
## Before frames (identity v1)
Real `draw_wallet` frames from the base branch at `b20313e`, rendered via `TestBackend` at 80x24. The dump test (`tests/tui_wallet_dump.rs`) was a throwaway — removed after capture, touches no `src/`. Trailing spaces omitted.
### Wallet screen — not-ready / daemon stopped (80x24)
```
┌wallet────────────────────────────────────────────────────────────────────────┐
└──────────────────────────────────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────────────────────────────────┐
│address 4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gD │
│balance not synced — unavailable │
│ │
│chain │
│chain: local monerod (monerod) — chain in /home/user/.onionwire/chain │
│daemon: stopped — press n to start it │
│sync: unknown — 127.0.0.1:18081: Connection refused (os error 111) │
│storage: 412 GB free here — pruned mainnet wants ~50-60 GB, a full node ~20… │
│not ready: wallet RPC not answering — balance is not authoritative │
│pruned nodes are not archives: a deep seed restore can degrade. once this │
│wallet has scanned, its own cache is the history │
│ │
│recent transfers │
│ (none shown) │
│ │
│ │
│ │
│ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘
s chain n start/stop c create i import r qr
```
### Wallet screen — receive-only (80x24)
```
┌wallet────────────────────────────────────────────────────────────────────────┐
└──────────────────────────────────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────────────────────────────────┐
│address no address yet — /profile xmr, or create a wallet │
│balance not synced — unavailable │
│ │
│chain │
│chain: receive-only — no daemon, no chain traffic │
│daemon: not configured — press s to choose a chain source │
│sync: unknown — receive-only: no daemon │
│storage: nothing stored on this device │
│not ready: no wallet — receive-only until c create / i import │
│pruned nodes are not archives: a deep seed restore can degrade. once this │
│wallet has scanned, its own cache is the history │
│ │
│recent transfers │
│ (none shown) │
│ │
│ │
│ │
│ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘
s chain n start/stop c create i import r qr
```
### Wallet screen — ready / synced (80x24)
```
┌wallet────────────────────────────────────────────────────────────────────────┐
└──────────────────────────────────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────────────────────────────────┐
│address 4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gD │
│balance 12.5 XMR │
│ │
│chain │
│chain: local monerod (monerod) — chain in /home/user/.onionwire/chain │
│daemon: running (child owned by this app) │
│sync: synced — height 3210000 │
│storage: 412 GB free here — pruned mainnet wants ~50-60 GB, a full node ~20… │
│ready: wallet synced — spend and receipt verification available │
│pruned nodes are not archives: a deep seed restore can degrade. once this │
│wallet has scanned, its own cache is the history │
│ │
│recent transfers │
│ (none shown) │
│ │
│ │
│ │
│ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘
s chain n start/stop c create i import r qr
```
### Wallet screen — ready / synced (120x40)
Wider: the truncated storage line reads in full — `…a full node ~200 GB` — and the body block has 27 rows of empty space.
```
┌wallet────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│address 4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gD │
│balance 12.5 XMR │
│ │
│chain │
│chain: local monerod (monerod) — chain in /home/user/.onionwire/chain │
│daemon: running (child owned by this app) │
│sync: synced — height 3210000 │
│storage: 412 GB free here — pruned mainnet wants ~50-60 GB, a full node ~200 GB │
│ready: wallet synced — spend and receipt verification available │
│pruned nodes are not archives: a deep seed restore can degrade. once this wallet has scanned, its own cache is the │
│history │
│ │
│recent transfers │
│ (none shown) │
│ │
│ │
│ │
│ │
│ │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
s chain n start/stop c create i import r qr
```
---
## Evidence
- `TMPDIR=/var/tmp/onionwire-tui-tmp` set for all compile steps (§1.5 disk-quota trap on `/tmp`).
- `cargo test --locked --test tui_frames -- --nocapture dump_audit_frames` — ok.
- `cargo test --locked --test tui_spec -- --nocapture dump_spec_frames` — ok.
- Wallet screen assertion tests: `wallet_screen_says_not_ready_and_never_a_balance_before_sync`, `wallet_screen_says_receive_only_when_nothing_is_configured`, `wallet_screen_keeps_the_balance_when_the_wallet_is_ready`, `a_view_only_wallet_says_so_instead_of_offering_a_spend` — all green.
- `ChainChoice::ALL.len() == 3` (three choices, never a public node) — asserted.
- `status_footer` keeps `send failed`, `TOR`, `me:`, `? help` at 80 and 120 — asserted by `status_footer_drops_send_failed_when_crowded`.
- `chars().count() <= width` on all locked public copy — asserted by `public_copy_fits_80_by_chars_count`.
## Deliverable 5 addendum — payment history frames (after)
Render with `cargo test --locked --test tui_frames -- --nocapture dump_history_pr_frames`.
### 80x24 — empty history
```
┌history bob──────────────────────────────────────────────────────────────────┐
│no payments with this friend yet │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘
Enter detail Esc back ? help ```
### 80x24 — mixed verified/unverified list
```
┌history alice────────────────────────────────────────────────────────────────┐
│> 0.001 XMR ✓ verified abcdef012345678… 21m │
│< 0.05 XMR ✓ verified deadbeefdeadbee… 3m │
│> 0.0005 XMR ✗ unverified awaiting receipt 1m │
└──────────────────────────────────────────────────────────────────────────────┘
Enter detail Esc back ? help ```
### 80x24 — detail view (hostile memo sanitized)
The memo was `pay\x01now\u{202E}reverse` (C0 control + bidi override).
After `sanitize::display_text` it renders as inert `paynowreverse`:
```
┌history alice detail────────────────────────────────────────────────────────┐
│txid awaiting receipt │
│address (none) │
│memo paynowreverse │
│amount 0.0005 XMR │
│kind invoice │
│direction outbound │
│verified unverified │
│timestamp 1700000200 (1m ago) │
└──────────────────────────────────────────────────────────────────────────────┘
Esc back ? help ```
### 80x24 — ASCII fallback
```
+history alice----------------------------------------------------------------+
|> 0.001 XMR verified abcdef0123456... 21m |
+------------------------------------------------------------------------------+
Enter detail Esc back ? help ```

View file

@ -10,8 +10,8 @@ receipt checks (`get_transfers`). `/tip` is off.
OnionWire a local spend authority for that wallet file — see the spend-authority
warning below. The threat-model write-up is [THREAT_MODEL.md](THREAT_MODEL.md).
The app talks to `monero-wallet-rpc` over loopback HTTP Digest only, whether
that process is one you already run or one the app spawns:
The app talks to `monero-wallet-rpc` over loopback HTTP Digest only, and it can
own that process itself:
- hand out a receive subaddress for `/pay` invoices (`create_address`),
- read incoming transfers to verify a peer's receipt (`get_transfers`),
@ -20,16 +20,178 @@ that process is one you already run or one the app spawns:
**Prefer view-only until you actually want `/tip`.** Everything else in this
document explains why, and what breaks when you do.
## The app-owned wallet child
`src/wallet_child.rs` owns the child pair instead of asking you to start it and
export an env var:
- **`monero-wallet-rpc`** is spawned with `--rpc-bind-ip 127.0.0.1`, a **random
free loopback port** (bind `127.0.0.1:0`, read the port, drop the listener, pass
it on — two instances on one box cannot collide), a generated `--rpc-login`
(`user:pass`, random `[a-z0-9]`, no shell or HTTP metacharacters), and
`--wallet-dir $ONIONWIRE_HOME/wallet`.
- **`monerod`** is spawned too when the chain source is *local*:
`--non-interactive --data-dir <datadir> --rpc-bind-ip 127.0.0.1 --rpc-bind-port
18081`. One box, one daemon: the wallet child dials it at `127.0.0.1:18081`.
- `--trusted-daemon` is never passed. A remote daemon stays untrusted.
- The wallet dir is created `0700` and the wallet file is kept `0600` — it is a
spend authority.
- The child is watched by polling (`try_wait`); an exit is reported rather than
hidden, and `stop()` kills both children on shutdown. The next launch starts
them again. Nothing promises "always running", and Android will not.
### Where the RPC credentials live
The generated `user:pass` is **sealed with the store data key and kept in the
encrypted SQLCipher store** (`wallet_child` table, AEAD with the store key on top
of whole-db encryption). It is never written to a plaintext file next to the
wallet, and it never appears in `ONIONWIRE_WALLET_RPC`. They persist across
launches, so the child restarts with the same login without asking you again.
The wallet passphrase is a separate thing: the child prompts/needs it for
`create_wallet` / `restore_deterministic_wallet`, and that is your runtime choice,
not something the app stores for you.
## Chain source
The wallet needs a daemon for scan, verify, and spend. You pick one; OnionWire
does not pick a public remote node for you. The three shapes are:
```
ChainSource::None receive-only; no child, no daemon
ChainSource::Local { monerod_bin, datadir } the app spawns monerod on this box
ChainSource::Remote { host, port } a daemon address you typed
```
1. **Local `monerod`.** Chain traffic stays on the box. You accept disk, first
sync, and (on Android) the daemon not always running.
2. **A daemon address you supply** — becomes `--daemon-address` on the wallet
child. Loopback if you already run `monerod`. `.onion` if you want chain
traffic over Tor — that needs a SOCKS proxy for the wallet child and is **not
implemented here**: configuring a `.onion` host today fails with a clear error
instead of silently dialling clearnet. Clearnet only if you type it — your ISP
sees Monero-node traffic; it is never a default.
The port is a convention, not a constant: restricted RPC on `18089` is common,
but you supply it.
### Readiness, and why it is not a guess
`chain_ready()` asks the wallet RPC `get_info` and requires **`synchronized ==
true`** with `height > 0` and `height >= target_height`. A missing field is
*not ready* — fail closed, never a silent pass. Until then:
- **receipt verification stays `verified=0`** (an unsynced wallet cannot see the
tx, so a `get_transfers` miss would be a lie), and
- **spend is refused** with `wallet is not synced — spend refused until the
daemon reaches the chain tip`.
`spend_ready()` is the stricter signal the spend UI reads: chain-ready *and*
holding an unlocked balance above zero.
That is the honest state, not a broken flow. Unsynced or unreachable → receipts
unverified and spend refused.
### Timeouts are the backend's, not a constant
Loopback management calls (`get_address`, `query_key`, create/import) get a 5s
budget — the child is on the same box. Calls that wait on the chain (`get_info`,
`get_transfers`, `transfer`) get 60s (`CHAIN_RPC_TIMEOUT`), because a first sync
or a remote daemon legitimately outlasts a loopback round trip; a 5s cap there is
what leaves receipts permanently unverified.
## Env vars
| Variable | Meaning |
|---|---|
| `ONIONWIRE_WALLET_RPC` | `http://[user:pass@]host[:port][/path]`. Unset → no wallet; chat still works and `/pay` falls back to the profile `xmr_addr`. |
| `ONIONWIRE_WALLET_RPC` | `http://[user:pass@]host[:port][/path]` — for an **externally run** `monero-wallet-rpc`. Unset → no wallet; chat still works and `/pay` falls back to the profile `xmr_addr`. The app-owned wallet child does not use this variable. |
| `ONIONWIRE_WALLET_RPC_LOGIN` | `user:pass` when you do not want the password in the URL. Ignored if the URL carries userinfo. |
| `ONIONWIRE_WALLET_NO_SPEND` | `1` / `true` / `yes` / `on` → view-only deployment: `/tip` is refused locally, before any RPC dial. `/pay` and receipt verification keep working. |
As of v0.2.2 these three are the **migration path**, not the only path: the
stored config set in **F7** wins at boot. See *Stored wallet config* below.
`README.md` carries the operator summary; this file is the long form.
## Stored wallet config (no env required)
Editing env vars is a deployment step, not a UI step. The TUI's **F7** screen
sets the same three fields and stores them, so a desktop install never needs env
at all:
| Field | Meaning |
|---|---|
| `rpc_url` | `http://host:port[/path]` for an **externally run** `monero-wallet-rpc`. **No** `user:pass` in the URL. Loopback only, same rule as env. |
| `rpc_login` | `user:pass`. Masked in the UI. Never logged, never in a status line, never on disk in the clear. |
| `no_spend` | View-only deployment. Same semantics as `ONIONWIRE_WALLET_NO_SPEND`. |
They live in the **encrypted SQLCipher store** (`wallet_config` table, one row:
the URL and the flag in the clear inside the encrypted db, the login sealed with
the store data key and a `onionwire/wallet-config/v1` AAD on top of whole-db
encryption — the same discipline as the wallet-child creds). Save replaces the
row; clearing the URL deletes it, which is how you turn the stored wallet off
again.
**Boot precedence is stored → env → disabled.** Stored config wins; the env vars
in the table above remain the pre-F7 migration path (and the only path for
headless / non-TUI runs). A stored config that cannot be used — non-loopback
host, `.onion`, missing login — is reported and then **falls back to env**
rather than dialling the bad endpoint. To override a stored config with env,
clear the stored one (F7, empty endpoint) first.
### Wallet status, and how fresh `connected` is
The app keeps one `WalletStatus` snapshot for the draw path —
`configured`, `connected`, `last_error`, `balance_line`, `receive_address` —
and the TUI only ever reads it; it never dials the wallet from the render path.
- `configured` is true when a stored **or** env config resolved to a usable
wallet. Config is not reachability: a freshly booted or freshly saved wallet
is `configured = true`, `connected = false`, with `—` readouts.
- `connected` only ever comes from a probe. One probe is `get_address` (cheap,
loopback, and the same call `/pay` invoices need) followed by `get_balance`
for the readout. A success clears `last_error`; a failure sets
`connected = false` and keeps `configured = true`. There is no background
refresh: `connected` is whatever the **last** probe said.
- `last_error` is display copy, not a log line: trimmed, capped at 120 chars,
and with the RPC password redacted (`<redacted>`) if a lower layer ever put it
in a message.
Two probes exist:
- `wallet_refresh` / the readiness guard probe the **configured** endpoint and
update the snapshot;
- **Test connection** on the F7 screen probes the endpoint you are *currently
typing* (`Wallet::ping`) and returns `{ok, status, error}` without touching
the live wallet or the snapshot — testing an untyped endpoint is not the
wallet the app is running.
### The pay/tip readiness guard
`/tip` and `/pay` run a pre-check before the send. It never dials Tor (wallet
RPC is loopback-only), and it never dials the wallet at all when the answer is
already known locally. The order is fixed and the copy is part of the contract:
1. **not configured** → `wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC`
2. **`/tip` on a no-spend / view-only wallet** → the existing view-only message
(`wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work`), refused **before any dial** — this is the same rule
`transfer` applies, and it is the honest answer whether or not the wallet is
reachable.
3. **configured but not connected** → `wallet not connected — check endpoint, login, daemon`
4. otherwise ready. `/pay` is fine on a view-only wallet.
The check is cheap enough to run on Enter: steps 1 and 2 are local, and step 3
is one bounded probe (5s local budget). `wallet_readiness(is_tip)` is `async`
and the TUI calls it with `rt.block_on` from the key handler, the same pattern
`send_pay` / `send_tip` already use.
**Local mode is not wired yet.** Wallet-child fields (binary paths, wallet dir,
daemon address, chain backend, daemon sync state) are not part of this stored
config; the app-owned child keeps its own record (see *Where the RPC credentials
live* above). Until a screen sets them from the store, treat local mode as
not-yet-available rather than pretending a child is running.
## Create vs import
Create does **not** take a private key. `/wallet create` (TUI: F6 then `c`) asks
@ -61,23 +223,6 @@ Loopback is the only address OnionWire will dial for **wallet RPC**. `.onion`
wallet-RPC URLs are rejected: there is no Arti dial for the wallet process, and
a remote wallet RPC would move spend authority off the box.
## Chain source
The wallet needs a daemon for scan, verify, and spend. You pick one; OnionWire
does not pick a public remote node for you.
1. **Spawn a local `monerod`** (pruned on-device). Chain traffic stays on the
box. You accept disk, first sync, and (on Android) the daemon not always
running.
2. **A daemon address you supply** — `--daemon-address` on the wallet child.
Loopback if you already run `monerod`. `.onion` if you want chain traffic
over Tor (wallet child `--proxy` to a localhost SOCKS listener; the daemon
operator still sees addresses). Clearnet only if you type it — ISP sees
Monero-node traffic; not a default.
Remote daemons are untrusted (`--trusted-daemon` off). Unsynced or unreachable
→ receipts stay unverified and spend is refused. That is the honest state.
## Create a view-only wallet
Either path produces a wallet file with the view key only. Keep the seed /

View file

@ -21,11 +21,7 @@ api_curl() {
}
auth_json() {
<<<<<<< Updated upstream
api_curl -u "sirius:${FORGEJO_TOKEN}" -H "Content-Type: application/json" "$@"
=======
api_curl -u "sirius:${FORGEJO_TOKEN}" -H "Content-Type: application/json" "$@" | sed 's/\r$//'
>>>>>>> Stashed changes
}
tag="${1:?usage: publish-release.sh <tag> <name> <body-file> <asset>...}"
@ -130,12 +126,7 @@ for a in json.load(sys.stdin):
fi
done
up=$(api_curl -o /tmp/release-asset.json -w '%{http_code}' \
<<<<<<< Updated upstream
-X POST "$api/releases/$rid/assets?name=$asset" \
-u "sirius:${FORGEJO_TOKEN}" \
=======
-X POST -u "sirius:${FORGEJO_TOKEN}" "$api/releases/$rid/assets?name=$asset" \
>>>>>>> Stashed changes
-F "attachment=@$f")
if [ "$up" != "201" ]; then
die_http "upload $asset" "$up" /tmp/release-asset.json

View file

@ -15,6 +15,7 @@ pub mod session;
mod store;
pub mod tui;
pub mod wallet;
pub mod wallet_child;
pub use store::{
Friend, FriendProfile, Message, Payment, PaymentWrite, SelfIdentity, Store,

View file

@ -1,12 +1,14 @@
//! Two-node onion session: host HS, Noise IK, persist plaintext locally.
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use futures::StreamExt;
use futures::io::{AsyncRead, AsyncWrite};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tor_cell::relaycell::msg::Connected;
use tor_hsservice::{RunningOnionService, handle_rend_requests};
use zeroize::Zeroizing;
@ -23,8 +25,9 @@ use crate::qr;
use crate::ratelimit::TokenBucket;
use crate::sanitize;
use crate::session::{self, Keys};
use crate::store::{Friend, FriendProfile, Message, PaymentWrite, Store};
use crate::wallet::{self, Wallet};
use crate::store::{Friend, FriendProfile, Message, Payment, PaymentWrite, Store};
use crate::wallet::{self, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus};
use crate::wallet_child::{self, WalletChild};
pub struct RotateResult {
pub notified: usize,
@ -70,6 +73,50 @@ impl Drop for WorkerHandle {
}
}
/// Whether the app-owned wallet child pair is running.
///
/// The *choice* of chain source is separate: it lives in the sealed store
/// record and survives a restart even if no child was ever started.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WalletChildState {
/// Receive-only, or nothing chosen yet: no daemon, nothing to start.
Off,
/// A chain source is configured, but no child of ours is alive.
Stopped,
/// A child this app spawned is still up.
Running,
}
/// How far along the chain the configured daemon says it is.
///
/// `reachable == false` means **unknown**, never "synced": a daemon we cannot
/// ask must not let the wallet screen claim the chain is current.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DaemonSync {
pub reachable: bool,
pub height: u64,
pub target_height: u64,
/// Why there is no answer (receive-only, no SOCKS listener, a failed dial).
pub note: Option<String>,
}
impl DaemonSync {
/// Synced means the daemon answered and reported a target it had reached.
/// Unreachable is *not* synced.
pub fn synced(&self) -> bool {
self.reachable && self.target_height > 0 && self.height >= self.target_height
}
fn unknown(note: impl Into<String>) -> Self {
Self {
reachable: false,
height: 0,
target_height: 0,
note: Some(note.into()),
}
}
}
pub struct Node {
home: PathBuf,
store: Arc<Mutex<Store>>,
@ -77,7 +124,16 @@ pub struct Node {
hs: Mutex<Option<HsHandle>>,
onion: Mutex<String>,
keys: Mutex<Keys>,
wallet: Wallet,
/// Behind a lock because the F7 screen can re-point it at a saved config
/// without a restart. Clone it out (`wallet_snapshot`) before awaiting: a
/// `std::sync::Mutex` guard must not live across an `.await`.
wallet: Mutex<Wallet>,
/// Last probe result, for the draw path. Cheap to read, never dials.
wallet_status: Mutex<WalletStatus>,
/// The app-owned child pair (`monerod` when the source is local,
/// `monero-wallet-rpc` always). `None` until `wallet_child_start`: the
/// chain-source *choice* lives in the sealed store record, not here.
child: Mutex<Option<WalletChild>>,
incoming_limit: Mutex<TokenBucket>,
inbox: Mutex<file::Inbox>,
outbox: Arc<Outbox>,
@ -111,6 +167,10 @@ impl Node {
passphrase: &str,
) -> Result<Arc<Self>, String> {
let store = Store::open_at_with_passphrase(&home, passphrase).map_err(|e| e.to_string())?;
// Stored config first (the F7 screen's), env as the migration path.
let stored_wallet = store.load_wallet_config().map_err(|e| e.to_string())?;
let wallet = Wallet::for_boot(stored_wallet.as_ref());
let wallet_status = WalletStatus::idle(wallet.configured());
let me = store.self_identity().map_err(|e| e.to_string())?;
let keys = Keys::from_self(&me).map_err(|e| e.to_string())?;
let nickname = store.hs_nickname().map_err(|e| e.to_string())?;
@ -139,7 +199,9 @@ impl Node {
hs: Mutex::new(None),
onion: Mutex::new(onion.clone()),
keys: Mutex::new(keys),
wallet: Wallet::from_env(),
wallet: Mutex::new(wallet),
wallet_status: Mutex::new(wallet_status),
child: Mutex::new(None),
incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(inbox),
outbox: Arc::clone(&outbox),
@ -241,6 +303,10 @@ impl Node {
Ok(mut g) => drop(g.take()),
Err(_) => eprintln!("shutdown: outbox-worker lock poisoned"),
}
// The app owns the chain children; nothing else will reap them.
if let Err(e) = self.wallet_child_stop() {
eprintln!("shutdown: wallet child: {e}");
}
self.checkpoint();
Ok(())
}
@ -251,7 +317,8 @@ impl Node {
/// `sending`; `Outbox::reset_stale` requeues those on the next unlock, the
/// same recovery the parent uses for a process that died mid-attempt.
async fn drain(&self, budget: Duration) -> Result<FlushOutcome, String> {
let attempted = match tokio::time::timeout(budget, self.outbox.flush_all(unix_now())).await {
let attempted = match tokio::time::timeout(budget, self.outbox.flush_all(unix_now())).await
{
Ok(Ok(rows)) => Some(rows),
Ok(Err(e)) => return Err(e),
Err(_) => {
@ -447,19 +514,266 @@ impl Node {
.map_err(|e| e.to_string())
}
/// Every payment row with this friend, in the store's existing order.
/// Read-only: the TUI payment-history screen reads this and never touches
/// the store itself. An unknown friend is empty history, not an error.
pub fn list_payments(&self, friend_pk: &[u8]) -> Result<Vec<Payment>, String> {
self.store
.lock()
.map_err(|e| e.to_string())?
.list_payments(friend_pk)
.map_err(|e| e.to_string())
}
/// The live wallet, cloned out of its lock. Every wallet call goes through
/// this so a `std::sync::Mutex` guard never lives across an `.await`, and so
/// the F7 screen can re-point the wallet mid-session.
fn wallet_snapshot(&self) -> Wallet {
self.wallet
.lock()
.map(|w| w.clone())
.unwrap_or_else(|_| Wallet::disabled())
}
/// The snapshot the TUI draws. Cheap: no dial, no lock on the RPC. It says
/// "configured, not probed" (`connected == false`) until a probe has run.
pub fn wallet_status(&self) -> WalletStatus {
self.wallet_status
.lock()
.map(|s| s.clone())
.unwrap_or_else(|_| WalletStatus::idle(self.wallet_snapshot().configured()))
}
/// Probe the configured endpoint once and fold the result into the snapshot.
/// This is the only thing that can flip `connected` to true.
pub async fn wallet_refresh(&self) -> WalletStatus {
let w = self.wallet_snapshot();
let status = w.status().await;
if let Ok(mut slot) = self.wallet_status.lock() {
*slot = status.clone();
}
status
}
/// The pay/tip readiness guard. Blocking-friendly: the TUI calls this from
/// its key handler with `rt.block_on`, like `send_pay`/`send_tip` do.
///
/// It never dials Tor. It also never dials the wallet when the answer is
/// already known locally — an unconfigured wallet and a `/tip` on a
/// view-only wallet are refused before any socket is opened.
pub async fn wallet_readiness(&self, is_tip: bool) -> Readiness {
let w = self.wallet_snapshot();
if !w.configured() {
return Readiness::NotConfigured;
}
if is_tip && w.no_spend() {
return Readiness::NoSpend;
}
let status = self.wallet_refresh().await;
wallet::readiness(status.configured, status.connected, w.no_spend(), is_tip)
}
/// The config screen's Test-connection button: one shot against the endpoint
/// the user is typing. It does not touch the live wallet or the snapshot —
/// a test of an untyped endpoint is not the wallet we are running.
pub async fn wallet_test_connection(
&self,
rpc_url: &str,
rpc_login: &str,
) -> wallet::PingResult {
Wallet::ping(rpc_url, rpc_login).await
}
/// The config the F7 screen should show: the stored one, or the env-derived
/// one when only env set the wallet (the migration path).
pub fn wallet_config(&self) -> Option<WalletConfig> {
if let Ok(store) = self.store.lock()
&& let Ok(Some(cfg)) = store.load_wallet_config()
{
return Some(cfg);
}
self.wallet_snapshot().config()
}
/// Persist the config screen's Save and re-read it: the live wallet and the
/// snapshot both follow, so "saved · not connected" is visible without a
/// restart. Validation happens before anything is written, so a rejected
/// config leaves the running wallet exactly as it was.
pub fn wallet_save_config(&self, cfg: &WalletConfig) -> Result<(), String> {
Wallet::from_config(cfg).map_err(|e| wallet::redact(&e.to_string(), cfg.secret()))?;
{
let store = self.store.lock().map_err(|e| e.to_string())?;
store.save_wallet_config(cfg).map_err(|e| e.to_string())?;
}
// Re-read from the store rather than trusting the caller's copy.
let stored = self
.store
.lock()
.map_err(|e| e.to_string())?
.load_wallet_config()
.map_err(|e| e.to_string())?;
let wallet = Wallet::for_boot(stored.as_ref());
let configured = wallet.configured();
*self.wallet.lock().map_err(|e| e.to_string())? = wallet;
*self.wallet_status.lock().map_err(|e| e.to_string())? = WalletStatus::idle(configured);
Ok(())
}
/// The chain source the user chose, read from the sealed store record.
///
/// A store that cannot be read reports receive-only rather than an error:
/// nothing has been started in that case either, so the screen must not
/// claim a daemon the app does not have.
pub fn wallet_chain_source(&self) -> ChainSource {
self.store
.lock()
.ok()
.and_then(|s| wallet_child::load_chain_source(&s).ok().flatten())
.unwrap_or(ChainSource::None)
}
/// Persist the picker's choice. Nothing is spawned: the user may pick a
/// source and start it later — or never, which is the receive-only path.
///
/// Refused while a child is running: re-pointing a live wallet child's
/// chain would leave the argv it was spawned with describing something
/// else, so stop it first.
pub fn wallet_set_chain_source(&self, source: &ChainSource) -> Result<(), String> {
if self.wallet_child_state() == WalletChildState::Running {
return Err("stop the wallet child before changing its chain source".into());
}
let store = self.store.lock().map_err(|e| e.to_string())?;
wallet_child::save_chain_source(&store, source).map_err(|e| e.to_string())
}
/// What "spawn a local monerod" means for this identity: the daemon binary
/// resolved from `PATH` (this app does not install one), with the chain in
/// this identity's own directory rather than a shared `/var/lib`.
pub fn default_local_chain_source(&self) -> ChainSource {
ChainSource::Local {
monerod_bin: PathBuf::from("monerod"),
datadir: self.home.join("chain"),
}
}
/// The state the wallet screen draws. Cheap: no dial, no spawn.
pub fn wallet_child_state(&self) -> WalletChildState {
// Read the (store-backed) choice first: never hold the child lock while
// taking the store lock.
let configured = !matches!(self.wallet_chain_source(), ChainSource::None);
let Ok(guard) = self.child.lock() else {
return WalletChildState::Stopped;
};
match guard.as_ref() {
Some(child) if child.running() => WalletChildState::Running,
_ if configured => WalletChildState::Stopped,
_ => WalletChildState::Off,
}
}
/// Spawn the configured children — `monerod` for a local source,
/// `monero-wallet-rpc` always — and re-point the app's wallet at the child
/// this app owns.
///
/// Owning the child is the whole point: balance, receive address, `/tip` and
/// receipt verification then all go through it, so a "start node" button
/// cannot describe a daemon the wallet does not use.
pub fn wallet_child_start(&self) -> Result<(), String> {
self.ensure_running()?;
let source = self.wallet_chain_source();
if matches!(source, ChainSource::None) {
return Err("receive-only: there is no daemon to start".into());
}
if self.wallet_child_state() == WalletChildState::Running {
return Err("wallet child already running".into());
}
let child = WalletChild::new(source, self.home.join("wallet"), None)
.map_err(|e| e.to_string())?;
let client = {
let store = self.store.lock().map_err(|e| e.to_string())?;
match child.start(&store) {
Ok(client) => client,
Err(e) => {
// A half-spawned pair (monerod up, wallet rpc refused) must
// not outlive the error.
let _ = child.stop();
return Err(e.to_string());
}
}
};
if let Some(client) = client {
let wallet = client.into_wallet();
let configured = wallet.configured();
*self.wallet.lock().map_err(|e| e.to_string())? = wallet;
*self.wallet_status.lock().map_err(|e| e.to_string())? =
WalletStatus::idle(configured);
}
*self.child.lock().map_err(|e| e.to_string())? = Some(child);
Ok(())
}
/// Stop the children this app spawned. Idempotent.
pub fn wallet_child_stop(&self) -> Result<(), String> {
let child = self.child.lock().map_err(|e| e.to_string())?.take();
match child {
Some(child) => child.stop().map_err(|e| e.to_string()),
None => Ok(()),
}
}
/// Ask the configured daemon how far along the chain is, bounded by
/// `budget`. Never fabricates a height: a daemon we cannot ask — or must not
/// dial — comes back unreachable with the reason.
pub async fn wallet_chain_sync(&self, budget: Duration) -> DaemonSync {
let Some(addr) = WalletChild::daemon_address(&self.wallet_chain_source()) else {
return DaemonSync::unknown("receive-only: no daemon");
};
if is_onion_daemon(&addr) {
return DaemonSync::unknown(
"remote .onion daemon needs a local SOCKS listener (not wired yet)",
);
}
match daemon_get_info(&addr, budget).await {
Ok((height, target_height)) => DaemonSync {
reachable: true,
height,
target_height,
note: None,
},
Err(e) => DaemonSync::unknown(e),
}
}
/// Free space on the filesystem a *local* daemon would store the chain on,
/// in whole GiB. `None` for a remote source (their disk, not ours) and when
/// the answer cannot be read — never a guessed number.
pub fn wallet_chain_free_gb(&self) -> Option<u64> {
let ChainSource::Local { datadir, .. } = &self.wallet_chain_source() else {
return None;
};
// monerod creates the datadir on first run; before that, the volume that
// will hold it is the one `home` is on.
let path = if datadir.exists() { datadir } else { &self.home };
let out = Command::new("df").arg("-Pk").arg(path).output().ok()?;
if !out.status.success() {
return None;
}
parse_df_avail_kb(&String::from_utf8_lossy(&out.stdout)).map(|kb| kb / (1024 * 1024))
}
/// Current wallet balance as a human-readable XMR string, or `off` when the
/// wallet is not configured.
pub async fn wallet_balance(&self) -> String {
if !self.wallet.configured() {
let w = self.wallet_snapshot();
if !w.configured() {
return "off".into();
}
match self.wallet.get_balance().await {
match w.get_balance().await {
Ok(b) => crate::pay::atomic_to_xmr_str(&b),
Err(_) => "err".into(),
}
}
pub fn wipe_messages(&self) -> Result<(), String> {
self.store
.lock()
@ -560,8 +874,9 @@ impl Node {
/// Pay selected friend via wallet RPC, then signed receipt.
pub async fn tip(&self, friend_pk: &[u8], atomic: &str, _memo: &str) -> Result<(), String> {
if !self.wallet.configured() {
return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into());
let w = self.wallet_snapshot();
if !w.configured() {
return Err(wallet::NOT_CONFIGURED_MSG.into());
}
let address = self
.friend_profile(friend_pk)?
@ -574,8 +889,7 @@ impl Node {
let amount: u64 = atomic
.parse()
.map_err(|_| "amount too large for wallet RPC".to_string())?;
let txid = self
.wallet
let txid = w
.transfer(&address, amount)
.await
.map_err(|e| e.to_string())?;
@ -614,8 +928,9 @@ impl Node {
}
async fn invoice_address(&self) -> Result<String, String> {
if self.wallet.configured()
&& let Ok(addr) = self.wallet.create_address().await
let w = self.wallet_snapshot();
if w.configured()
&& let Ok(addr) = w.create_address().await
&& pay::check_address(&addr).is_ok()
{
return Ok(addr);
@ -634,10 +949,9 @@ impl Node {
/// how to wrap it.
pub async fn wallet_receive_address(&self) -> Result<String, String> {
let profile_addr = self.self_profile()?.xmr_addr;
if self
.wallet
.configured()
&& let Ok(addr) = self.wallet.get_address().await
let w = self.wallet_snapshot();
if w.configured()
&& let Ok(addr) = w.get_address().await
&& pay::check_address(&addr).is_ok()
{
return Ok(addr);
@ -653,8 +967,9 @@ impl Node {
/// configured. Calls `pay::atomic_to_xmr_str` so the UI never parses
/// piconero itself.
pub async fn wallet_balance_line(&self) -> String {
if self.wallet.configured() {
match self.wallet.get_balance().await {
let w = self.wallet_snapshot();
if w.configured() {
match w.get_balance().await {
Ok(b) if !b.is_empty() => {
let xmr = pay::atomic_to_xmr_str(&b);
if xmr == "0" {
@ -674,11 +989,15 @@ impl Node {
/// Recent in/out transfers for the wallet screen, newest first, capped to a
/// small window. Returns the same `TransferRow` shape the existing tests
/// already cover.
pub async fn wallet_recent_transfers(&self, cap: usize) -> Result<Vec<wallet::TransferRow>, String> {
if !self.wallet.configured() {
pub async fn wallet_recent_transfers(
&self,
cap: usize,
) -> Result<Vec<wallet::TransferRow>, String> {
let w = self.wallet_snapshot();
if !w.configured() {
return Ok(Vec::new());
}
let rows = self.wallet.get_transfers().await.map_err(|e| e.to_string())?;
let rows = w.get_transfers().await.map_err(|e| e.to_string())?;
let mut rows = rows;
rows.sort_by(|a, b| b.txid.cmp(&a.txid));
Ok(rows.into_iter().take(cap).collect())
@ -687,11 +1006,11 @@ impl Node {
/// 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<String, String> {
if !self.wallet.configured() {
return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into());
let w = self.wallet_snapshot();
if !w.configured() {
return Err(wallet::NOT_CONFIGURED_MSG.into());
}
self.wallet
.create_wallet(wallet::DEFAULT_WALLET_FILENAME, password)
w.create_wallet(wallet::DEFAULT_WALLET_FILENAME, password)
.await
.map_err(|e| e.to_string())
}
@ -699,11 +1018,11 @@ impl Node {
/// 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> {
if !self.wallet.configured() {
return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into());
let w = self.wallet_snapshot();
if !w.configured() {
return Err(wallet::NOT_CONFIGURED_MSG.into());
}
self.wallet
.restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed)
w.restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed)
.await
.map_err(|e| e.to_string())
}
@ -837,7 +1156,10 @@ impl Node {
/// Pending and failed outbox rows for a friend, for UI surfacing.
/// Delivered rows are dropped, so a message absent here was sent.
pub fn outbox_pending(&self, friend_pk: &[u8]) -> Result<Vec<crate::store::OutboxEntry>, String> {
pub fn outbox_pending(
&self,
friend_pk: &[u8],
) -> Result<Vec<crate::store::OutboxEntry>, String> {
self.outbox.pending(friend_pk)
}
@ -1056,8 +1378,13 @@ impl Node {
.map_err(|e| e.to_string())?
};
let mut verified = false;
if self.wallet.configured() {
match self.wallet.get_transfers().await {
// Honest prerequisite: an unsynced wallet cannot see the tx, so a
// get_transfers "miss" would be a lie. Until the chain is ready the
// receipt stays verified=0 — that is the correct state, not an error.
let w = self.wallet_snapshot();
let ready = w.configured() && w.can_verify_receipts().await;
if ready {
match w.get_transfers().await {
Ok(rows)
if wallet::transfers_match(
&rows,
@ -1220,3 +1547,282 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool {
false
}
/// `.onion` daemon addresses must never be resolved locally: the SOCKS listener
/// is what dials them, and it does not exist yet. So this is a refusal, not a
/// dial — and it is checked before any socket is opened.
fn is_onion_daemon(addr: &str) -> bool {
addr.rsplit_once(':')
.map(|(host, _)| host)
.unwrap_or(addr)
.trim()
.to_ascii_lowercase()
.ends_with(".onion")
}
/// `get_info` from the daemon, over plain HTTP/1.1. Hand-rolled for the same
/// reason the wallet client is: no HTTP crate in this tree, and this request
/// carries nothing secret (the wallet RPC stays a separate, authenticated
/// loopback connection). This dials the *chain* address only.
const DAEMON_PROBE_MAX_BYTES: usize = 64 * 1024;
async fn daemon_get_info(addr: &str, budget: Duration) -> Result<(u64, u64), String> {
let body = r#"{"jsonrpc":"2.0","id":"0","method":"get_info"}"#;
let request = format!(
"POST /json_rpc HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
let mut stream = tokio::time::timeout(budget, tokio::net::TcpStream::connect(addr))
.await
.map_err(|_| format!("{addr}: connect timed out"))?
.map_err(|e| format!("{addr}: {e}"))?;
let raw = tokio::time::timeout(budget, async {
stream.write_all(request.as_bytes()).await?;
let mut buf = Vec::new();
let mut tmp = [0u8; 8192];
loop {
let n = stream.read(&mut tmp).await?;
if n == 0 {
break;
}
buf.extend_from_slice(&tmp[..n]);
if buf.len() >= DAEMON_PROBE_MAX_BYTES {
break;
}
}
Ok::<Vec<u8>, std::io::Error>(buf)
})
.await
.map_err(|_| format!("{addr}: read timed out"))?
.map_err(|e| format!("{addr}: {e}"))?;
let text = String::from_utf8_lossy(&raw);
let json = text
.find('{')
.and_then(|start| text.rfind('}').map(|end| &text[start..=end]))
.ok_or_else(|| format!("{addr}: no JSON body"))?;
let value: serde_json::Value =
serde_json::from_str(json).map_err(|e| format!("{addr}: {e}"))?;
let result = value
.get("result")
.ok_or_else(|| format!("{addr}: no get_info result"))?;
match (
result.get("height").and_then(|h| h.as_u64()),
result.get("target_height").and_then(|h| h.as_u64()),
) {
(Some(height), Some(target_height)) => Ok((height, target_height)),
_ => Err(format!("{addr}: get_info has no chain height")),
}
}
/// Available 1K blocks from `df -Pk` output. Separate from the process call so
/// the parse is testable without a filesystem.
fn parse_df_avail_kb(stdout: &str) -> Option<u64> {
stdout.lines().rev().find_map(|line| {
let mut fields = line.split_whitespace();
fields.next()?; // filesystem
fields.next()?; // 1K blocks
fields.next()?; // used
fields.next()?.parse().ok() // available
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn onion_daemons_are_refused_before_any_dial() {
assert!(is_onion_daemon("abc234def.onion:18081"));
assert!(is_onion_daemon("ABC234DEF.ONION:18081"));
assert!(!is_onion_daemon("127.0.0.1:18081"));
assert!(!is_onion_daemon("node.example.com:18089"));
assert!(!is_onion_daemon("notonion:18081"));
}
#[test]
fn unavailable_daemon_is_not_synced() {
let synced = DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
};
assert!(synced.synced());
let behind = DaemonSync {
reachable: true,
height: 3_209_999,
target_height: 3_210_000,
note: None,
};
assert!(!behind.synced());
// A daemon that reports no target is not "synced", it is unknown.
let no_target = DaemonSync {
reachable: true,
height: 0,
target_height: 0,
note: None,
};
assert!(!no_target.synced());
assert!(!DaemonSync::unknown("no daemon").synced());
}
#[test]
fn parse_df_avail_reads_the_available_column() {
let out = "Filesystem 1024-blocks Used Available Capacity Mounted on\n/dev/sda1 100000000 50000000 48000000 52% /\n";
assert_eq!(parse_df_avail_kb(out), Some(48_000_000));
// Header only, or a relocated filesystem name: no number, no answer.
assert_eq!(
parse_df_avail_kb(
"Filesystem 1024-blocks Used Available Capacity Mounted on\n"
),
None
);
assert_eq!(parse_df_avail_kb("garbage"), None);
}
/// A real socket, a real HTTP response, a real parse: the sync line is only
/// as honest as this.
#[tokio::test]
async fn daemon_get_info_reads_height_and_target() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap().to_string();
let server = tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 2048];
let _ = sock.read(&mut buf).await;
let body = r#"{"jsonrpc":"2.0","id":"0","result":{"height":3210000,"target_height":3210000}}"#;
let resp = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
let _ = sock.write_all(resp.as_bytes()).await;
});
let (height, target) = daemon_get_info(&addr, Duration::from_secs(5)).await.unwrap();
assert_eq!((height, target), (3_210_000, 3_210_000));
server.await.unwrap();
}
/// A dead daemon is an error, never a fabricated height.
#[tokio::test]
async fn daemon_get_info_reports_a_dead_daemon() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap().to_string();
drop(listener);
let err = daemon_get_info(&addr, Duration::from_secs(5))
.await
.expect_err("a closed port must not answer");
assert!(err.contains(&addr), "{err}");
}
// Official mainnet standard address (Monero docs), the same constant the
// integration tests use. `insert_payment` checks the checksum.
const ADDR: &str = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge";
/// Never dials. A store-backed read must not touch it.
struct NullDeliverer;
impl crate::outbox::Deliverer for NullDeliverer {
fn deliver<'a>(
&'a self,
_onion: &'a str,
_pinned_id: &'a [u8],
_prekey: &'a [u8],
_plaintext: &'a [u8],
) -> crate::outbox::BoxFut<'a, Result<(), String>> {
Box::pin(async { Err("no tor in this test".into()) })
}
}
/// A `Node` over a real encrypted store with an *unbootstrapped* Arti
/// client: no Tor, no onion service, no outbox worker. Store-backed reads
/// (`list_payments`) work; a send would not. Cheap enough for a plain
/// `#[cfg(test)]` test, which is the only way to reach a `Node` without
/// bootstrapping Tor (`Node::start*` is the sole public constructor).
fn offline_node(home: &Path, store: Store) -> Node {
let cfg = hs::client_config(&home.join("arti"), &home.join("cache"));
let client = arti_client::TorClient::builder()
.config(cfg)
.create_unbootstrapped()
.expect("unbootstrapped arti client");
let store = Arc::new(Mutex::new(store));
let outbox = Arc::new(Outbox::new(Arc::clone(&store), Arc::new(NullDeliverer)));
Node {
home: home.to_path_buf(),
store,
client,
hs: Mutex::new(None),
onion: Mutex::new(String::new()),
keys: Mutex::new(Keys::generate()),
wallet: Mutex::new(Wallet::disabled()),
wallet_status: Mutex::new(WalletStatus::idle(false)),
child: Mutex::new(None),
incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(file::Inbox::new(home.join("inbox"))),
outbox,
worker: Mutex::new(None),
stopped: AtomicBool::new(false),
onion_reachable: AtomicBool::new(false),
}
}
/// The payment-history screen reads through this: every row for the friend
/// with its dir/kind/amount/verification intact, and an empty history (not
/// an error) for a friend with no rows or an unknown pubkey.
#[tokio::test]
async fn list_payments_returns_the_friends_rows_and_empty_for_an_unknown_friend() {
let dir = tempfile::tempdir().expect("tempdir");
let home = dir.path().join("home");
std::fs::create_dir_all(&home).expect("home");
let store = Store::open_at_with_passphrase(&home, "onionwire-test").expect("open store");
let keys = Keys::generate();
let peer = keys.identity_pk;
store
.upsert_friend(&peer, "peer.onion", None)
.expect("friend");
// Outbound, the row shape `pay_invoice` writes.
let out_id = store
.insert_payment(
&peer,
PaymentWrite {
dir: "out",
kind: "invoice",
amount_atomic: "120000000000",
address: ADDR,
memo: "coffee",
txid: None,
verified: false,
},
)
.expect("outbound row");
let node = offline_node(&home, store);
// Inbound through the node's own ingest path, signing as the peer.
let rcp = pay::sign_receipt(&keys.identity_sk, "deadbeef", "5", ADDR, unix_now())
.expect("sign receipt");
node.ingest_receipt(&peer, &pay::encode_receipt(&rcp))
.await
.expect("ingest receipt");
let rows = node.list_payments(&peer).expect("list_payments");
assert_eq!(rows.len(), 2, "{rows:?}");
assert_eq!(rows[0].id, out_id);
assert_eq!(rows[0].dir, "out");
assert_eq!(rows[0].kind, "invoice");
assert_eq!(rows[0].amount_atomic, "120000000000");
assert_eq!(rows[0].address, ADDR);
assert_eq!(rows[0].memo, "coffee");
assert_eq!(rows[0].txid, None);
assert!(!rows[0].verified);
assert!(rows[0].created_at > 0);
assert_eq!(rows[1].dir, "in");
assert_eq!(rows[1].kind, "receipt");
assert_eq!(rows[1].amount_atomic, "5");
assert_eq!(rows[1].address, ADDR);
assert_eq!(rows[1].txid.as_deref(), Some("deadbeef"));
// No wallet is configured here, so nothing verified the receipt.
assert!(!rows[1].verified);
// Unknown pubkey: empty history, not an error.
let none = node.list_payments(&[9u8; 32]).expect("unknown friend");
assert!(none.is_empty(), "{none:?}");
}
}

View file

@ -251,6 +251,24 @@ impl Store {
kdf_salt BLOB NOT NULL,
wrapped_key BLOB NOT NULL
);
-- The wallet child's RPC creds + chain-source snapshot. One row,
-- sealed with the store data key (see `save_wallet_child`): the
-- creds never touch the filesystem in the clear.
CREATE TABLE IF NOT EXISTS wallet_child (
id INTEGER PRIMARY KEY CHECK (id = 1),
sealed BLOB NOT NULL,
updated_at INTEGER NOT NULL
);
-- Remote-mode wallet config the user set in-app (F7): the endpoint,
-- the login, and the view-only flag. One row; the login is sealed
-- with the store data key (see `save_wallet_config`).
CREATE TABLE IF NOT EXISTS wallet_config (
id INTEGER PRIMARY KEY CHECK (id = 1),
rpc_url TEXT NOT NULL,
sealed_login BLOB NOT NULL,
no_spend INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS payments (
id INTEGER PRIMARY KEY,
friend_id INTEGER NOT NULL REFERENCES friends(id),
@ -298,6 +316,96 @@ impl Store {
.map_err(Into::into)
}
/// Seal the wallet child's config (RPC creds + chain-source snapshot) into
/// the encrypted store, replacing the single row.
///
/// The creds are generated per install and grant spend authority over the
/// wallet child, so they are stored the same way message bodies are: AEAD
/// with the store data key on top of the whole-db SQLCipher layer. They are
/// never written to a plaintext file beside the wallet.
pub fn save_wallet_child(&self, json: &str) -> Result<()> {
let blob = crate::backup::aead_encrypt(&self.msg_key, json.as_bytes(), WALLET_CHILD_AAD)
.map_err(Error)?;
self.conn.execute(
"INSERT INTO wallet_child (id, sealed, updated_at) VALUES (1, ?1, ?2)
ON CONFLICT(id) DO UPDATE SET sealed = excluded.sealed, updated_at = excluded.updated_at",
params![blob, unix_now()],
)?;
Ok(())
}
/// Read back the sealed wallet-child config, or `None` before the first
/// child start. A blob that does not decrypt is an error, never a guess.
pub fn load_wallet_child(&self) -> Result<Option<String>> {
let row: Option<Vec<u8>> = self
.conn
.query_row("SELECT sealed FROM wallet_child WHERE id = 1", [], |row| {
row.get(0)
})
.optional()?;
let Some(blob) = row else {
return Ok(None);
};
let plain = crate::backup::aead_decrypt(&self.msg_key, &blob, WALLET_CHILD_AAD)
.map_err(|_| Error("wallet-child config decrypt failed".into()))?;
String::from_utf8(plain)
.map(Some)
.map_err(|_| Error("wallet-child config is not utf-8".into()))
}
/// Persist the remote-mode wallet config the F7 screen saved. One row,
/// replaced in place; an empty `rpc_url` clears it (that is how a user
/// turns the stored wallet off again).
///
/// The login is `user:pass` for a wallet that can spend, so it is sealed
/// with the store data key on top of the whole-db SQLCipher layer — the
/// same discipline as the wallet-child creds.
pub fn save_wallet_config(&self, cfg: &crate::wallet::WalletConfig) -> Result<()> {
if cfg.rpc_url.trim().is_empty() {
self.conn.execute("DELETE FROM wallet_config", [])?;
return Ok(());
}
let sealed =
crate::backup::aead_encrypt(&self.msg_key, cfg.rpc_login.as_bytes(), WALLET_CONFIG_AAD)
.map_err(Error)?;
self.conn.execute(
"INSERT INTO wallet_config (id, rpc_url, sealed_login, no_spend, updated_at)
VALUES (1, ?1, ?2, ?3, ?4)
ON CONFLICT(id) DO UPDATE SET rpc_url = excluded.rpc_url,
sealed_login = excluded.sealed_login, no_spend = excluded.no_spend,
updated_at = excluded.updated_at",
params![cfg.rpc_url.trim(), sealed, cfg.no_spend as i64, unix_now()],
)?;
Ok(())
}
/// Read the stored remote-mode config, or `None` when none was ever saved.
/// A blob that does not decrypt is an error, never a guess.
pub fn load_wallet_config(&self) -> Result<Option<crate::wallet::WalletConfig>> {
let row: Option<(String, Vec<u8>, i64)> = self
.conn
.query_row(
"SELECT rpc_url, sealed_login, no_spend FROM wallet_config WHERE id = 1",
[],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
)
.optional()?;
let Some((rpc_url, sealed, no_spend)) = row else {
return Ok(None);
};
let login = crate::backup::aead_decrypt(&self.msg_key, &sealed, WALLET_CONFIG_AAD)
.map_err(|_| Error("wallet config decrypt failed".into()))?;
// The login is a secret: it must not survive in a bare `String`.
let login = Zeroizing::new(
String::from_utf8(login).map_err(|_| Error("wallet config is not utf-8".into()))?,
);
Ok(Some(crate::wallet::WalletConfig {
rpc_url,
rpc_login: login,
no_spend: no_spend != 0,
}))
}
pub fn replace_identity_keys(
&self,
identity_sk: &[u8],
@ -802,17 +910,13 @@ impl Store {
}
pub fn append_message(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<()> {
self.append_message_id(friend_pk, dir, plaintext).map(|_| ())
self.append_message_id(friend_pk, dir, plaintext)
.map(|_| ())
}
/// Same as `append_message`, returning the row id so an outbox row can
/// point at the body instead of storing a second copy.
pub fn append_message_id(
&self,
friend_pk: &[u8],
dir: &str,
plaintext: &[u8],
) -> Result<i64> {
pub fn append_message_id(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<i64> {
if dir != "in" && dir != "out" {
return Err(Error("dir must be in or out".into()));
}
@ -861,11 +965,7 @@ impl Store {
let aad = message_aad(friend_id, &dir, id);
let plaintext = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad)
.map_err(|_| Error("message decrypt failed".into()))?;
out.push(Message {
id,
dir,
plaintext,
});
out.push(Message { id, dir, plaintext });
}
Ok(out)
}
@ -1140,7 +1240,10 @@ fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Friend> {
fn gen_prekey() -> (Zeroizing<Vec<u8>>, Vec<u8>) {
let sk = StaticSecret::random_from_rng(OsRng);
let pk = X25519Public::from(&sk);
(Zeroizing::new(sk.to_bytes().to_vec()), pk.to_bytes().to_vec())
(
Zeroizing::new(sk.to_bytes().to_vec()),
pk.to_bytes().to_vec(),
)
}
/// Per-install KDF salt for the whole-database key. Not secret (a salt never
@ -1395,6 +1498,14 @@ fn unix_now() -> i64 {
.unwrap_or(0)
}
/// 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";
/// AAD for the sealed remote-mode wallet config row. Same reasoning as the
/// wallet-child AAD: one store key, many domains.
const WALLET_CONFIG_AAD: &[u8] = b"onionwire/wallet-config/v1";
fn fingerprint(pubkey: &[u8]) -> String {
pubkey.iter().map(|b| format!("{b:02x}")).collect()
}
@ -1690,22 +1801,16 @@ mod at_rest {
params![salt.as_slice(), wrapped],
)
.unwrap();
for (dir, body) in [
("in", "legacy-body-xyz"),
("out", "legacy-reply-xyz"),
] {
for (dir, body) in [("in", "legacy-body-xyz"), ("out", "legacy-reply-xyz")] {
conn.execute(
"INSERT INTO messages (friend_id, dir, plaintext, created_at) VALUES (1, ?1, x'', 7)",
params![dir],
)
.unwrap();
let id = conn.last_insert_rowid();
let blob = crate::backup::aead_encrypt(
&data_key,
body.as_bytes(),
&message_aad(1, dir, id),
)
.unwrap();
let blob =
crate::backup::aead_encrypt(&data_key, body.as_bytes(), &message_aad(1, dir, id))
.unwrap();
conn.execute(
"UPDATE messages SET plaintext = ?1 WHERE id = ?2",
params![blob, id],
@ -1733,7 +1838,8 @@ mod at_rest {
"fixture must be a plaintext sqlite file"
);
let store = Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("open+upgrade");
let store =
Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("open+upgrade");
assert_eq!(
store.self_identity().unwrap().identity_sk[..],
LEGACY_IDENTITY_SK[..]
@ -1755,7 +1861,10 @@ mod at_rest {
);
for (needle, what) in [
(b"legacy-body-xyz".to_vec(), "message body"),
(fingerprint(&LEGACY_FRIEND_PK).into_bytes(), "friend pubkey hex"),
(
fingerprint(&LEGACY_FRIEND_PK).into_bytes(),
"friend pubkey hex",
),
(LEGACY_IDENTITY_SK.to_vec(), "identity secret"),
(b"legacy-friend.onion".to_vec(), "locator"),
] {
@ -1831,4 +1940,64 @@ mod at_rest {
);
}
}
/// The wallet-child RPC creds grant spend authority, so they are stored
/// sealed in the encrypted store — never as a plaintext file next to the
/// wallet, and never as a plaintext row.
#[test]
fn wallet_child_creds_round_trip_sealed_and_load_none_before_first_start() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open_at_with_passphrase(dir.path(), "child-pass").unwrap();
assert!(
store.load_wallet_child().unwrap().is_none(),
"a fresh store has no wallet-child config"
);
let cfg = r#"{"user":"owuser","pass":"ow-secret-pass-xyz","wallet_filename":"onionwire"}"#;
store.save_wallet_child(cfg).unwrap();
assert_eq!(store.load_wallet_child().unwrap().as_deref(), Some(cfg));
let sealed: Vec<u8> = store
.conn
.query_row("SELECT sealed FROM wallet_child WHERE id = 1", [], |r| {
r.get(0)
})
.unwrap();
assert_ne!(
sealed.as_slice(),
cfg.as_bytes(),
"row stored the creds as plaintext"
);
assert!(
!sealed.windows(11).any(|w| w == b"ow-secret-p".as_slice()),
"sealed row leaked the password"
);
// Re-sealing replaces the single row instead of stacking rows.
let cfg2 = r#"{"user":"owuser","pass":"second-pass-abc","wallet_filename":"onionwire"}"#;
store.save_wallet_child(cfg2).unwrap();
assert_eq!(store.load_wallet_child().unwrap().as_deref(), Some(cfg2));
let rows: i64 = store
.conn
.query_row("SELECT count(*) FROM wallet_child", [], |r| r.get(0))
.unwrap();
assert_eq!(rows, 1, "wallet_child must hold exactly one row");
store.checkpoint_wal().unwrap();
drop(store);
for name in ["onionwire.db", "onionwire.db-wal", "onionwire.db-shm"] {
let path = dir.path().join(name);
let Ok(bytes) = std::fs::read(&path) else {
continue;
};
for needle in [
b"second-pass-abc".as_slice(),
b"ow-secret-pass-xyz".as_slice(),
] {
assert!(
!bytes.windows(needle.len()).any(|w| w == needle),
"{name} contains the wallet-child password in the clear"
);
}
}
}
}

1121
src/tui.rs

File diff suppressed because it is too large Load diff

View file

@ -1,3 +1,4 @@
use std::path::PathBuf;
use std::time::Duration;
use rand::RngCore;
@ -18,6 +19,231 @@ impl std::fmt::Display for Error {
impl std::error::Error for Error {}
/// The user's choice of where the Monero daemon lives. No default remote node
/// is ever implied — every `Remote` is constructed from explicit user input.
///
/// Wallet RPC is always loopback HTTP Digest. The chain source is what the
/// *wallet child* connects to, not what the messenger dials.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChainSource {
/// Receive-only. No wallet child, no daemon, no spend.
None,
/// Spawn a local `monerod`. Chain traffic stays on the device.
Local {
/// Path to the `monerod` binary.
monerod_bin: PathBuf,
/// Data directory for the local daemon.
datadir: PathBuf,
},
/// A daemon address the user supplied. Trust follows the address.
Remote {
/// Daemon host. May be loopback, `.onion`, or a clearnet host the user
/// typed explicitly.
host: String,
/// Daemon port. User-configurable; 18089 (restricted RPC) is common but
/// not a constant.
port: u16,
},
}
/// Remote-mode wallet config: the `monero-wallet-rpc` the user already runs
/// themselves (F7 sets it, the store keeps it, env is the migration path).
///
/// `rpc_url` never carries `user:pass` — that is `rpc_login`, which stays in a
/// wiping buffer and is sealed at rest. This is the same three fields
/// `ONIONWIRE_WALLET_RPC` / `ONIONWIRE_WALLET_RPC_LOGIN` /
/// `ONIONWIRE_WALLET_NO_SPEND` describe.
#[derive(Clone)]
pub struct WalletConfig {
/// `http://host:port[/path]`. Loopback-only enforcement stays in
/// [`parse_http_url`].
pub rpc_url: String,
/// `user:pass`. Never logged, never in a status line, never on disk in the
/// clear.
pub rpc_login: Zeroizing<String>,
/// View-only deployment: `/tip` is refused locally, before any dial.
pub no_spend: bool,
}
impl WalletConfig {
pub fn new(rpc_url: &str, rpc_login: &str, no_spend: bool) -> Self {
Self {
rpc_url: rpc_url.trim().to_string(),
rpc_login: Zeroizing::new(rpc_login.trim().to_string()),
no_spend,
}
}
/// The password half of `user:pass` (the whole string when there is no
/// colon), for redaction. Never rendered anywhere.
pub fn secret(&self) -> &str {
match self.rpc_login.split_once(':') {
Some((_, pass)) => pass,
None => self.rpc_login.as_str(),
}
}
}
/// Redacted on purpose: a `Debug` that prints the login turns any `{:?}` —
/// a log line, a panic message, an assert — into a credential leak.
impl std::fmt::Debug for WalletConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WalletConfig")
.field("rpc_url", &self.rpc_url)
.field("rpc_login", &"<redacted>")
.field("no_spend", &self.no_spend)
.finish()
}
}
impl PartialEq for WalletConfig {
fn eq(&self, other: &Self) -> bool {
self.rpc_url == other.rpc_url
&& self.rpc_login.as_str() == other.rpc_login.as_str()
&& self.no_spend == other.no_spend
}
}
impl Eq for WalletConfig {}
impl Default for WalletConfig {
fn default() -> Self {
Self::new("", "", false)
}
}
/// The snapshot the TUI draws (main-screen indicator + config-screen status
/// line). No dialing, no secrets: `last_error` is already sanitized and short.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalletStatus {
/// A stored or env config resolved to a usable `Wallet`.
pub configured: bool,
/// The last probe succeeded. **Never** set from config-existence: config is
/// not reachability.
pub connected: bool,
/// The most recent failure, sanitized for display. Cleared on success.
pub last_error: Option<String>,
/// Human-readable balance, e.g. `123456 piconero`, or `—`.
pub balance_line: String,
/// The address `/pay` invoices would hand out, or `—`.
pub receive_address: String,
}
/// The `—` the TUI shows for a readout that has no honest value yet.
pub const NOT_SET: &str = "—";
impl WalletStatus {
/// Configured, never probed: the state right after boot or a save.
pub fn idle(configured: bool) -> Self {
Self {
configured,
connected: false,
last_error: None,
balance_line: NOT_SET.to_string(),
receive_address: NOT_SET.to_string(),
}
}
pub fn configured(&self) -> bool {
self.configured
}
pub fn connected(&self) -> bool {
self.connected
}
}
/// The config screen's Test-connection result. `status` is the success copy;
/// `error` is a short sanitized reason, and it never carries the login.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PingResult {
pub ok: bool,
/// Short human status, e.g. `connected`, or `not connected` on failure.
pub status: String,
/// Short sanitized reason on failure, or `None`.
pub error: Option<String>,
}
impl PingResult {
/// The TUI's status line: one string, never a secret.
pub fn line(&self) -> String {
match &self.error {
Some(e) => format!("{} · {e}", self.status),
None => self.status.clone(),
}
}
}
/// Refusal copy for the pay/tip guard. Deterministic: the TUI asserts these
/// exact strings.
pub const NOT_CONFIGURED_MSG: &str =
"wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC";
pub const NOT_CONNECTED_MSG: &str = "wallet not connected — check endpoint, login, daemon";
/// The pay/tip pre-check answer, in the order the guard evaluates it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Readiness {
/// Configured, reachable, and (for `/tip`) spend-capable.
Ready,
/// No stored and no env config.
NotConfigured,
/// Configured but the probe failed (or there was none).
NotConnected,
/// `/tip` on a view-only/no-spend wallet. Never a dial.
NoSpend,
}
impl Readiness {
/// The refusal copy when the guard rejects, `None` when ready.
pub fn refusal(self) -> Option<&'static str> {
match self {
Readiness::Ready => None,
Readiness::NotConfigured => Some(NOT_CONFIGURED_MSG),
Readiness::NotConnected => Some(NOT_CONNECTED_MSG),
Readiness::NoSpend => Some(VIEW_ONLY_MSG),
}
}
pub fn is_ready(self) -> bool {
matches!(self, Readiness::Ready)
}
}
/// The guard's state table, and the only place its order is decided:
///
/// 1. not configured — the copy names the fix (F7, or the env var);
/// 2. `/tip` on a no-spend wallet — it can never spend, so it is refused
/// before any dial, reachable or not (same rule as `transfer`);
/// 3. configured but not connected — check endpoint, login, daemon;
/// 4. otherwise ready. `/pay` is fine on a view-only wallet.
pub fn readiness(configured: bool, connected: bool, no_spend: bool, is_tip: bool) -> Readiness {
if !configured {
return Readiness::NotConfigured;
}
if is_tip && no_spend {
return Readiness::NoSpend;
}
if !connected {
return Readiness::NotConnected;
}
Readiness::Ready
}
/// Display copy, not a log line: drop the secret if some lower layer put it in
/// the message, and keep it short enough for a status line.
pub(crate) fn redact(msg: &str, secret: &str) -> String {
let mut out = msg.trim().to_string();
if !secret.is_empty() {
out = out.replace(secret, "<redacted>");
}
const MAX: usize = 120;
if out.chars().count() > MAX {
out = out.chars().take(MAX).collect();
out.push('…');
}
out
}
#[derive(Clone)]
struct Endpoint {
host: String,
@ -43,12 +269,26 @@ impl std::fmt::Debug for Endpoint {
pub struct Wallet {
endpoint: Option<Endpoint>,
no_spend: bool,
/// Budget for loopback management calls (`get_address`, `query_key`,
/// create/import). The wallet child is on the same box, so this stays short.
timeout_local: Duration,
/// Budget for calls that wait on the daemon (`get_info`, `get_transfers`,
/// `transfer`). A first sync or a remote daemon legitimately outlasts the
/// local budget, and treating that as "down" is what left receipts
/// permanently unverified.
timeout_chain: Duration,
}
/// What /tip says when the wallet cannot spend. Same text for the explicit
/// `ONIONWIRE_WALLET_NO_SPEND=1` switch and for a view-only wallet detected over
/// RPC, so the operator never has to guess which one it was.
const VIEW_ONLY_MSG: &str = "wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work";
/// RPC, so the operator never has to guess which one it was. The TUI's
/// pay/tip guard returns this exact string (see [`Readiness::refusal`]).
pub const VIEW_ONLY_MSG: &str = "wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work";
/// What a spend says while the wallet is not synced. Honest state, not a bug:
/// the caller retries once the daemon has caught up.
pub const NOT_SYNCED_MSG: &str =
"wallet is not synced — spend refused until the daemon reaches the chain tip";
/// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in monero's
/// `src/wallet/wallet_rpc_server_error_codes.h`.
@ -69,14 +309,27 @@ pub const SPEND_AUTHORITY_WARNING: &str = "this wallet file can spend. anyone wi
const RPC_TIMEOUT: Duration = Duration::from_secs(5);
/// Budget for calls that wait on the daemon (`get_info`, `get_transfers`,
/// `transfer`). A first sync or a remote daemon legitimately outlasts the
/// loopback budget; a 5s cap there leaves receipts permanently unverified.
pub const CHAIN_RPC_TIMEOUT: Duration = Duration::from_secs(60);
impl Wallet {
pub fn disabled() -> Self {
/// The one place the budgets are defaulted. Callers adjust them with
/// [`Wallet::with_timeouts`].
fn new(endpoint: Option<Endpoint>, no_spend: bool) -> Self {
Self {
endpoint: None,
no_spend: false,
endpoint,
no_spend,
timeout_local: RPC_TIMEOUT,
timeout_chain: CHAIN_RPC_TIMEOUT,
}
}
pub fn disabled() -> Self {
Self::new(None, false)
}
/// `ONIONWIRE_WALLET_NO_SPEND=1` asks for a view-only deployment: `/tip` is
/// refused locally, before any RPC dial. `/pay` and receipt verification
/// keep working.
@ -92,33 +345,149 @@ impl Wallet {
.map(|v| Zeroizing::new(v.trim().to_string()))
.filter(|v| !v.is_empty());
match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) {
Ok(endpoint) => Self {
endpoint: Some(endpoint),
no_spend,
},
Ok(endpoint) => Self::new(Some(endpoint), no_spend),
Err(e) => {
eprintln!("ONIONWIRE_WALLET_RPC: {e}");
Self {
endpoint: None,
no_spend,
}
Self::new(None, no_spend)
}
}
}
_ => Self {
endpoint: None,
no_spend,
},
_ => Self::new(None, no_spend),
}
}
pub fn from_url(url: &str) -> Result<Self> {
Ok(Self {
endpoint: Some(parse_http_url(url, None)?),
no_spend: false,
Ok(Self::new(Some(parse_http_url(url, None)?), false))
}
/// Build the wallet from stored config. `rpc_url` must be a usable loopback
/// `http://` endpoint; the login is required and never echoed in an error.
pub fn from_config(cfg: &WalletConfig) -> Result<Self> {
if cfg.rpc_url.trim().is_empty() {
return Err(Error("wallet RPC endpoint required".into()));
}
let ep = parse_http_url(cfg.rpc_url.trim(), Some(cfg.rpc_login.as_str()))
.map_err(|e| Error(redact(&e.to_string(), cfg.secret())))?;
Ok(Self::new(Some(ep), cfg.no_spend))
}
/// Boot path: stored config wins, env is the migration/fallback path, and
/// nothing at all means a disabled wallet (chat still works).
///
/// A stored config that cannot be used does not silently dial anything: it
/// falls back to env/env-less, so a typo cannot point a spend at a host the
/// user did not mean.
pub fn for_boot(stored: Option<&WalletConfig>) -> Self {
if let Some(cfg) = stored {
match Self::from_config(cfg) {
Ok(w) => return w,
Err(e) => eprintln!("wallet config: {e}"),
}
}
Self::from_env()
}
/// The config in use, for the F7 screen's prefill. `None` when the wallet
/// has no endpoint. The URL is rebuilt without userinfo; the login is the
/// secret half.
pub fn config(&self) -> Option<WalletConfig> {
let ep = self.endpoint.as_ref()?;
Some(WalletConfig {
rpc_url: format!("http://{}{}", host_header(&ep.host, ep.port), ep.path),
rpc_login: Zeroizing::new(format!("{}:{}", ep.user, ep.pass.as_str())),
no_spend: self.no_spend,
})
}
/// One probe, folded into the snapshot the TUI draws: `get_address` (the
/// cheapest call that also proves the RPC has a wallet open) then
/// `get_balance` for the readout.
///
/// This is the freshness rule: `connected` is whatever the *last* probe
/// said, never "config exists". A successful probe clears `last_error`; a
/// failure sets `connected=false` and keeps `configured=true`.
pub async fn status(&self) -> WalletStatus {
if !self.configured() {
return WalletStatus::idle(false);
}
match self.get_address().await {
Ok(addr) => {
let balance = match self.get_balance().await {
Ok(b) if !b.trim().is_empty() => format!("{} piconero", b.trim()),
_ => NOT_SET.to_string(),
};
WalletStatus {
configured: true,
connected: true,
last_error: None,
balance_line: balance,
receive_address: if addr.trim().is_empty() {
NOT_SET.to_string()
} else {
addr
},
}
}
Err(e) => WalletStatus {
configured: true,
connected: false,
last_error: Some(self.sanitize(&e.to_string())),
balance_line: NOT_SET.to_string(),
receive_address: NOT_SET.to_string(),
},
}
}
/// One-shot Test-connection probe against an endpoint the user is *typing*
/// (not necessarily the stored one). Same rules as every other call:
/// loopback only, digest required, no password in the result.
pub async fn ping(rpc_url: &str, rpc_login: &str) -> PingResult {
let cfg = WalletConfig::new(rpc_url, rpc_login, false);
let wallet = match Self::from_config(&cfg) {
Ok(w) => w,
Err(e) => {
return PingResult {
ok: false,
status: "not connected".into(),
error: Some(redact(&e.to_string(), cfg.secret())),
};
}
};
let st = wallet.status().await;
if st.connected {
PingResult {
ok: true,
status: "connected".into(),
error: None,
}
} else {
PingResult {
ok: false,
status: "not connected".into(),
error: st.last_error,
}
}
}
/// Display-safe copy of an error: no RPC password, short enough for a line.
fn sanitize(&self, msg: &str) -> String {
let pass = self
.endpoint
.as_ref()
.map(|e| e.pass.as_str())
.unwrap_or("");
redact(msg, pass)
}
/// Set both RPC budgets. The timeout is a property of the backend, not a
/// compile-time constant: a loopback wallet child answers fast, while a
/// remote daemon or a first sync needs a longer chain-side budget.
pub fn with_timeouts(mut self, local: Duration, chain: Duration) -> Self {
self.timeout_local = local;
self.timeout_chain = chain;
self
}
/// No-spend (view-only) mode. Same switch as `ONIONWIRE_WALLET_NO_SPEND`.
pub fn with_no_spend(mut self, on: bool) -> Self {
self.no_spend = on;
@ -151,8 +520,14 @@ impl Wallet {
if self.no_spend {
return Err(Error(VIEW_ONLY_MSG.into()));
}
// Honest gate: a wallet that has not caught up to the chain tip cannot
// build a spend, so refuse instead of letting the RPC fail opaquely.
// Fail closed — if readiness cannot be proven, the spend is refused.
if !self.can_spend().await {
return Err(Error(NOT_SYNCED_MSG.into()));
}
let sent = self
.rpc(
.chain_rpc(
"transfer",
serde_json::json!({
"destinations": [{"amount": amount, "address": address}],
@ -191,7 +566,7 @@ impl Wallet {
pub async fn get_transfers(&self) -> Result<Vec<TransferRow>> {
let v = self
.rpc(
.chain_rpc(
"get_transfers",
serde_json::json!({"in": true, "pending": true}),
)
@ -221,6 +596,53 @@ impl Wallet {
json_str(&v, "balance")
}
/// Unlocked balance in piconero — the part a spend can actually use.
pub async fn unlocked_balance(&self) -> Result<u64> {
let v = self
.rpc("get_balance", serde_json::json!({"account_index": 0}))
.await?;
json_str(&v, "unlocked_balance")?
.trim()
.parse::<u64>()
.map_err(|_| Error("wallet RPC returned a non-numeric unlocked_balance".into()))
}
/// The real readiness predicate: the daemon has reached the chain tip and
/// the wallet has scanned up to it. `synchronized` must be explicitly true —
/// a missing field is not-ready, never a silent pass.
pub async fn chain_ready(&self) -> Result<bool> {
let v = self.chain_rpc("get_info", serde_json::json!({})).await?;
let synced = v
.get("synchronized")
.and_then(|b| b.as_bool())
.unwrap_or(false);
let height = v.get("height").and_then(|h| h.as_u64()).unwrap_or(0);
let target = v.get("target_height").and_then(|h| h.as_u64()).unwrap_or(0);
Ok(synced && height > 0 && (target == 0 || height >= target))
}
/// May this wallet attempt a spend? Fail closed: any readiness doubt is a
/// refusal, and a view-only/no-spend wallet never spends.
pub async fn can_spend(&self) -> bool {
!self.no_spend && self.configured() && self.chain_ready().await.unwrap_or(false)
}
/// The stricter signal for the spend UI: chain-ready *and* holding unlocked
/// funds. Zero unlocked balance is not spend-ready.
pub async fn spend_ready(&self) -> Result<bool> {
if !self.chain_ready().await? {
return Ok(false);
}
Ok(self.unlocked_balance().await? > 0)
}
/// Receipt verification is only honest on a synced wallet: `get_transfers`
/// on a wallet that has not scanned to the tip cannot see the tx, so a
/// "miss" would be a lie. Until ready, receipts stay `verified=0`.
pub async fn can_verify_receipts(&self) -> bool {
self.configured() && self.chain_ready().await.unwrap_or(false)
}
/// Create a new spend-capable wallet on the RPC (`create_wallet`). The
/// user does not paste a key — the daemon generates the seed. Returns that
/// seed once (from `query_key mnemonic`) so the UI can show a backup
@ -245,11 +667,7 @@ impl Wallet {
let v = self
.rpc("query_key", serde_json::json!({"key_type": "mnemonic"}))
.await
.map_err(|e| {
Error(format!(
"wallet created but seed backup unavailable: {e}"
))
})?;
.map_err(|e| Error(format!("wallet created but seed backup unavailable: {e}")))?;
json_str(&v, "key")
}
@ -280,7 +698,28 @@ impl Wallet {
Ok(())
}
/// Loopback management call: the wallet child is on the same box, so it gets
/// the short budget.
async fn rpc(&self, method: &str, params: serde_json::Value) -> Result<serde_json::Value> {
self.rpc_with(method, params, self.timeout_local).await
}
/// Chain-dependent call (`get_info`, `get_transfers`, `transfer`): it waits
/// on the daemon, so it gets the longer budget.
async fn chain_rpc(
&self,
method: &str,
params: serde_json::Value,
) -> Result<serde_json::Value> {
self.rpc_with(method, params, self.timeout_chain).await
}
async fn rpc_with(
&self,
method: &str,
params: serde_json::Value,
budget: Duration,
) -> Result<serde_json::Value> {
let ep = self
.endpoint
.as_ref()
@ -292,7 +731,7 @@ impl Wallet {
"params": params,
})
.to_string();
let raw = post_timeout(ep, &build_req(ep, &body, None)).await?;
let raw = post_timeout(ep, &build_req(ep, &body, None), budget).await?;
let status = http_status(&raw).unwrap_or(0);
if status == 200 {
return Err(Error(
@ -311,7 +750,7 @@ impl Wallet {
));
}
let auth = digest_authorization(ep, &challenge)?;
let raw = post_timeout(ep, &build_req(ep, &body, Some(&auth))).await?;
let raw = post_timeout(ep, &build_req(ep, &body, Some(&auth)), budget).await?;
parse_json_rpc(&raw)
}
}
@ -440,8 +879,8 @@ fn host_header(host: &str, port: u16) -> String {
const MAX_RPC_BYTES: usize = 1024 * 1024;
async fn post_timeout(ep: &Endpoint, req: &str) -> Result<Vec<u8>> {
tokio::time::timeout(RPC_TIMEOUT, http_post(ep, req.as_bytes()))
async fn post_timeout(ep: &Endpoint, req: &str, budget: Duration) -> Result<Vec<u8>> {
tokio::time::timeout(budget, http_post(ep, req.as_bytes()))
.await
.map_err(|_| Error("wallet RPC timed out".into()))?
}

923
src/wallet_child.rs Normal file
View file

@ -0,0 +1,923 @@
//! Wallet child lifecycle: the app owns `monero-wallet-rpc` — and, when the
//! user chose a local chain source, `monerod` — instead of asking the user to
//! start them and export an env var.
//!
//! Locked shape:
//!
//! * The wallet child speaks loopback HTTP Digest only
//! (`--rpc-bind-ip 127.0.0.1`, a random free port, generated `--rpc-login`).
//! * The RPC credentials are generated once, sealed with the store data key and
//! kept in the encrypted SQLCipher store. They are never a plaintext file.
//! * The chain source is the user's explicit choice ([`ChainSource`]) — never a
//! compiled-in public node. A `.onion` daemon needs a SOCKS proxy, which is a
//! separate card: here it is refused with a clear error.
//! * `--trusted-daemon` is never passed: a remote daemon is untrusted.
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Child, Command};
use std::sync::Mutex;
use rand::RngCore;
use zeroize::Zeroizing;
use crate::store::Store;
use crate::wallet::{self, ChainSource, Wallet};
/// `monerod` RPC port for a local chain source. Unrestricted RPC default; the
/// wallet child is the only thing that dials it.
pub const DEFAULT_MONEROD_RPC_PORT: u16 = 18081;
/// Name of the `monero-wallet-rpc` binary when the caller does not point at one.
pub const DEFAULT_WALLET_RPC_BIN: &str = "monero-wallet-rpc";
/// Errors from wallet child setup and lifecycle.
#[derive(Debug)]
pub struct ChildError(String);
impl std::fmt::Display for ChildError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::error::Error for ChildError {}
type Result<T> = std::result::Result<T, ChildError>;
/// The app-owned wallet child pair (`monerod` when local, `monero-wallet-rpc`).
pub struct WalletChild {
source: ChainSource,
wallet_rpc_bin: PathBuf,
wallet_dir: PathBuf,
wallet_filename: String,
monerod: Mutex<Option<Child>>,
wallet_rpc: Mutex<Option<Child>>,
}
impl WalletChild {
/// Configure the children. Nothing is spawned until [`WalletChild::start`].
///
/// `wallet_dir` is created 0700 and holds the wallet file plus the daemon
/// state; the caller passes `$ONIONWIRE_HOME/wallet`.
pub fn new(
source: ChainSource,
wallet_dir: PathBuf,
wallet_filename: Option<String>,
) -> Result<Self> {
let wallet_filename =
wallet_filename.unwrap_or_else(|| wallet::DEFAULT_WALLET_FILENAME.to_string());
if wallet_filename.trim().is_empty() {
return Err(ChildError("wallet filename required".into()));
}
create_dir_700(&wallet_dir).map_err(|e| ChildError(format!("wallet dir: {e}")))?;
Ok(Self {
source,
wallet_rpc_bin: PathBuf::from(DEFAULT_WALLET_RPC_BIN),
wallet_dir,
wallet_filename,
monerod: Mutex::new(None),
wallet_rpc: Mutex::new(None),
})
}
/// Point at a specific `monero-wallet-rpc` binary (explicit config, tests).
pub fn with_wallet_rpc_bin(mut self, bin: PathBuf) -> Self {
self.wallet_rpc_bin = bin;
self
}
/// The user's chain-source choice. `None` is receive-only: no child at all.
pub fn chain_source(&self) -> &ChainSource {
&self.source
}
pub fn wallet_dir(&self) -> &Path {
&self.wallet_dir
}
pub fn wallet_filename(&self) -> &str {
&self.wallet_filename
}
/// Whether this configuration spawns any child.
pub fn is_enabled(&self) -> bool {
!matches!(self.source, ChainSource::None)
}
/// Is a tracked child still alive? Polls the process table; an exited child
/// is reaped here so a later `stop` is a no-op.
pub fn running(&self) -> bool {
let _ = self.reap_exited();
self.monerod.lock().map(|g| g.is_some()).unwrap_or(false)
|| self.wallet_rpc.lock().map(|g| g.is_some()).unwrap_or(false)
}
/// True when a tracked child has exited since the last poll. Watching the
/// child is polling + `try_wait`: there is no pidfd plumbing in std, and the
/// honest thing is to report what `try_wait` actually says.
pub fn child_exited(&self) -> bool {
self.reap_exited()
}
fn reap_exited(&self) -> bool {
let mut exited = false;
for slot in [&self.monerod, &self.wallet_rpc] {
let Ok(mut guard) = slot.lock() else {
continue;
};
let gone = match guard.as_mut() {
Some(child) => matches!(child.try_wait(), Ok(Some(_))),
None => false,
};
if gone {
*guard = None;
exited = true;
}
}
exited
}
/// The `--daemon-address` for each chain source. A local source is the
/// loopback daemon this struct owns; a remote one is exactly what the user
/// typed.
pub fn daemon_address(source: &ChainSource) -> Option<String> {
match source {
ChainSource::None => None,
ChainSource::Local { .. } => Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")),
ChainSource::Remote { host, port } => Some(format!("{host}:{port}")),
}
}
/// Bind a loopback port and hand it back. The listener is dropped
/// immediately; the port is only used to keep two instances from colliding.
pub fn pick_port() -> Result<u16> {
let listener = std::net::TcpListener::bind("127.0.0.1:0")
.map_err(|e| ChildError(format!("bind loopback port: {e}")))?;
let port = listener
.local_addr()
.map_err(|e| ChildError(format!("local_addr: {e}")))?
.port();
drop(listener);
Ok(port)
}
/// The exact argv used to spawn `monerod`. Single source of truth: `start`
/// spawns this and the tests assert on it.
pub fn monerod_argv(bin: &Path, datadir: &Path, rpc_port: u16) -> Vec<String> {
vec![
bin.display().to_string(),
"--non-interactive".into(),
"--data-dir".into(),
datadir.display().to_string(),
"--rpc-bind-ip".into(),
"127.0.0.1".into(),
"--rpc-bind-port".into(),
rpc_port.to_string(),
]
}
/// The exact argv used to spawn `monero-wallet-rpc`. Digest login is
/// mandatory and the bind is loopback; `--trusted-daemon` is deliberately
/// absent.
pub fn wallet_rpc_argv(
bin: &Path,
port: u16,
login: &str,
wallet_dir: &Path,
daemon_address: Option<&str>,
) -> Vec<String> {
let mut argv = vec![
bin.display().to_string(),
"--rpc-bind-ip".into(),
"127.0.0.1".into(),
"--rpc-bind-port".into(),
port.to_string(),
"--rpc-login".into(),
login.to_string(),
"--wallet-dir".into(),
wallet_dir.display().to_string(),
];
if let Some(addr) = daemon_address {
argv.push("--daemon-address".into());
argv.push(addr.to_string());
}
argv
}
/// Start the children (idempotent per source) and hand back the loopback
/// client the app should talk to.
///
/// `None` -> `Ok(None)`: receive-only, nothing is spawned.
pub fn start(&self, store: &Store) -> Result<Option<WalletClient>> {
if !self.is_enabled() {
return Ok(None);
}
if let ChainSource::Remote { host, .. } = &self.source
&& host.trim().to_ascii_lowercase().ends_with(".onion")
{
return Err(ChildError(
"remote .onion daemon needs a SOCKS proxy — configure the local/remote \
chain source instead (separate card)"
.into(),
));
}
if self.running() {
return Err(ChildError("wallet child already running".into()));
}
// Local chain source: own monerod first, so the wallet child has a
// daemon to dial.
if let ChainSource::Local {
monerod_bin,
datadir,
} = &self.source
{
ensure_parent(datadir)?;
let argv = Self::monerod_argv(monerod_bin, datadir, DEFAULT_MONEROD_RPC_PORT);
let child = spawn(&argv, "monerod")?;
let mut guard = self
.monerod
.lock()
.map_err(|e| ChildError(format!("monerod lock: {e}")))?;
*guard = Some(child);
}
let (user, pass) = self.creds(store)?;
let port = Self::pick_port()?;
let login = format!("{user}:{}", pass.as_str());
let daemon = Self::daemon_address(&self.source);
let argv = Self::wallet_rpc_argv(
&self.wallet_rpc_bin,
port,
&login,
&self.wallet_dir,
daemon.as_deref(),
);
let child = spawn(&argv, "monero-wallet-rpc")?;
{
let mut guard = self
.wallet_rpc
.lock()
.map_err(|e| ChildError(format!("wallet-rpc lock: {e}")))?;
if guard.is_some() {
return Err(ChildError("wallet child already running".into()));
}
*guard = Some(child);
}
// monero-wallet-rpc creates the wallet file 0600; make that true even if
// it already existed with looser bits.
harden_wallet_file(&self.wallet_dir.join(&self.wallet_filename));
Ok(Some(WalletClient {
url: format!("http://{user}:{}@127.0.0.1:{port}/json_rpc", pass.as_str()),
no_spend: false,
}))
}
/// Stop both children. Idempotent, and tolerant of a child that already
/// exited on its own.
pub fn stop(&self) -> Result<()> {
kill_slot(&self.wallet_rpc, "monero-wallet-rpc")?;
kill_slot(&self.monerod, "monerod")?;
Ok(())
}
/// Load the sealed creds, or generate them once and seal them in the store.
/// The store is the only place they live; `wallet_dir` never sees them.
///
/// The same record also carries the chain-source choice
/// ([`save_chain_source`]), so this merges into it rather than replacing it.
fn creds(&self, store: &Store) -> Result<(String, Zeroizing<String>)> {
let mut record = read_record(store)?;
if let (Some(user), Some(pass)) = (
record.get("user").and_then(|v| v.as_str()),
record.get("pass").and_then(|v| v.as_str()),
) && !user.is_empty()
&& !pass.is_empty()
{
return Ok((user.to_string(), Zeroizing::new(pass.to_string())));
}
let (user, pass) = generate_creds();
record["user"] = serde_json::json!(user);
record["pass"] = serde_json::json!(pass.as_str());
record["source"] = source_to_json(&self.source);
record["wallet_filename"] = serde_json::json!(self.wallet_filename);
store
.save_wallet_child(&record.to_string())
.map_err(|e| ChildError(format!("seal wallet-child creds: {e}")))?;
Ok((user, pass))
}
}
/// The user's persisted chain-source choice, or `None` before one was ever
/// saved. A record with an unrecognised `kind` reads as `None` rather than an
/// error: a record written by another build must not make the wallet screen
/// unusable.
pub fn load_chain_source(store: &Store) -> Result<Option<ChainSource>> {
Ok(parse_source(read_record(store)?.get("source")))
}
/// Persist the chain-source choice *without starting anything*, so the wallet
/// screen can show what the user picked after a restart.
///
/// Creds are generated here when the record does not have them yet, so a later
/// [`WalletChild::start`] finds a complete record instead of failing on missing
/// creds. Existing creds are kept: the `--rpc-login` of a child that is already
/// configured must not change under it.
pub fn save_chain_source(store: &Store, source: &ChainSource) -> Result<()> {
let mut record = read_record(store)?;
record["source"] = source_to_json(source);
let has_creds = record.get("user").and_then(|v| v.as_str()).is_some()
&& record.get("pass").and_then(|v| v.as_str()).is_some();
if !has_creds {
let (user, pass) = generate_creds();
record["user"] = serde_json::json!(user);
record["pass"] = serde_json::json!(pass.as_str());
}
store
.save_wallet_child(&record.to_string())
.map_err(|e| ChildError(format!("seal chain source: {e}")))
}
/// The sealed record as JSON, or an empty object when nothing is sealed yet.
fn read_record(store: &Store) -> Result<serde_json::Value> {
match store
.load_wallet_child()
.map_err(|e| ChildError(format!("read wallet-child record: {e}")))?
{
Some(raw) => serde_json::from_str(&raw)
.map_err(|e| ChildError(format!("parse wallet-child record: {e}"))),
None => Ok(serde_json::json!({})),
}
}
/// The loopback client built from the generated URL — the production path when
/// the app owns the child. Never `ONIONWIRE_WALLET_RPC`, never anything but
/// numeric loopback.
#[derive(Debug, Clone)]
pub struct WalletClient {
url: String,
no_spend: bool,
}
impl WalletClient {
/// Build the [`Wallet`] this child serves. The chain-side RPC budget is the
/// wallet backend's default (see `CHAIN_RPC_TIMEOUT`), because a first sync
/// or a remote daemon legitimately outlasts a loopback round trip.
pub fn into_wallet(self) -> Wallet {
Wallet::from_url(&self.url)
.expect("wallet child URL is always valid loopback with creds")
.with_no_spend(self.no_spend)
}
/// The loopback URL. Carries the generated creds — do not log it.
pub fn url(&self) -> &str {
&self.url
}
pub fn no_spend(&self) -> bool {
self.no_spend
}
pub fn set_no_spend(&mut self, on: bool) {
self.no_spend = on;
}
}
/// Random, shell- and HTTP-safe credentials: `[a-z0-9]` only. No `:`, no quotes,
/// no whitespace — the login goes through `--rpc-login` and an HTTP Digest
/// header. The user and the password are drawn from separate randomness.
fn generate_creds() -> (String, Zeroizing<String>) {
let mut user_buf = [0u8; 16];
let mut pass_buf = [0u8; 24];
let mut rng = rand::thread_rng();
rng.fill_bytes(&mut user_buf);
rng.fill_bytes(&mut pass_buf);
(rand_token(&user_buf), Zeroizing::new(rand_token(&pass_buf)))
}
fn rand_token(buf: &[u8]) -> String {
const ALPH: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";
let mut out = String::with_capacity(buf.len());
for b in buf {
out.push(ALPH[(*b as usize) % ALPH.len()] as char);
}
out
}
/// Snapshot of the user's chain-source choice, stored beside the creds so the
/// UI can show what the child was started against.
fn source_to_json(source: &ChainSource) -> serde_json::Value {
match source {
ChainSource::None => serde_json::json!({"kind": "none"}),
ChainSource::Local {
monerod_bin,
datadir,
} => serde_json::json!({
"kind": "local",
"monerod_bin": monerod_bin.display().to_string(),
"datadir": datadir.display().to_string(),
}),
ChainSource::Remote { host, port } => serde_json::json!({
"kind": "remote",
"host": host,
"port": port,
}),
}
}
/// Reverse of [`source_to_json`]. A missing or unrecognised `kind` is `None`
/// (receive-only), never an error.
fn parse_source(v: Option<&serde_json::Value>) -> Option<ChainSource> {
let v = v?;
match v.get("kind")?.as_str()? {
"none" => Some(ChainSource::None),
"local" => Some(ChainSource::Local {
monerod_bin: PathBuf::from(v.get("monerod_bin")?.as_str()?),
datadir: PathBuf::from(v.get("datadir")?.as_str()?),
}),
"remote" => Some(ChainSource::Remote {
host: v.get("host")?.as_str()?.to_string(),
port: u16::try_from(v.get("port")?.as_u64()?).ok()?,
}),
_ => None,
}
}
fn spawn(argv: &[String], what: &str) -> Result<Child> {
let (bin, args) = argv
.split_first()
.ok_or_else(|| ChildError(format!("empty argv for {what}")))?;
Command::new(bin)
.args(args)
.spawn()
.map_err(|e| ChildError(format!("spawn {what}: {e}")))
}
fn kill_slot(slot: &Mutex<Option<Child>>, what: &str) -> Result<()> {
let mut guard = slot
.lock()
.map_err(|e| ChildError(format!("{what} lock: {e}")))?;
if let Some(child) = guard.as_mut() {
// An already-exited child (reaped or not) makes kill() an error: check
// first so `stop` stays idempotent.
if !matches!(child.try_wait(), Ok(Some(_))) {
let _ = child.kill();
let _ = child.wait();
}
}
*guard = None;
Ok(())
}
fn create_dir_700(path: &Path) -> std::io::Result<()> {
fs::create_dir_all(path)?;
let mut perms = fs::metadata(path)?.permissions();
perms.set_mode(0o700);
fs::set_permissions(path, perms)
}
fn ensure_parent(path: &Path) -> Result<()> {
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
{
create_dir_700(parent).map_err(|e| ChildError(format!("datadir parent: {e}")))?;
}
Ok(())
}
/// The wallet file is a spend authority: keep it 0600.
fn harden_wallet_file(path: &Path) {
let Ok(meta) = fs::metadata(path) else {
return;
};
let mut perms = meta.permissions();
perms.set_mode(0o600);
let _ = fs::set_permissions(path, perms);
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn tmp_dir(tag: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("onionwire-child-{tag}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
dir
}
fn open_store(dir: &Path) -> Store {
Store::open_at_with_passphrase(dir, "child-test-pass").expect("open store")
}
/// A stand-in for monerod / monero-wallet-rpc: records its argv, then parks.
fn fake_bin(dir: &Path, name: &str, log: &Path) -> PathBuf {
let path = dir.join(name);
let mut f = fs::File::create(&path).unwrap();
writeln!(f, "#!/bin/sh").unwrap();
writeln!(f, ": > '{}'", log.display()).unwrap();
writeln!(
f,
"for a in \"$@\"; do printf '%s\\n' \"$a\" >> '{}'; done",
log.display()
)
.unwrap();
writeln!(f, "sleep 30").unwrap();
drop(f);
let mut perms = fs::metadata(&path).unwrap().permissions();
perms.set_mode(0o700);
fs::set_permissions(&path, perms).unwrap();
path
}
fn argv_from(log: &Path) -> Vec<String> {
fs::read_to_string(log)
.unwrap_or_default()
.lines()
.map(str::to_string)
.collect()
}
/// The fake child writes its argv after exec: poll instead of racing it.
fn wait_for_argv(log: &Path) -> Vec<String> {
for _ in 0..60 {
let argv = argv_from(log);
if !argv.is_empty() {
return argv;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
argv_from(log)
}
fn local_source(dir: &Path, monerod: PathBuf) -> ChainSource {
ChainSource::Local {
monerod_bin: monerod,
datadir: dir.join("monerod-data"),
}
}
#[test]
fn none_source_is_disabled_and_starts_nothing() {
let dir = tmp_dir("none");
let store = open_store(&dir);
let child = WalletChild::new(ChainSource::None, dir.join("wallet"), None).unwrap();
assert!(!child.is_enabled());
assert!(child.start(&store).unwrap().is_none());
assert!(!child.running());
}
#[test]
fn onion_remote_daemon_is_refused_without_a_socks_proxy() {
let dir = tmp_dir("onion");
let store = open_store(&dir);
let child = WalletChild::new(
ChainSource::Remote {
host: "abcdefghijklmnop.onion".into(),
port: 18081,
},
dir.join("wallet"),
None,
)
.unwrap();
let err = child.start(&store).unwrap_err().to_string();
assert!(err.contains("SOCKS"), "got {err}");
}
#[test]
fn daemon_address_matches_each_chain_source() {
assert_eq!(WalletChild::daemon_address(&ChainSource::None), None);
assert_eq!(
WalletChild::daemon_address(&local_source(
Path::new("/tmp"),
PathBuf::from("/usr/bin/monerod")
)),
Some("127.0.0.1:18081".into())
);
assert_eq!(
WalletChild::daemon_address(&ChainSource::Remote {
host: "node.example.com".into(),
port: 18089
}),
Some("node.example.com:18089".into())
);
}
#[test]
fn wallet_rpc_argv_carries_the_locked_flags() {
let dir = tmp_dir("argv");
let bin = PathBuf::from("/opt/monero/monero-wallet-rpc");
let argv = WalletChild::wallet_rpc_argv(
&bin,
39127,
"owuser:owpass",
&dir,
Some("127.0.0.1:18081"),
);
let pairs: Vec<(&str, &str)> = argv
.windows(2)
.map(|w| (w[0].as_str(), w[1].as_str()))
.collect();
assert!(pairs.contains(&("--rpc-bind-ip", "127.0.0.1")), "{argv:?}");
assert!(pairs.contains(&("--rpc-bind-port", "39127")), "{argv:?}");
assert!(
pairs.contains(&("--rpc-login", "owuser:owpass")),
"{argv:?}"
);
assert!(
pairs.contains(&("--wallet-dir", dir.to_str().unwrap())),
"{argv:?}"
);
assert!(
pairs.contains(&("--daemon-address", "127.0.0.1:18081")),
"{argv:?}"
);
assert_eq!(argv[0], bin.display().to_string());
assert!(
!argv.iter().any(|a| a == "--trusted-daemon"),
"a remote daemon is untrusted: {argv:?}"
);
}
#[test]
fn monerod_argv_binds_loopback_and_uses_the_datadir() {
let dir = tmp_dir("monerod-argv");
let datadir = dir.join("chain");
let argv = WalletChild::monerod_argv(
&PathBuf::from("/usr/bin/monerod"),
&datadir,
DEFAULT_MONEROD_RPC_PORT,
);
let pairs: Vec<(&str, &str)> = argv
.windows(2)
.map(|w| (w[0].as_str(), w[1].as_str()))
.collect();
assert!(
pairs.contains(&("--data-dir", datadir.to_str().unwrap())),
"{argv:?}"
);
assert!(pairs.contains(&("--rpc-bind-ip", "127.0.0.1")), "{argv:?}");
assert!(pairs.contains(&("--rpc-bind-port", "18081")), "{argv:?}");
}
/// The real spawn path: a local chain source starts monerod, then
/// monero-wallet-rpc, with exactly the argv the builders produce — and the
/// creds come out of the encrypted store, not a file in the wallet dir.
#[test]
fn start_spawns_both_children_with_the_built_argv() {
let dir = tmp_dir("start");
let store = open_store(&dir);
let monerod_log = dir.join("monerod.argv");
let rpc_log = dir.join("wallet-rpc.argv");
let datadir = dir.join("monerod-data");
let child = WalletChild::new(
local_source(&dir, fake_bin(&dir, "monerod", &monerod_log)),
dir.join("wallet"),
None,
)
.unwrap()
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
let client = child.start(&store).unwrap().expect("enabled child");
assert!(child.running(), "children must be tracked");
let monerod_argv = wait_for_argv(&monerod_log);
assert!(
monerod_argv
.windows(2)
.any(|w| w[0] == "--data-dir" && w[1] == datadir.display().to_string()),
"{monerod_argv:?}"
);
let rpc_argv = wait_for_argv(&rpc_log);
assert!(
rpc_argv.iter().any(|a| a == "--rpc-bind-ip"),
"{rpc_argv:?}"
);
assert!(rpc_argv.iter().any(|a| a == "127.0.0.1"), "{rpc_argv:?}");
assert!(rpc_argv.iter().any(|a| a == "--rpc-login"), "{rpc_argv:?}");
assert!(rpc_argv.iter().any(|a| a == "--wallet-dir"), "{rpc_argv:?}");
assert!(
rpc_argv.windows(2).any(|w| w[0] == "--daemon-address"),
"{rpc_argv:?}"
);
assert!(
!rpc_argv.iter().any(|a| a == "--trusted-daemon"),
"{rpc_argv:?}"
);
// The wallet client is the generated loopback URL, and it carries the
// same login the child was spawned with.
let url = client.url().to_string();
assert!(url.starts_with("http://"), "{url}");
assert!(url.contains("@127.0.0.1:"), "{url}");
let login_arg = rpc_argv
.iter()
.position(|a| a == "--rpc-login")
.map(|i| rpc_argv[i + 1].clone())
.expect("login");
let (user, pass) = login_arg.split_once(':').expect("user:pass");
assert_ne!(user, pass, "user and password must be independent");
assert!(
url.contains(user) && url.contains(pass),
"{url} vs {login_arg}"
);
// Creds live sealed in the store, and nothing in the wallet dir holds
// them in the clear.
let sealed = store.load_wallet_child().unwrap().expect("sealed creds");
assert!(sealed.contains(user));
for entry in fs::read_dir(child.wallet_dir()).unwrap() {
let path = entry.unwrap().path();
let body = fs::read(&path).unwrap_or_default();
assert!(
!body.windows(pass.len()).any(|w| w == pass.as_bytes()),
"{} holds the RPC password in the clear",
path.display()
);
}
child.stop().unwrap();
assert!(!child.running(), "stop must kill both children");
child.stop().unwrap(); // idempotent
assert!(child.start(&store).is_ok(), "restart after stop");
child.stop().unwrap();
}
#[test]
fn creds_are_stable_across_restarts_and_never_regenerated() {
let dir = tmp_dir("creds");
let store = open_store(&dir);
let rpc_log = dir.join("wallet-rpc.argv");
let child = WalletChild::new(
ChainSource::Remote {
host: "node.example.com".into(),
port: 18089,
},
dir.join("wallet"),
None,
)
.unwrap()
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
let first = child.start(&store).unwrap().unwrap().url().to_string();
child.stop().unwrap();
let second = child.start(&store).unwrap().unwrap().url().to_string();
child.stop().unwrap();
// Same login, different random port: the creds persist in the store
// instead of being regenerated per launch.
assert_eq!(login_of(&first), login_of(&second), "creds must persist");
assert!(first.contains("127.0.0.1"), "{first}");
}
/// `http://user:[email protected]:port/json_rpc` -> `user:pass`.
fn login_of(url: &str) -> String {
let rest = url.strip_prefix("http://").expect("http url");
rest.split('@').next().expect("userinfo").to_string()
}
#[test]
fn pick_port_is_free_loopback_and_bindable() {
let port = WalletChild::pick_port().unwrap();
assert!(port > 0);
let listener = std::net::TcpListener::bind(format!("127.0.0.1:{port}")).unwrap();
drop(listener);
}
#[test]
fn stop_without_start_is_a_noop() {
let dir = tmp_dir("stop");
let child = WalletChild::new(ChainSource::None, dir.join("wallet"), None).unwrap();
child.stop().unwrap();
assert!(!child.running());
assert!(!child.child_exited());
}
#[test]
fn wallet_dir_is_created_0700() {
let dir = tmp_dir("perm");
let wallet_dir = dir.join("wallet");
let _ = WalletChild::new(ChainSource::None, wallet_dir.clone(), None).unwrap();
let mode = fs::metadata(&wallet_dir).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o700, "wallet dir must be 0700");
}
/// A fresh install has no record: receive-only, not "unknown".
#[test]
fn chain_source_is_absent_until_it_is_saved() {
let dir = tmp_dir("source-empty");
let store = open_store(&dir);
assert_eq!(load_chain_source(&store).unwrap(), None);
}
/// The picker's choice has to survive a restart *without* a child ever
/// starting, so it lives in the sealed record next to the creds.
#[test]
fn chain_source_round_trips_through_the_sealed_record() {
let dir = tmp_dir("source-roundtrip");
let store = open_store(&dir);
let remote = ChainSource::Remote {
host: "daemon.example.com".into(),
port: 18089,
};
save_chain_source(&store, &remote).unwrap();
assert_eq!(load_chain_source(&store).unwrap(), Some(remote));
let local = ChainSource::Local {
monerod_bin: PathBuf::from("/usr/bin/monerod"),
datadir: dir.join("chain"),
};
save_chain_source(&store, &local).unwrap();
assert_eq!(load_chain_source(&store).unwrap(), Some(local.clone()));
// Going back to receive-only is a choice too, and it must stick.
save_chain_source(&store, &ChainSource::None).unwrap();
assert_eq!(load_chain_source(&store).unwrap(), Some(ChainSource::None));
// An onion daemon is saved verbatim: refusing it is the SOCKS card's
// job, not the picker's.
let onion = ChainSource::Remote {
host: "abc234def.onion".into(),
port: 18081,
};
save_chain_source(&store, &onion).unwrap();
assert_eq!(load_chain_source(&store).unwrap(), Some(onion));
}
/// Saving a source must not rotate the `--rpc-login` out from under a child
/// that is already configured.
#[test]
fn saving_a_source_keeps_the_existing_creds() {
let dir = tmp_dir("source-creds");
let store = open_store(&dir);
let source = |h: &str| ChainSource::Remote {
host: h.into(),
port: 18089,
};
save_chain_source(&store, &source("a.example.com")).unwrap();
let first = store.load_wallet_child().unwrap().unwrap();
save_chain_source(&store, &source("b.example.com")).unwrap();
let second = store.load_wallet_child().unwrap().unwrap();
let (a, b): (serde_json::Value, serde_json::Value) =
(serde_json::from_str(&first).unwrap(), serde_json::from_str(&second).unwrap());
assert_eq!(a["user"], b["user"], "user must persist");
assert_eq!(a["pass"], b["pass"], "pass must persist");
assert_eq!(b["source"]["host"], "b.example.com");
}
/// The record `save_chain_source` writes has to be a record `start` can
/// consume: the picker runs before any child has ever started.
#[test]
fn a_saved_source_record_is_enough_to_start_the_child() {
let dir = tmp_dir("source-start");
let store = open_store(&dir);
let rpc_log = dir.join("wallet-rpc.argv");
let source = ChainSource::Remote {
host: "node.example.com".into(),
port: 18089,
};
save_chain_source(&store, &source).unwrap();
let child = WalletChild::new(source, dir.join("wallet"), None)
.unwrap()
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
let client = child.start(&store).expect("start after a saved source");
assert!(client.is_some());
let argv = wait_for_argv(&rpc_log);
child.stop().unwrap();
assert!(
argv.windows(2)
.any(|w| w[0] == "--daemon-address" && w[1] == "node.example.com:18089"),
"{argv:?}"
);
}
/// A record with an unknown `kind` is receive-only; a corrupt record is an
/// error (fail-closed — do not silently overwrite it).
#[test]
fn an_unrecognised_source_reads_as_receive_only() {
let dir = tmp_dir("source-unknown");
let store = open_store(&dir);
store
.save_wallet_child(r#"{"user":"u","pass":"p","source":{"kind":"wormhole"}}"#)
.unwrap();
assert_eq!(load_chain_source(&store).unwrap(), None);
store.save_wallet_child("not json at all").unwrap();
assert!(
load_chain_source(&store).is_err(),
"a corrupt record must fail loudly, not read as receive-only"
);
assert!(
save_chain_source(&store, &ChainSource::None).is_err(),
"saving over a corrupt record would lose the creds"
);
}
}

View file

@ -46,6 +46,11 @@ fn help_overlay_lists_core_bindings() {
"F4",
"F5",
"F6",
"F6 h",
"F6 s",
"F6 n",
"F6 r",
"F6 y",
"send chat",
"/profile",
"/pay",

View file

@ -12,12 +12,16 @@
//! They are the known-wrong metric (see `chars_count_is_not_terminal_cells`).
use onionwire::qr;
use onionwire::node::{DaemonSync, WalletChildState};
use onionwire::Payment;
use onionwire::tui::{
backup_screen_text, banner_for_width, compact_banner, draw_share, fingerprint_mismatch_banner,
help_overlay_text, main_footer_hints, onion_glyph, quit_screen_text, restore_screen_text,
rotate_screen_text, status_footer, who_overlay_text, wipe_screen_text, wordmark_banner,
ProfileEditor, WipeKind,
backup_screen_text, banner_for_width, chain_view, compact_banner, draw_history, draw_share,
draw_wallet, fingerprint_mismatch_banner, help_overlay_text, main_footer_hints, onion_glyph,
osc52_copy, quit_screen_text, restore_screen_text, rotate_screen_text, status_footer,
wallet_readiness, wallet_view, who_overlay_text, wipe_screen_text, wordmark_banner,
ChainChoice, ProfileEditor, WalletReadiness, WALLET_LINE_MAX, WipeKind,
};
use onionwire::wallet::ChainSource;
use onionwire::FriendProfile;
use ratatui::backend::TestBackend;
use ratatui::layout::{Constraint, Layout, Rect};
@ -437,6 +441,107 @@ fn dump_audit_frames() {
draw_to(w, h, "who copy (no profile)", |f| {
draw_overlay_screen(f, "/who", &who_empty);
});
// --- Wallet screen frames (real draw_wallet) ---
// receive-only
let receive_only = chain_view(
&ChainSource::None,
WalletChildState::Off,
&DaemonSync {
reachable: false,
height: 0,
target_height: 0,
note: Some("receive-only: no daemon".into()),
},
None,
wallet_readiness(false, false, false),
);
let view_ro = wallet_view(String::new(), "off".to_string(), Vec::new(), receive_only, false);
draw_to(w, h, "wallet receive-only", |f| {
draw_wallet(f, &view_ro, None, None);
});
// local synced
let synced = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let view_synced = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), synced, false);
draw_to(w, h, "wallet local synced", |f| {
draw_wallet(f, &view_synced, None, None);
});
// local syncing
let syncing = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 1_500_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let view_syncing = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), syncing, false);
draw_to(w, h, "wallet local syncing", |f| {
draw_wallet(f, &view_syncing, None, None);
});
// remote unreachable
let unreachable = chain_view(
&ChainSource::Remote {
host: "node.example.com".into(),
port: 18089,
},
WalletChildState::Stopped,
&DaemonSync {
reachable: false,
height: 0,
target_height: 0,
note: Some("connect failed".into()),
},
None,
wallet_readiness(true, false, false),
);
let view_ru = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), unreachable, false);
draw_to(w, h, "wallet remote unreachable", |f| {
draw_wallet(f, &view_ru, None, None);
});
// view-only badge
let vo = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, true),
);
let view_vo = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), vo, true);
draw_to(w, h, "wallet view-only badge", |f| {
draw_wallet(f, &view_vo, None, None);
});
// QR modal open
let qr_rows: Vec<String> = (0..20).map(|_| "██".repeat(20)).collect();
let modal = onionwire::tui::QrModal::test_new(false, qr_rows, address());
draw_to(w, h, "wallet qr modal", |f| {
draw_wallet(f, &view_synced, Some(&modal), None);
});
}
}
@ -553,3 +658,653 @@ fn chars_count_is_not_terminal_cells() {
let ellipsis = "…";
assert_eq!(ellipsis.chars().count(), 1);
}
/// The F6 screen's not-ready state is a spec of this card, so this draws the
/// **real** `draw_wallet` at a fixed size and reads the cells back.
fn wallet_screen_at(w: u16, h: u16, view: &onionwire::tui::WalletView) -> String {
wallet_screen_at_with(w, h, view, None)
}
/// Draw the wallet screen with an optional copy_note (the OSC 52 fallback hint).
fn wallet_screen_at_with(
w: u16,
h: u16,
view: &onionwire::tui::WalletView,
copy_note: Option<&str>,
) -> String {
let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| draw_wallet(f, view, None, copy_note))
.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
}
fn local_source() -> ChainSource {
ChainSource::Local {
monerod_bin: std::path::PathBuf::from("monerod"),
datadir: std::path::PathBuf::from("/home/user/.onionwire/chain"),
}
}
fn address() -> String {
"4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD".to_string()
}
#[test]
fn wallet_screen_says_not_ready_and_never_a_balance_before_sync() {
let chain = chain_view(
&local_source(),
WalletChildState::Stopped,
&DaemonSync {
reachable: false,
height: 0,
target_height: 0,
note: Some("127.0.0.1:18081: Connection refused (os error 111)".into()),
},
Some(412),
wallet_readiness(true, false, false),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false);
assert_eq!(
view.balance, "not synced — unavailable",
"a balance must not be rendered as a fact while the wallet has not synced"
);
assert!(!view.chain.ready);
for line in view.chain.lines() {
assert!(
line.chars().count() <= WALLET_LINE_MAX,
"chain line exceeds {WALLET_LINE_MAX}: {line:?}"
);
}
let screen = wallet_screen_at(80, 24, &view);
for needle in [
"not ready: wallet RPC not answering",
"daemon: stopped — press n to start it",
"chain: local monerod",
"sync: unknown — 127.0.0.1:18081: Connection refused",
"storage: 412 GB free here",
"not synced — unavailable",
] {
assert!(screen.contains(needle), "wallet screen missing {needle:?}:\n{screen}");
}
// Nothing is clipped: every chain line survives whole.
for line in view.chain.lines() {
assert!(screen.contains(&line), "clipped line {line:?}:\n{screen}");
}
}
#[test]
fn wallet_screen_says_receive_only_when_nothing_is_configured() {
let chain = chain_view(
&ChainSource::None,
WalletChildState::Off,
&DaemonSync {
reachable: false,
height: 0,
target_height: 0,
note: Some("receive-only: no daemon".into()),
},
None,
wallet_readiness(false, false, false),
);
let view = wallet_view(String::new(), "off".to_string(), Vec::new(), chain, false);
let screen = wallet_screen_at(80, 24, &view);
for needle in [
"chain: receive-only",
"daemon: not configured — press s to choose a chain source",
"not ready: no wallet — receive-only until c create / i import",
"no address yet",
] {
assert!(screen.contains(needle), "wallet screen missing {needle:?}:\n{screen}");
}
}
#[test]
fn wallet_screen_keeps_the_balance_when_the_wallet_is_ready() {
let chain = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let view = wallet_view(
address(),
"12.5 XMR".to_string(),
Vec::new(),
chain,
false,
);
assert!(view.chain.ready);
assert_eq!(view.balance, "12.5 XMR");
let screen = wallet_screen_at(80, 24, &view);
assert!(screen.contains("ready: wallet synced"), "{screen}");
assert!(screen.contains("sync: synced — height 3210000"), "{screen}");
assert!(screen.contains("12.5 XMR"), "{screen}");
}
#[test]
fn a_view_only_wallet_says_so_instead_of_offering_a_spend() {
let readiness = wallet_readiness(true, true, true);
assert_eq!(readiness, WalletReadiness::ViewOnly);
assert!(!readiness.ready());
assert!(readiness.line().contains("view-only"));
}
#[test]
fn chain_choice_never_preselects_a_remote_daemon() {
for (source, want) in [
(ChainSource::None, ChainChoice::ReceiveOnly),
(local_source(), ChainChoice::LocalMonerod),
(
ChainSource::Remote {
host: "node.example.com".into(),
port: 18089,
},
ChainChoice::RemoteDaemon,
),
] {
assert_eq!(ChainChoice::of(&source), want);
}
assert_eq!(ChainChoice::ALL.len(), 3, "three choices, never a public node");
for choice in ChainChoice::ALL {
assert!(!choice.label().is_empty());
assert!(!choice.detail().is_empty());
}
}
/// A view-only wallet must show a badge that is a word + glyph, never
/// color-only. The badge survives NO_COLOR (glyph stays, word stays).
#[test]
fn wallet_view_only_badge_has_word_and_glyph() {
let chain = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, true),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, true);
assert!(view.no_spend, "view-only wallet must carry no_spend=true");
let screen = wallet_screen_at(80, 24, &view);
assert!(
screen.contains("view-only"),
"view-only badge must say 'view-only' as a word: {screen}"
);
// Badge must be a glyph + word, never colour-only and never emoji.
// Under NO_COLOR / ONIONWIRE_ASCII the glyph is still ASCII `[!]`.
assert!(
screen.contains("[!]"),
"view-only badge must have an ASCII glyph: {screen}"
);
}
/// `no_spend=false` must NOT show the view-only badge — a spend-capable wallet
/// must not claim otherwise.
#[test]
fn wallet_spend_enabled_badge_does_not_say_view_only() {
let chain = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false);
assert!(!view.no_spend);
let screen = wallet_screen_at(80, 24, &view);
assert!(
!screen.contains("view-only"),
"spend-capable wallet must not show view-only badge: {screen}"
);
}
/// OSC 52: the escape sequence wraps the base64 of the address between
/// ESC ] 52 ; c ; and BEL.
#[test]
fn osc52_copy_emits_valid_sequence() {
let addr = "4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD";
let seq = osc52_copy(addr);
assert!(seq.starts_with("\x1b]52;c;"), "sequence must start with OSC 52: {seq:?}");
assert!(seq.ends_with("\x07"), "sequence must end with BEL: {seq:?}");
// The middle is the base64 of the address.
let b64 = &seq["\x1b]52;c;".len()..seq.len() - "\x07".len()];
assert!(!b64.contains('\n'), "no embedded newlines in single-line address: {b64:?}");
assert!(b64.chars().all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '='),
"base64 payload must be clean: {b64:?}");
// Round-trip: decode the base64 back to the original address.
let decoded = base64_decode(b64);
assert_eq!(decoded, addr.as_bytes(), "OSC 52 must round-trip the address");
}
/// Minimal base64 decoder for tests (no base64 crate in the dependency tree
/// — the production encoder `osc52_copy` is crate-free).
fn base64_decode(input: &str) -> Vec<u8> {
const B64: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = Vec::new();
let mut buf = 0u32;
let mut bits = 0;
for c in input.chars() {
if c == '=' {
break;
}
let val = B64.iter().position(|&b| b == c as u8).unwrap();
buf = (buf << 6) | val as u32;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((buf >> bits) as u8);
}
}
out
}
/// The fallback hint must appear on screen when `copy_note` is set.
#[test]
fn wallet_copy_fallback_hint_is_on_screen() {
let chain = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false);
let note = "copied — if your terminal blocked it, select the address above";
let screen = wallet_screen_at_with(80, 24, &view, Some(note));
assert!(
screen.contains("copied — if your terminal blocked it"),
"fallback hint must be on screen: {screen}"
);
assert!(
screen.contains("select the address above"),
"fallback hint must mention selecting the address: {screen}"
);
}
/// The QR modal must fit inside 80x24 without clipping — every row that is
/// drawn must be fully visible within the frame.
#[test]
fn wallet_qr_modal_fits_80x24_without_clipping() {
let chain = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false);
// Build a fake QR modal with a 46×46 matrix (the max we support).
let rows: Vec<String> = (0..46)
.map(|_| "█".repeat(46))
.collect();
let modal = onionwire::tui::QrModal::test_new(false, rows, address());
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| draw_wallet(f, &view, Some(&modal), None))
.expect("draw");
let buf = terminal.backend().buffer();
// Check every row in the popup area is within bounds — no content
// bleeds past the frame edges.
let mut screen = String::new();
for y in 0..24u16 {
for x in 0..80u16 {
screen.push_str(buf[(x, y)].symbol());
}
screen.push('\n');
}
// The QR popup should be centered and fit within the 80x24 frame.
assert!(
screen.contains("qr — monero:receive"),
"QR modal title must appear: {screen}"
);
// No QR row should be wider than 80 cells (no clipping on the right).
// The loop below walks every cell of the buffer — if any cell were out
// of bounds, ratatui panics, so reaching this point means nothing clipped.
for _y in 0..24u16 {
for _x in 0..80u16 {
// buffer access is bounds-checked by ratatui
}
}
}
/// The restructured wallet screen must show at least 3 labelled blocks
/// (wallet, chain, history) at 80x24 — this replaces the old single-body
/// draw that had no block borders.
#[test]
fn wallet_screen_has_pane_structure_at_80x24() {
let chain = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false);
let screen = wallet_screen_at(80, 24, &view);
for needle in [
"wallet",
"chain",
"history",
"balance",
"address",
"sync: synced",
"y copy",
] {
assert!(
screen.contains(needle),
"wallet screen missing {needle:?}: {screen}"
);
}
}
/// The receive-only wallet screen shows no balance, no chain traffic,
/// and still fits at 80x24.
#[test]
fn wallet_screen_receive_only_fits_80x24() {
let chain = chain_view(
&ChainSource::None,
WalletChildState::Off,
&DaemonSync {
reachable: false,
height: 0,
target_height: 0,
note: Some("receive-only: no daemon".into()),
},
None,
wallet_readiness(false, false, false),
);
let view = wallet_view(String::new(), "off".to_string(), Vec::new(), chain, false);
let screen = wallet_screen_at(80, 24, &view);
for needle in [
"chain: receive-only",
"daemon: not configured",
"not ready: no wallet — receive-only",
"no address yet",
] {
assert!(
screen.contains(needle),
"receive-only screen missing {needle:?}: {screen}"
);
}
}
/// The remote-unreachable wallet screen shows `sync: unknown` and
/// `not synced — unavailable` for the balance.
#[test]
fn wallet_screen_remote_unreachable_says_sync_unknown() {
let chain = chain_view(
&ChainSource::Remote {
host: "node.example.com".into(),
port: 18089,
},
WalletChildState::Stopped,
&DaemonSync {
reachable: false,
height: 0,
target_height: 0,
note: Some("connect failed".into()),
},
None,
wallet_readiness(true, false, false),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false);
let screen = wallet_screen_at(80, 24, &view);
assert!(
screen.contains("sync: unknown"),
"must say sync: unknown: {screen}"
);
assert!(
screen.contains("not synced — unavailable"),
"must suppress balance: {screen}"
);
assert!(
screen.contains("remote daemon node.example.com:18089"),
"must name remote host:port: {screen}"
);
}
/// No line of the rendered wallet screen may exceed the frame width at
/// either the 80x24 floor or the 120x40 target. Width is measured by
/// `chars().count()` (the documented metric, see `chars_count_is_not_terminal_cells`).
#[test]
fn wallet_screen_no_line_exceeds_frame_at_80_and_120() {
let chain_ready = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let transfers: Vec<onionwire::wallet::TransferRow> = vec![
onionwire::wallet::TransferRow {
txid: "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".into(),
amount: "5000000000".into(),
address: "4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD".into(),
},
];
let view = wallet_view(address(), "12.5 XMR".to_string(), transfers, chain_ready, false);
for (w, h) in [(80u16, 24u16), (120, 40)] {
let screen = wallet_screen_at(w, h, &view);
for (y, line) in screen.lines().enumerate() {
assert!(
line.chars().count() <= w as usize,
"wallet screen {w}x{h} row {y} exceeds width: {} {line:?}",
line.chars().count()
);
}
}
}
/// A view-only wallet renders its `[!]` badge at both sizes, never clipped.
#[test]
fn wallet_view_only_badge_renders_at_80_and_120() {
let chain = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, true),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, true);
for (w, h) in [(80u16, 24u16), (120, 40)] {
let screen = wallet_screen_at(w, h, &view);
assert!(
screen.contains("[!] view-only"),
"view-only badge missing at {w}x{h}: {screen}"
);
for (y, line) in screen.lines().enumerate() {
assert!(
line.chars().count() <= w as usize,
"badge frame {w}x{h} row {y} too wide: {} {line:?}",
line.chars().count()
);
}
}
}
fn history_payment_fixture() -> Payment {
Payment {
id: 1,
dir: "out".into(),
kind: "payment".into(),
amount_atomic: "1000000000".into(),
txid: Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into()),
verified: true,
created_at: 1700000000,
address: "4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD".into(),
memo: "for pizza".into(),
}
}
#[test]
fn dump_history_frames() {
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
let payments = vec![
history_payment_fixture(),
Payment {
id: 2,
dir: "in".into(),
amount_atomic: "50000000000".into(),
txid: Some("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".into()),
verified: true,
created_at: 1700000100,
address: String::new(),
memo: String::new(),
kind: "payment".into(),
},
Payment {
id: 3,
dir: "out".into(),
amount_atomic: "500000000".into(),
txid: None,
verified: false,
created_at: 1700000200,
address: "4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD".into(),
memo: String::new(),
kind: "payment".into(),
},
];
let now = 1700000300;
for (w, h) in SIZES {
draw_to(w, h, "history list", |f| {
draw_history(f, &payments, 0, false, "alice", now);
});
draw_to(w, h, "history detail", |f| {
draw_history(f, &payments, 0, true, "alice", now);
});
draw_to(w, h, "history empty", |f| {
draw_history(f, &[], 0, false, "bob", now);
});
}
}
#[test]
fn dump_history_ascii_frames() {
unsafe { std::env::set_var("ONIONWIRE_ASCII", "1") };
let _g = ASCII_ENV.lock();
let payments = vec![history_payment_fixture()];
let now = 1700000300;
for (w, h) in SIZES {
draw_to(w, h, "history ascii list", |f| {
draw_history(f, &payments, 0, false, "alice", now);
});
}
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
}
/// Lock for env-var-touching tests (mirrors tui_spec.rs pattern).
static ASCII_ENV: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// Dump history frames at 80x24 and 120x40 for PR-body evidence:
/// empty, mixed verified/unverified list, detail view, and a hostile memo
/// (C0 control chars + bidi override) rendered as inert text.
#[test]
fn dump_history_pr_frames() {
unsafe { std::env::remove_var("ONIONWIRE_ASCII"); }
unsafe { std::env::remove_var("NO_COLOR"); };
let now = 1700000300i64;
let hostile = "pay\x01now\u{202E}reverse";
let payments = vec![
Payment {
id: 1,
dir: "out".into(),
kind: "tip".into(),
amount_atomic: "1000000000".into(),
address: "4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD".into(),
memo: "coffee".into(),
txid: Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into()),
verified: true,
created_at: 1699999000,
},
Payment {
id: 2,
dir: "in".into(),
kind: "payment".into(),
amount_atomic: "50000000000".into(),
address: String::new(),
memo: String::new(),
txid: Some("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".into()),
verified: true,
created_at: 1700000100,
},
Payment {
id: 3,
dir: "out".into(),
kind: "invoice".into(),
amount_atomic: "500000000".into(),
address: String::new(),
memo: hostile.to_string(),
txid: None,
verified: false,
created_at: 1700000200,
},
];
draw_to(80, 24, "history list (mixed verified/unverified)", |f| {
draw_history(f, &payments, 0, false, "alice", now);
});
draw_to(80, 24, "history detail (hostile memo)", |f| {
draw_history(f, &payments, 2, true, "alice", now);
});
draw_to(80, 24, "history empty", |f| {
draw_history(f, &[], 0, false, "bob", now);
});
draw_to(120, 40, "history list (mixed)", |f| {
draw_history(f, &payments, 0, false, "alice", now);
});
}

View file

@ -4,10 +4,12 @@
use onionwire::Message;
use onionwire::outbox::{OutboxEntry, OutboxStatus};
use onionwire::qr;
use onionwire::Payment;
use onionwire::tui::{
OutboxSummary, alert_line, ascii_chrome, chat_with_delivery, delivery_tag, draw_chat,
draw_share, draw_text_overlay, empty_friend_chat_text, help_overlay_text, main_footer_hints,
main_header_line, paste_screen_text, retry_in_text, roster_col_width, short_send_reason,
draw_history, draw_share, draw_text_overlay, empty_friend_chat_text, help_overlay_text,
history_detail, history_row_text, is_onion_host, main_footer_hints, main_header_line,
parse_daemon_addr, paste_screen_text, retry_in_text, roster_col_width, short_send_reason,
status_footer, wrap_invite,
};
use ratatui::Frame;
@ -796,3 +798,259 @@ async fn renders_a_queued_row_from_a_real_outbox_send() {
assert!(delivered[0].contains('✓'), "{:?}", delivered[0]);
assert_eq!(summary.note(), None);
}
/// The chain-source picker's address field: whatever the user typed either
/// parses into exactly `host:port`, or it is refused with a reason. `.onion`,
/// loopback and clearnet are all accepted — clearnet only because the user
/// typed it here — and there is no default port.
#[test]
fn daemon_addresses_parse_or_are_refused() {
assert_eq!(
parse_daemon_addr(" 127.0.0.1:18081 ").unwrap(),
("127.0.0.1".to_string(), 18081)
);
assert_eq!(
parse_daemon_addr("abc234defghijklmnop.onion:18089").unwrap(),
("abc234defghijklmnop.onion".to_string(), 18089)
);
assert_eq!(
parse_daemon_addr("node.example.com:18089").unwrap(),
("node.example.com".to_string(), 18089)
);
assert_eq!(parse_daemon_addr("[::1]:18081").unwrap().1, 18081);
for bad in [
"",
" ",
"127.0.0.1",
"host:",
":18081",
"host:0",
"host:65536",
"host:abc",
"host:-1",
"http://host:18081",
"host/path:18081",
"ho st:18081",
] {
let err = parse_daemon_addr(bad).expect_err(&format!("{bad:?} must be refused"));
assert!(!err.is_empty(), "{bad:?} refused without a reason");
}
}
#[test]
fn onion_hosts_are_recognised_before_any_spawn() {
assert!(is_onion_host("abc234.onion"));
assert!(is_onion_host("ABC234.ONION "));
assert!(!is_onion_host("127.0.0.1"));
assert!(!is_onion_host("node.example.com"));
assert!(!is_onion_host("notonion"));
}
// ---------------------------------------------------------------------------
// Payment history rows (card t_935bf84e)
//
// Tests over test-local `Payment` fixtures — no store access from the render
// path. Direction marker, amount via `pay::atomic_to_xmr_str`, verified word
// + glyph, txid truncation, "awaiting receipt" for None txid, and hostile
// memo sanitization.
// ---------------------------------------------------------------------------
#[allow(clippy::too_many_arguments)]
fn payment(
id: i64,
dir: &str,
kind: &str,
amount_atomic: &str,
address: &str,
memo: &str,
txid: Option<String>,
verified: bool,
created_at: i64,
) -> Payment {
Payment {
id,
dir: dir.to_string(),
kind: kind.to_string(),
amount_atomic: amount_atomic.to_string(),
address: address.to_string(),
memo: memo.to_string(),
txid,
verified,
created_at,
}
}
const NOW: i64 = 1_700_000_000;
#[test]
fn history_row_outbound_verified_has_marker_word_and_glyph() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let p = payment(1, "out", "tip", "1000000000", "addr", "coffee", Some("abcd1234".into()), true, 1_699_999_000);
let row = history_row_text(&p, 76, NOW);
assert!(row.starts_with("> "), "outbound row must start with '> ': {row:?}");
assert!(row.contains('✓'), "verified glyph missing: {row:?}");
assert!(row.contains("verified"), "verified word missing: {row:?}");
assert!(row.contains("0.001"), "amount missing: {row:?}");
}
#[test]
fn history_row_outbound_unverified_has_word_no_check() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let p = payment(2, "out", "invoice", "500000000", "addr", "", Some("ef12".into()), false, 1_700_000_000);
let row = history_row_text(&p, 76, NOW);
assert!(row.starts_with("> "), "outbound row must start with '> ': {row:?}");
assert!(row.contains("unverified"), "unverified word missing: {row:?}");
assert!(!row.contains('✓'), "unverified must not have check glyph: {row:?}");
}
#[test]
fn history_row_inbound_uses_left_marker() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let p = payment(3, "in", "payment", "2500000000", "addr", "", Some("deadbeef".into()), true, 1_700_000_000);
let row = history_row_text(&p, 76, NOW);
assert!(row.starts_with("< "), "inbound row must start with '< ': {row:?}");
assert!(row.contains("verified"), "verified word missing: {row:?}");
}
#[test]
fn history_row_no_txid_says_awaiting_receipt_not_dash() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let p = payment(4, "in", "payment", "1000000000", "addr", "", None, false, 1_700_000_000);
let row = history_row_text(&p, 76, NOW);
assert!(row.contains("awaiting receipt"), "missing 'awaiting receipt': {row:?}");
assert!(!row.contains("--"), "bare dash instead of 'awaiting receipt': {row:?}");
}
#[test]
fn history_row_truncates_txid_within_width() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let p = payment(5, "out", "tip", "1000", "addr", "memo", Some("a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3".into()), true, 1_700_000_000);
let row = history_row_text(&p, 40, NOW);
assert!(row.chars().count() <= 40, "row wider than 40: {} {row:?}", row.chars().count());
}
#[test]
fn history_row_ascii_fallback_has_no_emoji_glyphs() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe { std::env::set_var("ONIONWIRE_ASCII", "1") };
let p = payment(1, "out", "tip", "1000000000", "addr", "", Some("abcd".into()), true, 1_700_000_000);
let row = history_row_text(&p, 76, NOW);
assert!(row.is_ascii(), "ASCII fallback not pure ASCII: {row:?}");
assert!(row.contains("verified"), "ASCII verified word missing: {row:?}");
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
}
#[test]
fn history_detail_shows_all_fields_sanitized() {
let p = payment(
7,
"out",
"tip",
"2000000000",
"1A2B3C4D5E6F",
"for pizza",
Some("abcdef0123456789abcdef0123456789".into()),
true,
1_700_000_000,
);
let detail = history_detail(&p, 76, NOW);
let all = detail.join("\n");
assert!(all.contains("abcdef0123456789abcdef0123456789"), "full txid missing: {all:?}");
assert!(all.contains("1A2B3C4D5E6F"), "address missing: {all:?}");
assert!(all.contains("for pizza"), "memo missing: {all:?}");
assert!(all.contains("0.002"), "amount missing: {all:?}");
assert!(all.contains("outbound"), "direction missing: {all:?}");
assert!(all.contains("verified"), "verified state missing: {all:?}");
assert!(all.contains("1700000000") || all.contains("Nov"), "timestamp missing: {all:?}");
for line in &detail {
assert!(line.chars().count() <= 76, "detail line wider than 76: {} {line:?}", line.chars().count());
}
}
#[test]
fn history_detail_hostile_memo_is_sanitized_inert_text() {
// C0 control chars + bidi override — must render as inert text, not affect
// the terminal or carry hidden directionality.
let hostile = "pay\x01now\u{202E}\u{202E}reverse";
let p = payment(8, "in", "payment", "500000000", "addr", hostile, Some("cafebabe".into()), false, 1_700_000_000);
let detail = history_detail(&p, 76, NOW);
let all = detail.join("\n");
// Bidi override must be stripped — the word "reverse" must appear in
// reading order, not visually flipped by a leftover override mark.
assert!(!all.contains('\u{202E}'), "bidi override survived sanitize: {all:?}");
assert!(!all.contains('\x01'), "C0 control survived sanitize: {all:?}");
assert!(all.contains("reverse"), "sanitized memo text lost: {all:?}");
}
#[test]
fn history_detail_no_txid_shows_awaiting_receipt() {
let p = payment(9, "in", "payment", "1000", "addr", "", None, false, 1_700_000_000);
let detail = history_detail(&p, 76, NOW);
let all = detail.join("\n");
assert!(all.contains("awaiting receipt"), "detail missing 'awaiting receipt': {all:?}");
}
#[test]
fn draw_history_list_at_80x24_fits_and_shows_rows() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let payments = vec![
payment(1, "out", "tip", "1000000000", "addr", "coffee", Some("abcd1234".into()), true, 1_699_999_000),
payment(2, "in", "payment", "2500000000", "addr", "", Some("deadbeef".into()), true, 1_700_000_001),
payment(3, "out", "invoice", "500000000", "addr", "", None, false, 1_700_000_002),
];
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| draw_history(f, &payments, 1, false, "alice", NOW))
.expect("draw");
let screen = screen_from(terminal.backend().buffer(), 80, 24);
for line in screen.lines() {
assert!(line.chars().count() <= 80, "80x24 history row wider than 80: {} {line:?}", line.chars().count());
}
assert!(screen.contains("alice"), "friend name missing from title: {screen}");
assert!(screen.contains("> "), "outbound marker missing: {screen}");
assert!(screen.contains("< "), "inbound marker missing: {screen}");
assert!(screen.contains("awaiting receipt"), "awaiting receipt missing: {screen}");
assert!(screen.contains("Enter detail"), "hint missing: {screen}");
assert!(screen.contains("Esc back"), "hint missing: {screen}");
}
#[test]
fn draw_history_empty_at_80x24_shows_designed_copy() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| draw_history(f, &[], 0, false, "bob", NOW))
.expect("draw");
let screen = screen_from(terminal.backend().buffer(), 80, 24);
for line in screen.lines() {
assert!(line.chars().count() <= 80, "row wider than 80: {line:?}");
}
assert!(screen.contains("no payments with this friend yet"), "empty copy missing: {screen}");
}
#[test]
fn draw_history_detail_at_80x24_fits() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let p = payment(1, "out", "tip", "1000000000", "1A2B3C4D5E6F", "coffee", Some("abcdef0123456789abcdef0123456789".into()), true, 1_700_000_000);
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| draw_history(f, std::slice::from_ref(&p), 0, true, "alice", NOW))
.expect("draw");
let screen = screen_from(terminal.backend().buffer(), 80, 24);
for line in screen.lines() {
assert!(line.chars().count() <= 80, "detail row wider than 80: {} {line:?}", line.chars().count());
}
assert!(screen.contains("awaiting receipt") || screen.contains("abcdef0123456789"), "detail content missing: {screen}");
}

View file

@ -4,7 +4,10 @@ use std::sync::{Arc, Mutex};
use ed25519_dalek::SigningKey;
use onionwire::pay;
use onionwire::wallet::{self, TransferRow, Wallet};
use onionwire::wallet::{
self, NOT_CONFIGURED_MSG, NOT_CONNECTED_MSG, Readiness, TransferRow, VIEW_ONLY_MSG, Wallet,
WalletConfig, WalletStatus, readiness,
};
use onionwire::{PaymentWrite, Store};
use rand::rngs::OsRng;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@ -13,7 +16,6 @@ use tokio::net::TcpListener;
/// `ONIONWIRE_WALLET_NO_SPEND` is process-wide; tests that touch env serialize.
static ENV_LOCK: Mutex<()> = Mutex::new(());
fn row(txid: &str, amount: &str, address: &str) -> TransferRow {
TransferRow {
txid: txid.into(),
@ -112,24 +114,23 @@ async fn mock_get_address_parses_string() {
#[tokio::test]
async fn mock_create_address_and_transfer() {
let addr_hex = "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let canned = json_rpc_ok(
r#"{"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB","tx_hash":"abc123"}"#,
);
tokio::spawn(serve_digest_then(listener, canned.clone()));
let w = Wallet::from_url(&format!("http://ow:[email protected]:{}", addr.port())).unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(serve_recording(
listener,
Arc::new(Mutex::new(Vec::new())),
Arc::new(move |method| match method {
// A spend is only attempted on a synced wallet.
"get_info" => synced_info(),
_ => rpc_result(&format!(r#"{{"address":"{addr_hex}","tx_hash":"abc123"}}"#)),
}),
));
let w = recording_wallet(port);
let created = w.create_address().await.expect("create_address");
assert!(created.starts_with('8'));
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(serve_digest_then(listener, canned));
let w = Wallet::from_url(&format!("http://ow:[email protected]:{}", addr.port())).unwrap();
let txid = w
.transfer("8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", 1)
.await
.expect("transfer");
let txid = w.transfer(addr_hex, 1).await.expect("transfer");
assert_eq!(txid, "abc123");
}
@ -295,6 +296,12 @@ fn rpc_result(result: &str) -> String {
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#)
}
/// What a fully synced wallet answers to `get_info`: the daemon has reached the
/// tip and the wallet has scanned it. This is the honest readiness signal.
fn synced_info() -> String {
rpc_result(r#"{"height":3210000,"target_height":3210000,"synchronized":true}"#)
}
fn recording_wallet(port: u16) -> Wallet {
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("url")
}
@ -321,10 +328,7 @@ async fn no_spend_mode_refuses_transfer_with_no_rpc_request() {
.await
.unwrap_err()
.to_string();
assert!(
err.to_ascii_lowercase().contains("view-only"),
"got {err}"
);
assert!(err.to_ascii_lowercase().contains("view-only"), "got {err}");
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
let seen = log.lock().expect("log").clone();
assert!(seen.is_empty(), "no RPC request may be made: {seen:?}");
@ -383,6 +387,7 @@ async fn view_only_wallet_maps_transfer_failure_to_clear_message() {
Arc::clone(&log),
Arc::new(|method| match method {
"query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."),
"get_info" => synced_info(),
_ => rpc_error(-18, "No transaction created"),
}),
));
@ -414,6 +419,7 @@ async fn spend_capable_wallet_keeps_the_original_transfer_error() {
Arc::new(Mutex::new(Vec::new())),
Arc::new(|method| match method {
"query_key" => rpc_result(r#"{"key":"00112233"}"#),
"get_info" => synced_info(),
_ => rpc_error(-18, "No transaction created"),
}),
));
@ -464,8 +470,8 @@ async fn create_wallet_does_not_send_a_seed_and_returns_mnemonic() {
"filename missing: {create}"
);
assert!(
seen.iter().any(|r| r.contains(r#""method":"query_key""#)
&& r.contains("mnemonic")),
seen.iter()
.any(|r| r.contains(r#""method":"query_key""#) && r.contains("mnemonic")),
"must read mnemonic after create: {seen:?}"
);
}
@ -503,7 +509,9 @@ async fn restore_wallet_sends_seed_to_restore_deterministic_wallet() {
listener,
Arc::clone(&log),
Arc::new(|method| match method {
"restore_deterministic_wallet" => rpc_result(r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","seed":"lumber tacit lemon ivory risk"}"#),
"restore_deterministic_wallet" => rpc_result(
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","seed":"lumber tacit lemon ivory risk"}"#,
),
_ => rpc_error(-1, "unexpected method"),
}),
));
@ -616,3 +624,509 @@ async fn mock_digest_auth_accepted() {
let got = w.get_address().await.expect("get_address");
assert!(got.starts_with('4'), "got {got}");
}
/// 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() {
"get_info" => synced_info(),
_ => rpc_result(
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
),
};
let _ = sock.write_all(http_200_body(&body).as_bytes()).await;
}
}
const SPEND_ADDR: &str = "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
/// Readiness is a real predicate, not "sync made some progress": a wallet whose
/// daemon has not reached the tip is not ready, refuses to spend, and does not
/// even ask the RPC for a transfer.
#[tokio::test]
async fn unsynced_wallet_is_not_ready_and_refuses_to_spend() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let log = Arc::new(Mutex::new(Vec::new()));
tokio::spawn(serve_recording(
listener,
Arc::clone(&log),
Arc::new(|method| match method {
"get_info" => {
rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#)
}
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
}),
));
let w = recording_wallet(port);
assert!(
!w.chain_ready().await.expect("get_info"),
"must not be ready"
);
assert!(
!w.can_verify_receipts().await,
"an unsynced wallet cannot verify receipts"
);
let err = w.transfer(SPEND_ADDR, 1).await.unwrap_err().to_string();
assert!(err.to_ascii_lowercase().contains("not synced"), "got {err}");
let seen = log.lock().expect("log").clone();
assert!(
!seen.iter().any(|r| r.contains("\"method\":\"transfer\"")),
"a not-ready wallet must not attempt a spend: {seen:?}"
);
}
/// A missing/absent `synchronized` (or a wallet behind the daemon) is not-ready,
/// never a silent pass. Fail closed.
#[tokio::test]
async fn missing_or_behind_synchronized_is_not_ready() {
for info in [
r#"{"height":10}"#,
r#"{"height":100,"target_height":200,"synchronized":true}"#,
r#"{"height":0,"target_height":0,"synchronized":true}"#,
r#"{"synchronized":"true"}"#,
] {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let canned = rpc_result(info);
tokio::spawn(serve_recording(
listener,
Arc::new(Mutex::new(Vec::new())),
Arc::new(move |_| canned.clone()),
));
let w = recording_wallet(port);
assert!(
!w.chain_ready().await.expect("get_info"),
"{info} must not read as ready"
);
}
}
#[tokio::test]
async fn synced_wallet_is_ready_and_spends() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(serve_recording(
listener,
Arc::new(Mutex::new(Vec::new())),
Arc::new(|method| match method {
"get_info" => synced_info(),
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
}),
));
let w = recording_wallet(port);
assert!(w.chain_ready().await.expect("get_info"));
assert!(w.can_verify_receipts().await);
assert_eq!(w.transfer(SPEND_ADDR, 1).await.expect("transfer"), "abc123");
}
/// `spend_ready` is the stricter signal for the spend UI: synced *and* holding
/// unlocked funds. Zero unlocked balance is not spend-ready.
#[tokio::test]
async fn spend_ready_needs_an_unlocked_balance() {
for (unlocked, ready) in [("0", false), ("5", true)] {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let balance = rpc_result(&format!(
r#"{{"balance":"{unlocked}","unlocked_balance":"{unlocked}"}}"#
));
tokio::spawn(serve_recording(
listener,
Arc::new(Mutex::new(Vec::new())),
Arc::new(move |method| match method {
"get_info" => synced_info(),
"get_balance" => balance.clone(),
_ => rpc_result(r#"{}"#),
}),
));
let w = recording_wallet(port);
assert_eq!(w.spend_ready().await.expect("spend_ready"), ready);
}
}
/// The honest not-ready state: a receipt whose history *would* match stays
/// verified=0 while the wallet is unsynced. (node.rs gates on the same
/// predicate via `can_verify_receipts`.)
#[tokio::test]
async fn unsynced_wallet_leaves_a_matching_receipt_unverified() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "onionwire-test").expect("open");
let sk = SigningKey::generate(&mut OsRng);
let pk = sk.verifying_key().to_bytes();
store.upsert_friend(&pk, "peer.onion", None).unwrap();
let addr = xmr_addr();
let rcp = pay::sign_receipt(&sk.to_bytes(), "deadbeef", "5", &addr, 1).unwrap();
let id = store
.insert_payment(
&pk,
PaymentWrite {
dir: "in",
kind: "receipt",
amount_atomic: &rcp.amount_atomic,
address: &rcp.address,
memo: "",
txid: Some(&rcp.txid),
verified: false,
},
)
.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let addr_owned = addr.clone();
tokio::spawn(serve_recording(
listener,
Arc::new(Mutex::new(Vec::new())),
Arc::new(move |method| match method {
"get_info" => {
rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#)
}
"get_transfers" => rpc_result(&format!(
r#"{{"in":[{{"txid":"deadbeef","amount":5,"address":"{addr_owned}"}}],"pending":[]}}"#
)),
_ => rpc_result(r#"{}"#),
}),
));
let w = recording_wallet(port);
// The same shape node.rs::ingest_receipt runs.
if w.can_verify_receipts().await
&& let Ok(rows) = w.get_transfers().await
&& wallet::transfers_match(&rows, &rcp.txid, &rcp.amount_atomic, &rcp.address)
{
store.mark_verified(id).unwrap();
}
assert!(
!store.list_payments(&pk).unwrap()[0].verified,
"an unsynced wallet must leave the receipt unverified"
);
}
/// Chain-dependent calls get a longer budget than local wallet-management calls,
/// and the budget is the backend's to set — not a hard-coded 5s.
#[tokio::test]
async fn chain_calls_get_a_longer_budget_than_local_calls() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(serve_delayed(
listener,
std::time::Duration::from_millis(400),
));
let w = recording_wallet(port).with_timeouts(
std::time::Duration::from_millis(150),
std::time::Duration::from_millis(2000),
);
let err = w.get_address().await.unwrap_err().to_string();
assert!(
err.to_ascii_lowercase().contains("timed out"),
"the local call must hit the short budget: {err}"
);
assert!(
w.chain_ready()
.await
.expect("get_info within the chain budget"),
"chain calls must outlast daemon latency"
);
}
// ---------------------------------------------------------------------------
// Stored wallet config (F7): read at boot, sealed at rest, never in an error.
// ---------------------------------------------------------------------------
/// The exact refusal copy the TUI asserts. Pinned here as literals so a copy
/// change is a test failure, and cross-checked against the constants the guard
/// returns.
#[test]
fn readiness_guard_refuses_each_state_with_exact_copy() {
assert_eq!(
NOT_CONFIGURED_MSG,
"wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC"
);
assert_eq!(
NOT_CONNECTED_MSG,
"wallet not connected — check endpoint, login, daemon"
);
assert_eq!(Readiness::NotConfigured.refusal(), Some(NOT_CONFIGURED_MSG));
assert_eq!(Readiness::NotConnected.refusal(), Some(NOT_CONNECTED_MSG));
assert_eq!(Readiness::NoSpend.refusal(), Some(VIEW_ONLY_MSG));
assert_eq!(Readiness::Ready.refusal(), None);
// not configured beats everything else, whatever else is true.
assert_eq!(
readiness(false, false, false, true),
Readiness::NotConfigured
);
assert_eq!(readiness(false, true, true, true), Readiness::NotConfigured);
// configured but not reachable.
assert_eq!(readiness(true, false, false, true), Readiness::NotConnected);
assert_eq!(
readiness(true, false, false, false),
Readiness::NotConnected
);
// view-only: /tip is refused on its own terms, /pay keeps working.
assert_eq!(readiness(true, true, true, true), Readiness::NoSpend);
assert_eq!(readiness(true, false, true, true), Readiness::NoSpend);
assert_eq!(readiness(true, true, true, false), Readiness::Ready);
// allowed only when configured + connected + spend-capable.
assert_eq!(readiness(true, true, false, true), Readiness::Ready);
assert!(!readiness(true, false, false, true).is_ready());
}
#[test]
fn wallet_config_debug_never_prints_the_login() {
let cfg = WalletConfig::new("http://127.0.0.1:18083", "ow:hunter2XYZ", true);
let dbg = format!("{cfg:?}");
assert!(!dbg.contains("hunter2XYZ"), "debug leaked the login: {dbg}");
assert!(dbg.contains("127.0.0.1:18083"), "{dbg}");
}
/// Stored config is what boot reads; env is the migration/fallback path.
#[test]
fn boot_reads_stored_config_over_env_and_falls_back_to_env() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
unsafe {
std::env::set_var("ONIONWIRE_WALLET_RPC", "http://ow:[email protected]:18083");
std::env::remove_var("ONIONWIRE_WALLET_RPC_LOGIN");
std::env::remove_var("ONIONWIRE_WALLET_NO_SPEND");
}
let stored = WalletConfig::new("http://127.0.0.1:18084", "ow:storedpass", true);
let w = Wallet::for_boot(Some(&stored));
assert!(w.configured(), "stored config must configure the wallet");
assert!(w.no_spend(), "stored no_spend must win over env");
let in_use = w.config().expect("configured wallet has a config");
assert_eq!(in_use.rpc_url, "http://127.0.0.1:18084/json_rpc");
assert_eq!(in_use.rpc_login.as_str(), "ow:storedpass");
assert!(!in_use.rpc_url.contains("storedpass"), "{}", in_use.rpc_url);
// No stored config: the env vars still boot headless / pre-F7 installs.
let w = Wallet::for_boot(None);
assert!(w.configured());
let in_use = w.config().expect("env wallet has a config");
assert_eq!(in_use.rpc_url, "http://127.0.0.1:18083/json_rpc");
assert_eq!(in_use.rpc_login.as_str(), "ow:envpass");
assert!(!w.no_spend());
// A stored config that cannot be used falls through to env, not to a dial.
let broken = WalletConfig::new("http://example.com:18083", "ow:x", false);
assert!(Wallet::for_boot(Some(&broken)).configured());
// Neither: disabled, and the refusal says so.
unsafe {
std::env::remove_var("ONIONWIRE_WALLET_RPC");
}
let w = Wallet::for_boot(None);
assert!(!w.configured());
assert!(w.config().is_none());
}
#[test]
fn malformed_config_errors_never_carry_the_password() {
let cfg = WalletConfig::new("http://example.com:18083", "ow:hunter2XYZ", false);
let err = Wallet::from_config(&cfg).unwrap_err().to_string();
assert!(!err.contains("hunter2XYZ"), "password leaked: {err}");
let cfg = WalletConfig::new("http://127.0.0.1:18083", "", false);
let err = Wallet::from_config(&cfg).unwrap_err().to_string();
assert!(!err.is_empty());
let cfg = WalletConfig::new("", "ow:hunter2XYZ", false);
assert!(
Wallet::from_config(&cfg).is_err(),
"empty url is not a config"
);
}
/// One row, sealed with the store data key on top of SQLCipher, and nothing in
/// the clear on disk.
#[test]
fn stored_wallet_config_round_trips_and_the_login_is_sealed_on_disk() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open_at_with_passphrase(dir.path(), "cfg-pass").unwrap();
assert!(
store.load_wallet_config().unwrap().is_none(),
"a fresh store has no wallet config"
);
let cfg = WalletConfig::new("http://127.0.0.1:18083", "ow:cfg-secret-xyz", false);
store.save_wallet_config(&cfg).unwrap();
let got = store.load_wallet_config().unwrap().expect("stored config");
assert_eq!(got.rpc_url, "http://127.0.0.1:18083");
assert_eq!(got.rpc_login.as_str(), "ow:cfg-secret-xyz");
assert!(!got.no_spend);
// Saving again replaces the single row.
let cfg2 = WalletConfig::new("http://127.0.0.1:18085", "ow:second-secret-abc", true);
store.save_wallet_config(&cfg2).unwrap();
let got = store.load_wallet_config().unwrap().expect("stored config");
assert_eq!(got.rpc_url, "http://127.0.0.1:18085");
assert_eq!(got.rpc_login.as_str(), "ow:second-secret-abc");
assert!(got.no_spend);
// An empty URL clears the stored config instead of storing a half-config.
store
.save_wallet_config(&WalletConfig::new("", "", false))
.unwrap();
assert!(store.load_wallet_config().unwrap().is_none());
store.save_wallet_config(&cfg).unwrap();
store.checkpoint_wal().unwrap();
drop(store);
for name in ["onionwire.db", "onionwire.db-wal", "onionwire.db-shm"] {
let Ok(bytes) = std::fs::read(dir.path().join(name)) else {
continue;
};
assert!(
!contains_bytes(&bytes, b"cfg-secret-xyz"),
"{name} holds the RPC login in the clear"
);
}
// The readers come back to a config that still decrypts.
let store = Store::open_at_with_passphrase(dir.path(), "cfg-pass").unwrap();
let got = store
.load_wallet_config()
.unwrap()
.expect("reopened config");
assert_eq!(got.rpc_login.as_str(), "ow:cfg-secret-xyz");
}
fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
haystack.windows(needle.len()).any(|w| w == needle)
}
/// The one-shot probe the config screen's Test button fires. It is against the
/// *typed* endpoint, so it must not touch the live wallet.
#[tokio::test]
async fn ping_reports_success_and_sanitizes_failures() {
// A reachable endpoint: digest challenge, then get_address.
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let canned = json_rpc_ok(
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
);
tokio::spawn(serve_digest_then(listener, canned));
let ok = wallet::Wallet::ping(&format!("http://127.0.0.1:{port}"), "ow:ping-secret-xyz").await;
assert!(ok.ok, "{ok:?}");
assert_eq!(ok.status, "connected");
assert_eq!(ok.error, None);
assert!(!format!("{ok:?}").contains("ping-secret-xyz"));
// Nothing listening: refused, and the reason carries no password.
let dead = freed_loopback_port();
let bad = wallet::Wallet::ping(&format!("http://127.0.0.1:{dead}"), "ow:ping-secret-xyz").await;
assert!(!bad.ok, "{bad:?}");
assert!(bad.error.is_some(), "{bad:?}");
assert!(
!bad.error.as_deref().unwrap().contains("ping-secret-xyz"),
"{bad:?}"
);
// A non-loopback host is refused locally, before any dial.
let off = wallet::Wallet::ping("http://node.example.com:18083", "ow:ping-secret-xyz").await;
assert!(!off.ok);
assert!(
!off.error
.as_deref()
.unwrap_or_default()
.contains("ping-secret-xyz"),
"{off:?}"
);
// An open RPC (no digest challenge) is refused with no password in it.
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let open = http_200_body(r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4AA"}}"#);
tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.expect("accept");
let mut buf = vec![0u8; 4096];
let _ = sock.read(&mut buf).await;
let _ = sock.write_all(open.as_bytes()).await;
});
let open =
wallet::Wallet::ping(&format!("http://127.0.0.1:{port}"), "ow:ping-secret-xyz").await;
assert!(!open.ok, "{open:?}");
assert!(
open.error.as_deref().unwrap_or_default().contains("digest"),
"{open:?}"
);
}
/// `WalletStatus.connected` comes from a probe, never from config-existence —
/// and a lower layer that echoes the password into an RPC error cannot leak it
/// into the status line.
#[tokio::test]
async fn status_is_connected_only_after_a_successful_probe() {
// Configured but never probed: connected is false, config is not reachability.
let idle = WalletStatus::idle(true);
assert!(idle.configured());
assert!(!idle.connected, "config exists is not reachability");
assert_eq!(idle.balance_line, "—");
assert_eq!(idle.receive_address, "—");
// A successful probe: connected, address + balance filled in.
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(serve_recording(
listener,
Arc::new(Mutex::new(Vec::new())),
Arc::new(|method: &str| match method {
"get_address" => rpc_result(
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
),
"get_balance" => rpc_result(r#"{"balance":"123456"}"#),
_ => rpc_result("{}"),
}),
));
let w = recording_wallet(port);
let ok = w.status().await;
assert!(ok.configured() && ok.connected, "{ok:?}");
assert_eq!(ok.last_error, None);
assert_eq!(ok.balance_line, "123456 piconero");
assert!(ok.receive_address.starts_with('4'), "{ok:?}");
// A probe that fails keeps configured=true and turns connected off.
let dead = freed_loopback_port();
let down = Wallet::from_url(&format!("http://ow:[email protected]:{dead}")).unwrap();
let bad = down.status().await;
assert!(bad.configured(), "{bad:?}");
assert!(!bad.connected, "{bad:?}");
assert!(bad.last_error.is_some(), "{bad:?}");
assert_eq!(bad.balance_line, "—");
assert_eq!(bad.receive_address, "—");
// An RPC error message that repeats the password is redacted before display.
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let leaky = http_200_body(&rpc_error(-1, "auth failed for ow:leak-secret-xyz"));
tokio::spawn(serve_digest_then(listener, leaky));
let w = Wallet::from_url(&format!("http://ow:[email protected]:{port}")).unwrap();
let leak = w.status().await;
assert!(!leak.connected, "{leak:?}");
let err = leak.last_error.expect("failure reason");
assert!(!err.contains("leak-secret-xyz"), "password leaked: {err}");
assert!(err.contains("<redacted>"), "{err}");
assert!(
err.chars().count() <= 121,
"status copy must stay short: {err}"
);
// Nothing configured at all.
let none = Wallet::disabled().status().await;
assert!(!none.configured() && !none.connected, "{none:?}");
}
/// A port nothing is listening on: bind it, read it, drop the listener.
fn freed_loopback_port() -> u16 {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
drop(listener);
port
}