Merge branch 'main' into feat/android-foreground-keepalive

This commit is contained in:
sirius 2026-09-12 22:08:35 +00:00
commit 5032243934
12 changed files with 1469 additions and 120 deletions

View file

@ -3,7 +3,7 @@
Lean Tor messenger: one Rust process (ratatui + Noise IK + sqlite + in-process Arti). Lean Tor messenger: one Rust process (ratatui + Noise IK + sqlite + in-process Arti).
No hosted server. Identity is a public key; the onion is only a locator. No hosted server. Identity is a public key; the onion is only a locator.
**v0.2** — Linux TUI. Two people add each other with an `onionwire:v1:…` invite string (`F2` share / `F3` paste). There is no QR graphic. Chat is Noise IK over your own v3 onion. Optional Monero invoices if you point at a local `monero-wallet-rpc`. Fail closed: peer down → send fails. Arti onion services are still experimental. Chat bodies are encrypted at rest; identity keys in sqlite are still plaintext. **v0.2** — Linux TUI. Two people add each other with an `onionwire:v1:…` invite string (`F2` share / `F3` paste). There is no QR graphic. Chat is Noise IK over your own v3 onion. Optional Monero invoices if you point at a local `monero-wallet-rpc`. Fail closed: peer down → send fails. Arti onion services are still experimental. The whole store is encrypted at rest with SQLCipher; message bodies add a row-bound AEAD layer on top.
You do **not** install a `tor` daemon, `torrc`, Prosody, or XMPP. OnionWire embeds Arti and publishes its own v3 onion. You do **not** install a `tor` daemon, `torrc`, Prosody, or XMPP. OnionWire embeds Arti and publishes its own v3 onion.
@ -222,14 +222,11 @@ If you set `ONIONWIRE_HOME`, delete that directory instead.
## Seized laptop ## Seized laptop
Chat bodies in sqlite are ChaCha20-Poly1305 (`nonce || ciphertext` in `messages.plaintext`) with AAD bound to `friend_id`, `dir`, and row id, wrapped by a passphrase-derived Argon2id key. A disk grep of `onionwire.db` must not yield the message log. Empty-AAD v0.2 blobs are rewrapped once on unlock. The whole sqlite file is SQLCipher (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`). A 32-byte key is derived from the store passphrase with Argon2id over a per-install 16-byte salt in `store_salt` (mode 0600, in `ONIONWIRE_HOME`) and handed to SQLCipher as a **raw** key (`PRAGMA key = "x'…'"`) as the first statement after open. The file header, schema, `self.identity_sk`, friend public keys, locators, profiles and payment rows are all ciphertext on disk, so a disk grep of `onionwire.db` must not yield the message log, your identity key or your roster. A wrong or empty passphrase fails closed before any write; an encrypted store whose `store_salt` is missing refuses to open instead of guessing. v0.2.1 plaintext installs upgrade in place on the first open with the right passphrase; a wrong one leaves the plaintext file untouched.
Still plaintext on disk (unless you add OS/FDE): Chat bodies carry a second, row-bound layer: ChaCha20-Poly1305 (`nonce || ciphertext` in `messages.plaintext`) with AAD `owmsg1 || friend_id_le64 || dir || 0x00 || row_id_le64`, plus a random 32-byte data key in `store_meta` wrapped with Argon2id from the same passphrase. Whole-file encryption does not stop someone who can write the file from moving one row's ciphertext into another row; the row-bound AAD does, and it stays. Empty-AAD v0.2 blobs are rewrapped once on unlock.
- your identity secret key (`self.identity_sk`) At-rest encryption is not a defense against a live compromise: while OnionWire runs, the passphrase, the db key and decrypted rows are in process memory, and SQLCipher's page cache holds decrypted pages. It also does not stop an attacker who has your passphrase. `/wipe` deletes chat and payments history; it is not a forensic erase — SSD wear-levelling can keep copies. Roster and identity stay. `/wipe-all` deletes the data dir (new identity). Ctrl-Q can clear history on the way out (`CLEAR`) without becoming a new person.
- friend public keys and current locators
The message key is **not** wrapped with `identity_sk` (that key is in the same file). sqlcipher is out of v1. `/wipe` deletes chat and payments history; it is not a forensic erase. Roster and identity stay. `/wipe-all` deletes the data dir (new identity). Ctrl-Q can clear history on the way out (`CLEAR`) without becoming a new person.
Threat model: [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md). Threat model: [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md).
@ -316,7 +313,7 @@ Do not run `cargo publish`; `publish = false`. CI needs the repo secret
## Not in v1 ## Not in v1
Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server, sqlcipher, QR codes, A/V. Protocol lock: [docs/PROTOCOL.md](docs/PROTOCOL.md). Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server, QR codes, A/V. Protocol lock: [docs/PROTOCOL.md](docs/PROTOCOL.md).
## License ## License

View file

@ -24,7 +24,7 @@ Original pass: rust-dev, no live hidden service / live wallet. Ignored tests
## Still true / not a “finding we forgot” ## Still true / not a “finding we forgot”
- Identity secret key and roster (pubkeys + locators) are **plaintext** in sqlite. Chat bodies are not. Seized laptop without FDE yields who you are and who you talk to. - At rest the whole store is SQLCipher (Argon2id key over a 16-byte `store_salt`), so the identity secret key, roster (pubkeys + locators) and chat bodies are ciphertext on disk; chat bodies add a row-bound AEAD layer on top. That is not a defense against a live compromise or an attacker who has the passphrase — see [THREAT_MODEL.md](THREAT_MODEL.md).
- Arti onion services are experimental. Fail closed; no C-tor fallback. - Arti onion services are experimental. Fail closed; no C-tor fallback.
- No public third-party audit, no `cargo-audit` gate in CI as of the original pass. - No public third-party audit, no `cargo-audit` gate in CI as of the original pass.
- Invite decode still accepts the legacy concat signature (compatibility). - Invite decode still accepts the legacy concat signature (compatibility).

View file

@ -73,6 +73,18 @@ A signed `prf` frame is shown to people who already have a session with you. App
OnionWire never holds spend keys. Optional `ONIONWIRE_WALLET_RPC` talks HTTP Digest to a user-hosted `monero-wallet-rpc` on loopback (`--rpc-login` required; open RPC is refused). A Noise friend can sign any `rcp`; the signature proves who sent the claim, not that a payment happened. `verified=1` only after a conjunctive RPC match: one `get_transfers` row with the same non-empty `txid`, `amount`, and `address`. Incoming `rcp` stays `verified=0` if RPC is down, errors, or no exact row. Subaddress reuse is the user’s wallet policy. OnionWire never holds spend keys. Optional `ONIONWIRE_WALLET_RPC` talks HTTP Digest to a user-hosted `monero-wallet-rpc` on loopback (`--rpc-login` required; open RPC is refused). A Noise friend can sign any `rcp`; the signature proves who sent the claim, not that a payment happened. `verified=1` only after a conjunctive RPC match: one `get_transfers` row with the same non-empty `txid`, `amount`, and `address`. Incoming `rcp` stays `verified=0` if RPC is down, errors, or no exact row. Subaddress reuse is the user’s wallet policy.
Run it **view-only** (recommended). `/pay` and receipt verification need only
`create_address`/`get_transfers`, which a wallet without a spend key serves
fine; `ONIONWIRE_WALLET_NO_SPEND=1` disables `/tip` locally, before any RPC
dial, and a view-only wallet is detected over RPC (`query_key`
`key_type=spend_key` → `-29`, `WALLET_RPC_ERROR_CODE_WATCH_ONLY`) so `/tip` says
so plainly instead of failing with a raw wallet error. The trade-off is
explicit: an OnionWire instance pointed at a **spend-capable** wallet is a local
spend authority — any process that can read the RPC credentials can move the
balance, and `/tip` gives a chat peer a supported way to ask for a transfer.
Loopback binding is not an authorization boundary. Full setup, view-only wallet
creation, and the credential/loopback reasoning: [WALLET.md](WALLET.md).
## Backup file is the identity ## Backup file is the identity
`/backup` writes the identity and Noise static secrets. Treat the file like `onionwire.db`. Restore overwrites self keys and does **not** rewrite the friends table. `/backup` writes the identity and Noise static secrets. Treat the file like `onionwire.db`. Restore overwrites self keys and does **not** rewrite the friends table.

View file

@ -351,6 +351,16 @@ Else RGB as today.
| box | ratatui `Borders::ALL` (light) | `+` `-` `\|` via `border::Set` | | box | ratatui `Borders::ALL` (light) | `+` `-` `\|` via `border::Set` |
| alert prefix | `! ` | `! ` | | alert prefix | `! ` | `! ` |
| stale | word `stale` | `stale` | | stale | word `stale` | `stale` |
| delivery: delivered | `✓` | `ok` |
| delivery: queued | `◷` | (word) `queued` |
| delivery: sending | `»` | (word) `sending` |
| delivery: failed | `✗` | (word) `failed` |
`queued` / `sending` / `failed` always carry their state word, so the ASCII
fallback drops the glyph instead of inventing one. Only `✓` is wordless, so it
falls back to `ok`. `delivery_glyph()` /
`tests/tui_spec.rs::delivery_markers_have_exercised_ascii_fallbacks` exercise the
fallback path.
No emoji. `onion_glyph()` stays for callers that already use it; do not put it No emoji. `onion_glyph()` stays for callers that already use it; do not put it
on the main header. on the main header.
@ -401,6 +411,9 @@ Do not soften fail-closed into a loader.
| sending | `sending` (keep, no spinner) | | sending | `sending` (keep, no spinner) |
| sent | `sent` | | sent | `sent` |
| peer down / send err | `send failed: {e}` (visible) | | peer down / send err | `send failed: {e}` (visible) |
| queued (outbox) | `{n} queued` — replaces the flat `sent`/`send failed` while rows are outstanding |
| queued + terminal failure | `{n} queued, send failed: {short}` |
| terminal failure | `send failed: {short}` (`{f} failed` when more than one) |
| already sending | `already sending` (keep) | | already sending | `already sending` (keep) |
| stale friend | `stale` suffix (keep) | | stale friend | `stale` suffix (keep) |
| empty composer | `message` as dim placeholder (not the slash list). Slash list stays in `?` | | empty composer | `message` as dim placeholder (not the slash list). Slash list stays in `?` |
@ -570,3 +583,42 @@ cargo test --locked --test tui_spec -- --nocapture dump_spec_frames
Copy wired in `src/tui.rs` (not in the reconstructed standin): empty thread is Copy wired in `src/tui.rs` (not in the reconstructed standin): empty thread is
`no messages` / `type below, Enter sends`; paste error is `{err}` then `no messages` / `type below, Enter sends`; paste error is `{err}` then
`Enter resubmits Esc back`; alerts truncate to the frame width. `Enter resubmits Esc back`; alerts truncate to the frame width.
## Delivery state (outbox) — implemented
Per-message state, read from the local outbox. The states are the store's own
(`Queued` / `Sending` / `Sent` / `Failed`) — no parallel model, no new wire
prefix, no server.
| Row | Marker |
|---|---|
| delivered | `you: ping ✓` |
| queued (2nd attempt, 45s out) | `you: pong ◷ queued (try 2/8, retry 45s)` |
| sending | `you: pong » sending` |
| failed | `you: pong ✗ failed: connection timed out` |
| inbound | `them: pong` (no marker) |
- `try {n}/{8}` is the outbox attempt count; `retry {s}s` / `retry {m}m` /
`retry now` comes from the stored absolute `next_attempt_at`.
- Failed reasons are sanitized, cut to the tail of the `a: b: c` chain and
capped at 24 cells (`short_send_reason`).
- Footer while rows are outstanding: `{n} queued`; any terminal failure keeps a
fail-closed `send failed: {short}` statement (with `! ` when colour is off).
- The tag trails the body and wraps with it, so it is never clipped away.
Correlation: a delivered row is deleted from the outbox, so an outbound message
with no row is `Sent`; pending rows are matched to messages by body, newest send
first (`chat_with_delivery`). The outbox holds no message id the UI can join on,
so two identical bodies where only the newer one is still queued attach the
marker to the newer send. An id-bearing accessor would remove that last
ambiguity; see the follow-up card noted in the PR.
### Size floor / target
- **Floor: 80x24.** Everything above must render there.
- **Target: 120x40.**
- `tests/tui_spec.rs::chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping`
draws the real `draw_chat` + `status_footer` at 80x24 and asserts every chat
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`.

184
docs/WALLET.md Normal file
View file

@ -0,0 +1,184 @@
# OnionWire + monero-wallet-rpc
OnionWire is not a wallet. It never holds a seed, a spend key, or a view key.
It talks optional JSON-RPC to a `monero-wallet-rpc` that **you** run, on
loopback, only to:
- hand out a receive subaddress for `/pay` invoices (`create_address`),
- read incoming transfers to verify a peer's receipt (`get_transfers`),
- and — only if you let it — spend for `/tip` (`transfer`).
**Run it view-only, and switch `/tip` off explicitly.** Everything else in this
document explains why, and what breaks when you do.
## 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_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. |
`README.md` carries the operator summary; this file is the long form.
## Recommended topology
```
wallet host (this machine)
┌──────────────────────────────────────────────────────────────┐
│ monero-wallet-rpc --rpc-bind-ip 127.0.0.1 --rpc-login u:p │
│ ▲ HTTP Digest, loopback only │
│ │ │
│ OnionWire (ONIONWIRE_WALLET_NO_SPEND=1) ── /pay, receipts │
│ └── /tip refused locally │
└──────────────────────────────────────────────────────────────┘
```
Loopback is the only address OnionWire will dial. `.onion` RPC URLs are
rejected: there is no Arti dial for the wallet, and a remote wallet would move
your key material off the box.
## Create a view-only wallet
Either path produces a wallet file with the view key only. Keep the seed /
spend key on a machine that is **not** running OnionWire.
With `monero-wallet-cli` (`--generate-from-view-key` prompts for the *standard*
address the view key belongs to, then the secret view key):
```bash
monero-wallet-cli --generate-from-view-key "$HOME/.onionwire-viewonly" \
--daemon-address "$YOUR_MONEROD:18089" --restore-height "$BIRTH_HEIGHT"
# Standard address: 4...
# Secret view key: <hex>
```
Or through a running RPC that was started with `--wallet-dir` (`generate_from_keys`
without `spendkey` writes a watch-only wallet):
```bash
curl -u onionwire:secret http://127.0.0.1:18083/json_rpc \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":"0","method":"generate_from_keys","params":{
"filename":"viewonly","password":"walletpass",
"address":"4...","viewkey":"<hex>","restore_height":<height>}}'
# → "Watch-only wallet has been generated successfully."
```
Then serve it:
```bash
monero-wallet-rpc --wallet-file "$HOME/.onionwire-viewonly" \
--rpc-bind-ip 127.0.0.1 --rpc-bind-port 18083 --rpc-login onionwire:secret \
--daemon-address "$YOUR_MONEROD:18089"
export ONIONWIRE_WALLET_RPC=http://127.0.0.1:18083
export ONIONWIRE_WALLET_RPC_LOGIN=onionwire:secret
export ONIONWIRE_WALLET_NO_SPEND=1
```
Restore the wallet from a height *at or before* its first incoming transaction
— a view-only wallet cannot rescan cheaply from height 0.
## What works, what does not
| Feature | View-only | Spend-capable |
|---|---|---|
| `/pay <xmr>` invoice subaddress (`create_address`) | works | works |
| Receipt verification (`get_transfers`) | works | works |
| Profile `xmr_addr` fallback when RPC is down | works | works |
| `/tip <xmr>` (`transfer`) | **cannot work** | works |
| OnionWire learns your spend key | never | never (it stays in the wallet) |
With `ONIONWIRE_WALLET_NO_SPEND=1` a `/tip` is refused before the RPC is
contacted, with:
```
wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work
```
Without the flag, `/tip` against a view-only wallet fails at the wallet and
OnionWire then asks the wallet directly whether it can spend (see below), so you
get the same sentence instead of a raw RPC error.
## How OnionWire detects view-only over RPC
The signal people usually reach for is `query_key` with `key_type=mnemonic`. It
works, but it is the wrong key to ask for: on a spend-capable wallet it hands
over the whole seed (full spend ability) over loopback HTTP, and it answers
`-43` for wallets that have no mnemonic at all. The spend key is narrower and
just as unambiguous:
```
query_key {"key_type":"spend_key"}
spend-capable → result.key = <hex secret spend key>
view-only → error code -29, "The wallet is watch-only. Cannot retrieve spend key."
```
(`query_key key_type=mnemonic` returns `-29` for a view-only wallet too, so the
two agree — OnionWire asks for the spend key because it is the smaller secret.)
- Method: [`query_key`](https://www.getmonero.org/resources/developer-guides/wallet-rpc.html#query_key)
- `-29` is `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in
[`wallet_rpc_server_error_codes.h`](https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server_error_codes.h)
- The view-only branch is `on_query_key` in
[`wallet_rpc_server.cpp`](https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server.cpp)
OnionWire only calls this **after** a `transfer` has already failed — it never
probes a healthy wallet — and it discards `result.key` immediately. There is no
RPC method that reports "view-only" as a plain field; `query_key` is the
documented signal and this is its only cost: a spend-capable wallet answers with
its spend key over loopback HTTP, which is one more reason to run view-only.
Fail-closed details: if the probe cannot answer (wallet down, `--restricted-rpc`
answers `-7 DENIED` instead), OnionWire surfaces the wallet's own error
unchanged. It never guesses "view-only" from an unrelated failure.
## Why loopback still needs authentication
`--rpc-bind-ip 127.0.0.1` keeps the port off the network; it does **not** keep it
away from other users or processes on the same machine. Any local process can
`connect(127.0.0.1:18083)`.
- OnionWire refuses an RPC that answers HTTP 200 without a Digest challenge, and
refuses URLs without credentials. Unset the credentials and the wallet is open
to every local process — with a spend-capable wallet file, that is a
one-curl drain of your balance.
- `--rpc-login` is HTTP Digest (MD5), so the password is not sent in cleartext,
but Digest gives no confidentiality: a local attacker who can sniff loopback
can replay it. Treat loopback as trusted-ish, not safe.
- Do not log the password, and do not put it in a shell history you share.
Prefer `ONIONWIRE_WALLET_RPC_LOGIN` over userinfo in the URL.
## The spend-authority warning
An OnionWire instance pointed at a **spend-capable** `monero-wallet-rpc` is a
local spend authority: any process that can read the RPC credentials (env var,
`/proc/<pid>/environ`, shell history, a stored URL) can spend the wallet's
balance, and `/tip` gives a chat peer a supported path to ask for a transfer.
That is why view-only plus `ONIONWIRE_WALLET_NO_SPEND=1` is the recommended
default:
- the wallet file holds no spend key, so a stolen wallet file cannot be used to
move funds;
- the RPC credentials grant only receive-address and history reads;
- `/tip` fails locally with a plain message, so nothing in the UI pretends the
spend path exists.
If you want tips to work, understand that you are deliberately making the
OnionWire process able to spend. Give it a **separate hot wallet with a small
balance**, not your savings wallet.
## References
- Monero Wallet RPC reference:
<https://www.getmonero.org/resources/developer-guides/wallet-rpc.html>
- `on_query_key` (view-only → `-29`):
<https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server.cpp>
- `WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29`:
<https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server_error_codes.h>
- `--generate-from-view-key` (incoming-only wallet):
<https://github.com/monero-project/monero/blob/master/src/simplewallet/simplewallet.cpp>
- `generate_from_keys` (watch-only when `spendkey` is omitted):
<https://www.getmonero.org/resources/developer-guides/wallet-rpc.html#generate_from_keys>

View file

@ -23,9 +23,10 @@ pub struct Loc {
const PREFIX: &[u8] = b"loc "; const PREFIX: &[u8] = b"loc ";
pub fn sign(identity_sk: &[u8], onion: &str, ts: i64) -> Result<Loc> { pub fn sign(identity_sk: &[u8], onion: &str, ts: i64) -> Result<Loc> {
let sk_bytes: [u8; 32] = identity_sk // Same one-shot raw identity-secret copy as `profile::sign`; shared so
.try_into() // `Zeroize` covers it here too.
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?; let sk_bytes =
crate::profile::signing_key_bytes(identity_sk).map_err(|e| Error(e.to_string()))?;
let sk = SigningKey::from_bytes(&sk_bytes); let sk = SigningKey::from_bytes(&sk_bytes);
let sig = sk.sign(&sign_msg_v2(onion, ts)).to_bytes().to_vec(); let sig = sk.sign(&sign_msg_v2(onion, ts)).to_bytes().to_vec();
Ok(Loc { Ok(Loc {

View file

@ -1,4 +1,5 @@
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use zeroize::Zeroizing;
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
@ -30,6 +31,23 @@ pub fn validate(display_name: &str, bio: &str, xmr_addr: &str) -> Result<()> {
check_fields(display_name, bio, xmr_addr) check_fields(display_name, bio, xmr_addr)
} }
/// The raw 32-byte identity-secret copy that `ed25519-dalek` needs in order to
/// build a `SigningKey`.
///
/// `SigningKey` wipes its own copy on drop (its default `zeroize` feature);
/// the raw bytes are ours to wipe, so they live in a `Zeroizing` buffer rather
/// than on the stack in a bare `[u8; 32]`. Same pattern as `pay::sign_bytes`
/// and `qr::encode`; `loc::sign` shares this helper for the identical copy it
/// used to make.
pub fn signing_key_bytes(identity_sk: &[u8]) -> Result<Zeroizing<[u8; 32]>> {
if identity_sk.len() != 32 {
return Err(Error("identity secret key must be 32 bytes".into()));
}
let mut bytes = Zeroizing::new([0u8; 32]);
bytes[..].copy_from_slice(identity_sk);
Ok(bytes)
}
pub fn sign( pub fn sign(
identity_sk: &[u8], identity_sk: &[u8],
display_name: &str, display_name: &str,
@ -38,9 +56,7 @@ pub fn sign(
ts: i64, ts: i64,
) -> Result<Profile> { ) -> Result<Profile> {
check_fields(display_name, bio, xmr_addr)?; check_fields(display_name, bio, xmr_addr)?;
let sk_bytes: [u8; 32] = identity_sk let sk_bytes = signing_key_bytes(identity_sk)?;
.try_into()
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?;
let sk = SigningKey::from_bytes(&sk_bytes); let sk = SigningKey::from_bytes(&sk_bytes);
let sig = sk let sig = sk
.sign(&sign_msg_v2(display_name, bio, xmr_addr, ts)) .sign(&sign_msg_v2(display_name, bio, xmr_addr, ts))

View file

@ -1,6 +1,7 @@
use std::collections::HashMap;
use std::io::{self, IsTerminal}; use std::io::{self, IsTerminal};
use std::sync::{Arc, mpsc}; use std::sync::{Arc, mpsc};
use std::time::Duration; use std::time::{Duration, SystemTime, UNIX_EPOCH};
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::layout::{Constraint, Layout, Rect}; use ratatui::layout::{Constraint, Layout, Rect};
@ -8,11 +9,13 @@ use ratatui::style::{Color, Modifier, Style};
use ratatui::symbols::border; use ratatui::symbols::border;
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap}; use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap};
use ratatui::{DefaultTerminal, Frame}; use ratatui::{DefaultTerminal, Frame};
use zeroize::{Zeroize, Zeroizing};
use crate::node::Node; use crate::node::Node;
use crate::outbox::DEFAULT_MAX_ATTEMPTS;
use crate::qr::{self, QrPayload}; use crate::qr::{self, QrPayload};
use crate::sanitize; use crate::sanitize;
use crate::store::{Friend, FriendProfile}; use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus};
const C_ACCENT: Color = Color::Rgb(232, 165, 75); const C_ACCENT: Color = Color::Rgb(232, 165, 75);
const C_TEXT: Color = Color::Rgb(196, 214, 176); const C_TEXT: Color = Color::Rgb(196, 214, 176);
@ -116,6 +119,202 @@ pub fn empty_friend_chat_text() -> &'static str {
"no messages\ntype below, Enter sends" "no messages\ntype below, Enter sends"
} }
// ---------------------------------------------------------------------------
// Delivery state (outbox)
//
// The outbox is the only source of per-message state: `Queued` / `Sending` /
// `Failed` rows are what `Node::outbox_pending` still holds, and a row is
// deleted the moment the send crosses the circuit — so an outbound message with
// no row is `Sent`. No parallel state model, no new wire prefix.
// ---------------------------------------------------------------------------
/// Longest short-form failure reason shown in a chat row.
pub const FAIL_REASON_BUDGET: usize = 24;
/// Marker glyph for one delivery state. ASCII chrome falls back to `ok` for the
/// wordless delivered state; `queued` / `sending` / `failed` already carry their
/// word, so their glyph is dropped rather than invented.
pub fn delivery_glyph(status: &OutboxStatus) -> &'static str {
let ascii = ascii_chrome();
match status {
OutboxStatus::Sent => {
if ascii {
"ok"
} else {
"✓"
}
}
OutboxStatus::Queued => {
if ascii {
""
} else {
"◷"
}
}
OutboxStatus::Sending => {
if ascii {
""
} else {
"»"
}
}
OutboxStatus::Failed(_) => {
if ascii {
""
} else {
"✗"
}
}
}
}
/// Next-attempt age for a queued row, from the absolute `next_attempt_at` the
/// outbox stores.
pub fn retry_in_text(next_in_secs: i64) -> String {
if next_in_secs <= 0 {
"retry now".to_string()
} else if next_in_secs < 60 {
format!("retry {next_in_secs}s")
} else {
format!("retry {}m", (next_in_secs + 59) / 60)
}
}
/// Transport failure text, short form: sanitized, tail of the `a: b: c` chain,
/// capped at `budget` cells so one peer's error cannot blow out the row.
pub fn short_send_reason(why: &str, budget: usize) -> String {
let clean = sanitize::display_text(why.as_bytes());
let tail = clean.rsplit(": ").next().unwrap_or("").trim();
let text = if tail.is_empty() { clean.trim() } else { tail };
truncate_chars(text, budget)
}
/// One row's delivery marker, straight from the outbox state.
pub fn delivery_tag(status: &OutboxStatus, attempts: u32, next_in_secs: i64) -> String {
let glyph = delivery_glyph(status);
let body = match status {
OutboxStatus::Sent => String::new(),
OutboxStatus::Queued => format!(
"queued (try {attempts}/{DEFAULT_MAX_ATTEMPTS}, {})",
retry_in_text(next_in_secs)
),
OutboxStatus::Sending => "sending".to_string(),
OutboxStatus::Failed(why) => {
format!("failed: {}", short_send_reason(why, FAIL_REASON_BUDGET))
}
};
match (glyph.is_empty(), body.is_empty()) {
(_, true) => glyph.to_string(),
(true, false) => body,
(false, false) => format!("{glyph} {body}"),
}
}
/// Footer summary derived from the outbox rows of the selected friend.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct OutboxSummary {
/// `Queued` + `Sending`: rows the worker may still deliver.
pub queued: usize,
/// Terminal failures — these never retry.
pub failed: usize,
/// First terminal failure, for the fail-closed footer copy.
pub first_error: Option<String>,
}
impl OutboxSummary {
/// Footer note, or `None` when nothing is outstanding. Any terminal failure
/// keeps a `send failed` statement so the fail-closed copy stays visible.
pub fn note(&self) -> Option<String> {
let reason = || {
short_send_reason(
self.first_error.as_deref().unwrap_or("unknown"),
FAIL_REASON_BUDGET,
)
};
match (self.queued, self.failed) {
(0, 0) => None,
(queued, 0) => Some(format!("{queued} queued")),
(0, 1) => Some(format!("send failed: {}", reason())),
(0, failed) => Some(format!("send failed: {} ({failed} failed)", reason())),
(queued, _) => Some(format!("{queued} queued, send failed: {}", reason())),
}
}
}
/// Chat transcript with per-message delivery state, plus the footer summary.
///
/// Pending rows are matched to messages by body, newest send first: an
/// outstanding retry is the most recent send of that text, and the outbox holds
/// no message id the UI could join on.
pub fn chat_with_delivery(
msgs: &[Message],
pending: &[OutboxEntry],
now: i64,
) -> (Vec<String>, OutboxSummary) {
let mut summary = OutboxSummary::default();
for entry in pending {
match &entry.status {
OutboxStatus::Failed(why) => {
summary.failed += 1;
summary.first_error.get_or_insert_with(|| why.clone());
}
_ => summary.queued += 1,
}
}
if msgs.is_empty() {
return (
empty_friend_chat_text()
.lines()
.map(str::to_string)
.collect(),
summary,
);
}
let mut by_body: HashMap<&[u8], Vec<&OutboxEntry>> = HashMap::new();
for entry in pending {
by_body
.entry(entry.body.as_slice())
.or_default()
.push(entry);
}
let mut tags: Vec<Option<String>> = vec![None; msgs.len()];
for (i, msg) in msgs.iter().enumerate().rev() {
if msg.dir != "out" {
continue;
}
if let Some(rows) = by_body.get_mut(msg.plaintext.as_slice())
&& let Some(entry) = rows.pop()
{
tags[i] = Some(delivery_tag(
&entry.status,
entry.attempts,
entry.next_attempt_at - now,
));
}
}
let lines = msgs
.iter()
.enumerate()
.map(|(i, msg)| {
let side = if msg.dir == "out" { "you" } else { "them" };
let body = sanitize::display_text(&msg.plaintext);
let tag = match tags[i].clone() {
Some(tag) => tag,
None if msg.dir == "out" => delivery_tag(&OutboxStatus::Sent, 0, 0),
None => String::new(),
};
if tag.is_empty() {
format!("{side}: {body}")
} else {
format!("{side}: {body} {tag}")
}
})
.collect();
(lines, summary)
}
/// Paste overlay copy. Error keeps the resubmit hint. /// Paste overlay copy. Error keeps the resubmit hint.
pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String { pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String {
let hint = match err { let hint = match err {
@ -761,6 +960,78 @@ impl BackupPrompt {
} }
} }
/// The in-progress passphrase on the backup/restore screen: the hidden buffer
/// plus the first entry, kept across the second prompt of the backup flow.
///
/// Both are `Zeroizing<String>`, so the passphrase does not sit in a plain
/// heap `String` for the life of the screen; `close()` wipes eagerly on every
/// exit path (submit, mismatch, cancel) instead of waiting for the screen
/// value to be dropped, and the wrapper covers the paths that cannot call it
/// (Ctrl-Q, a panic).
pub struct PassphraseEntry {
first: Option<Zeroizing<String>>,
buf: Zeroizing<String>,
}
impl Default for PassphraseEntry {
fn default() -> Self {
Self {
first: None,
buf: Zeroizing::new(String::new()),
}
}
}
impl PassphraseEntry {
pub fn new() -> Self {
Self::default()
}
/// Second prompt of the backup flow: the first passphrase was already typed.
pub fn with_first(first: &str) -> Self {
Self {
first: Some(Zeroizing::new(first.to_string())),
..Self::default()
}
}
pub fn push(&mut self, c: char) {
self.buf.push(c);
}
pub fn backspace(&mut self) {
self.buf.pop();
}
/// What the screen echoes back — the passphrase itself is not drawn.
pub fn buf(&self) -> &str {
self.buf.as_str()
}
pub fn first(&self) -> Option<&str> {
self.first.as_deref().map(String::as_str)
}
/// Take the typed passphrase for submission, leaving this entry empty.
pub fn take_buf(&mut self) -> Zeroizing<String> {
std::mem::replace(&mut self.buf, Zeroizing::new(String::new()))
}
/// Take the first-passphrase copy for the confirm comparison.
pub fn take_first(&mut self) -> Option<Zeroizing<String>> {
self.first.take()
}
/// Wipe both buffers: the screen is done with them.
pub fn close(&mut self) {
self.buf.zeroize();
if let Some(first) = self.first.as_mut() {
first.zeroize();
}
self.first = None;
}
}
pub fn backup_screen_text() -> &'static str { pub fn backup_screen_text() -> &'static str {
"Write encrypted identity backup?\n\ "Write encrypted identity backup?\n\
This file is your identity secret. Treat it like the database.\n\ This file is your identity secret. Treat it like the database.\n\
@ -840,8 +1111,7 @@ enum Screen {
Passphrase { Passphrase {
kind: BackupKind, kind: BackupKind,
path: String, path: String,
first: Option<String>, entry: PassphraseEntry,
buf: String,
}, },
Quit { Quit {
prompt: QuitPrompt, prompt: QuitPrompt,
@ -929,6 +1199,7 @@ impl App {
let mut tip_cmd = None; let mut tip_cmd = None;
let mut file_cmd = None; let mut file_cmd = None;
let mut chat_send = None; let mut chat_send = None;
let mut pass_submit = None;
match &mut self.screen { match &mut self.screen {
Screen::Main => match key.code { Screen::Main => match key.code {
KeyCode::Tab => self.focus = self.focus.next(), KeyCode::Tab => self.focus = self.focus.next(),
@ -1090,8 +1361,7 @@ impl App {
self.screen = Screen::Passphrase { self.screen = Screen::Passphrase {
kind, kind,
path: path.clone(), path: path.clone(),
first: None, entry: PassphraseEntry::new(),
buf: String::new(),
}; };
} }
} }
@ -1101,25 +1371,17 @@ impl App {
_ => {} _ => {}
} }
} }
Screen::Passphrase { Screen::Passphrase { kind, path, entry } => match key.code {
kind, KeyCode::Esc => {
path, entry.close();
first, self.screen = Screen::Main;
buf,
} => match key.code {
KeyCode::Esc => self.screen = Screen::Main,
KeyCode::Backspace => {
buf.pop();
} }
KeyCode::Backspace => entry.backspace(),
KeyCode::Enter => { KeyCode::Enter => {
let kind = *kind; pass_submit = Some((*kind, path.clone(), entry.take_first(), entry.take_buf()));
let path = path.clone();
let first = first.clone();
let pass = buf.clone();
self.submit_passphrase(kind, &path, first.as_deref(), &pass)?;
} }
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
buf.push(c); entry.push(c);
} }
_ => {} _ => {}
}, },
@ -1166,6 +1428,9 @@ impl App {
if let Some(text) = chat_send { if let Some(text) = chat_send {
self.send_chat(&text)?; self.send_chat(&text)?;
} }
if let Some((kind, path, first, pass)) = pass_submit {
self.submit_passphrase(kind, &path, first.as_deref().map(String::as_str), &pass)?;
}
Ok(None) Ok(None)
} }
@ -1279,8 +1544,7 @@ impl App {
self.screen = Screen::Passphrase { self.screen = Screen::Passphrase {
kind, kind,
path: path.to_string(), path: path.to_string(),
first: Some(pass.to_string()), entry: PassphraseEntry::with_first(pass),
buf: String::new(),
}; };
} }
} }
@ -1449,11 +1713,13 @@ impl App {
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
self.status_note = Some("sending".into()); self.status_note = Some("sending".into());
std::mem::drop(self.rt.spawn(async move { std::mem::drop(self.rt.spawn(async move {
// send() now reports `Sent`/`Queued`; surfacing `queued` in the // `send()` reports `Sent` when the circuit took it and `Queued` when
// footer is a follow-up card, so this arm keeps today's wording. // the peer's onion is unreachable. The footer then reads the real
// row count from the outbox, so this note is only the first word.
let note = match node.send(&pk, &body).await { let note = match node.send(&pk, &body).await {
Ok(_) => "sent".to_string(), Ok(OutboxStatus::Sent) => "sent".to_string(),
Err(e) => format!("send failed: {e}"), Ok(_) => "queued".to_string(),
Err(e) => format!("send failed: {}", short_send_reason(&e, FAIL_REASON_BUDGET)),
}; };
let _ = tx.send(note); let _ = tx.send(note);
})); }));
@ -1487,9 +1753,9 @@ impl App {
Screen::Wipe { kind, prompt } => draw_wipe(f, *kind, prompt.typed()), Screen::Wipe { kind, prompt } => draw_wipe(f, *kind, prompt.typed()),
Screen::Profile { editor } => draw_profile(f, editor), Screen::Profile { editor } => draw_profile(f, editor),
Screen::ConfirmKeys { kind, prompt, .. } => draw_confirm_keys(f, *kind, prompt.typed()), Screen::ConfirmKeys { kind, prompt, .. } => draw_confirm_keys(f, *kind, prompt.typed()),
Screen::Passphrase { Screen::Passphrase { kind, entry, .. } => {
kind, first, buf, .. draw_passphrase(f, *kind, entry.first().is_some(), entry.buf())
} => draw_passphrase(f, *kind, first.is_some(), buf), }
Screen::Quit { prompt } => draw_quit(f, prompt.typed()), Screen::Quit { prompt } => draw_quit(f, prompt.typed()),
} }
if self.help_open { if self.help_open {
@ -1563,38 +1829,22 @@ impl App {
} }
f.render_stateful_widget(roster, panes[0], &mut roster_state); f.render_stateful_widget(roster, panes[0], &mut roster_state);
let chat_lines = self.chat_lines(); let (chat_lines, summary) = self.chat_view();
let inner_h = panes[1].height.saturating_sub(2); let chat_name = self.friends.get(self.selected).map(|friend| {
let nlines = chat_lines.len(); friend
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16; .petname
let scroll = self.chat_scroll.min(max_scroll); .as_deref()
let overflow = nlines > inner_h as usize && inner_h > 0; .unwrap_or(&friend.fingerprint)
let chat_title = { .to_string()
let name = self.friends.get(self.selected).map(|friend| { });
friend draw_chat(
.petname f,
.as_deref() panes[1],
.unwrap_or(&friend.fingerprint) &chat_lines,
.to_string() chat_name.as_deref(),
}); self.focus == Pane::Chat,
let mut t = match name { self.chat_scroll,
Some(n) => format!("chat {n}"), );
None => "chat".to_string(),
};
if overflow {
let end = (scroll as usize + inner_h as usize).min(nlines);
t.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
}
let mark = if self.focus == Pane::Chat { "> " } else { " " };
format!("{mark}{t}")
};
let chat_text = chat_lines.join("\n");
let chat = Paragraph::new(chat_text)
.style(style_text())
.wrap(Wrap { trim: false })
.scroll((scroll, 0))
.block(self.pane_block(&chat_title, Pane::Chat));
f.render_widget(chat, panes[1]);
let mark = if self.focus == Pane::Composer { let mark = if self.focus == Pane::Composer {
"> " "> "
@ -1618,62 +1868,108 @@ impl App {
cols[3], cols[3],
); );
let footer = self.footer_line(area.width); let footer = self.footer_line(area.width, &summary);
f.render_widget(Paragraph::new(footer).style(style_dim()), cols[4]); f.render_widget(Paragraph::new(footer).style(style_dim()), cols[4]);
} }
fn footer_line(&self, width: u16) -> String { fn footer_line(&self, width: u16, summary: &OutboxSummary) -> String {
// The outbox is the source of truth while anything is outstanding; the
// transient note still covers "sending", "sent file x", "invoice sent".
let note = summary.note().or_else(|| self.status_note.clone());
status_footer( status_footer(
width, width,
&self.me_fp, &self.me_fp,
&self.me_onion, &self.me_onion,
self.status_note.as_deref(), note.as_deref(),
footer_hints(&self.screen), footer_hints(&self.screen),
) )
} }
fn chat_lines(&self) -> Vec<String> { fn chat_view(&self) -> (Vec<String>, OutboxSummary) {
let Some(friend) = self.friends.get(self.selected) else { let Some(friend) = self.friends.get(self.selected) else {
return vec![ return (
"no friends yet".into(), vec![
"F3 paste an invite to add one".into(), "no friends yet".into(),
]; "F3 paste an invite to add one".into(),
],
OutboxSummary::default(),
);
}; };
match self.node.list_messages(&friend.pubkey) { match self.node.list_messages(&friend.pubkey) {
Ok(msgs) if msgs.is_empty() => empty_friend_chat_text() Ok(msgs) => {
.lines() let pending = self.node.outbox_pending(&friend.pubkey).unwrap_or_default();
.map(str::to_string) chat_with_delivery(&msgs, &pending, unix_now_secs())
.collect(), }
Ok(msgs) => msgs Err(e) => (vec![e], OutboxSummary::default()),
.iter()
.map(|m| {
let side = if m.dir == "out" { "you" } else { "them" };
format!("{side}: {}", sanitize::display_text(&m.plaintext))
})
.collect(),
Err(e) => vec![e],
} }
} }
fn pane_block<'a>(&self, title: &'a str, pane: Pane) -> Block<'a> { fn pane_block<'a>(&self, title: &'a str, pane: Pane) -> Block<'a> {
let focused = self.focus == pane; pane_block_for(title, self.focus == pane)
let border = if focused {
style_accent()
} else {
style_border()
};
let title_style = if focused {
style_accent().add_modifier(Modifier::BOLD)
} else {
style_dim()
};
apply_chrome_borders(Block::default())
.border_style(border)
.title(title)
.title_style(title_style)
} }
} }
/// Pane chrome without an `App`: focus is accent border + bold title, never
/// color alone (the `> ` marks come from the callers).
fn pane_block_for(title: &str, focused: bool) -> Block<'_> {
let border = if focused {
style_accent()
} else {
style_border()
};
let title_style = if focused {
style_accent().add_modifier(Modifier::BOLD)
} else {
style_dim()
};
apply_chrome_borders(Block::default())
.border_style(border)
.title(title)
.title_style(title_style)
}
fn unix_now_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
/// Real chat-pane renderer: `App::draw_main` calls this, so width, wrap and
/// delivery-marker behaviour are testable without constructing a `Node`.
pub fn draw_chat(
f: &mut Frame,
area: Rect,
lines: &[String],
name: Option<&str>,
focused: bool,
scroll: u16,
) {
let inner_h = area.height.saturating_sub(2);
let nlines = lines.len();
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16;
let scroll = scroll.min(max_scroll);
let overflow = nlines > inner_h as usize && inner_h > 0;
let mut title = match name {
Some(n) => format!("chat {n}"),
None => "chat".to_string(),
};
if overflow {
let end = (scroll as usize + inner_h as usize).min(nlines);
title.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
}
let mark = if focused { "> " } else { " " };
let title = format!("{mark}{title}");
f.render_widget(
Paragraph::new(lines.join("\n"))
.style(style_text())
.wrap(Wrap { trim: false })
.scroll((scroll, 0))
.block(pane_block_for(&title, focused)),
area,
);
}
/// Status bar: never drop a non-empty `status_note`. Always keep `TOR`, `me:`, `? help`. /// Status bar: never drop a non-empty `status_note`. Always keep `TOR`, `me:`, `? help`.
pub fn status_footer( pub fn status_footer(
width: u16, width: u16,
@ -1689,7 +1985,7 @@ pub fn status_footer(
let mut note = status_note.unwrap_or("").trim().to_string(); let mut note = status_note.unwrap_or("").trim().to_string();
if !note.is_empty() if !note.is_empty()
&& color_mode() == ColorMode::None && color_mode() == ColorMode::None
&& (note.starts_with("send failed") || note == "fingerprint mismatch") && (note.contains("send failed") || note == "fingerprint mismatch")
&& !note.starts_with("! ") && !note.starts_with("! ")
{ {
note = format!("! {note}"); note = format!("! {note}");
@ -2017,3 +2313,66 @@ fn to_hex(bytes: &[u8]) -> String {
fn io_err(e: io::Error) -> String { fn io_err(e: io::Error) -> String {
e.to_string() e.to_string()
} }
#[cfg(test)]
mod passphrase_buffer_tests {
use super::*;
fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
/// The typed passphrase lives in `Zeroizing` buffers, not in bare
/// `String`s that sit in the heap for the life of the screen.
#[test]
fn passphrase_buffers_are_zeroizing() {
let mut entry = PassphraseEntry::new();
entry.push('x');
let _: &Zeroizing<String> = &entry.buf;
let _: &Option<Zeroizing<String>> = &entry.first;
assert_zeroize_on_drop::<Zeroizing<String>>();
}
/// Closing the screen (submit, mismatch or cancel) must leave nothing of
/// the typed passphrase behind in its heap buffer.
#[test]
fn closing_the_passphrase_screen_wipes_the_typed_secret() {
let mut entry = PassphraseEntry::new();
for c in "hunter2-secret".chars() {
entry.push(c);
}
assert_eq!(entry.buf(), "hunter2-secret");
let ptr = entry.buf.as_ptr();
let cap = entry.buf.capacity();
assert!(cap >= 14, "expected a heap buffer, capacity {cap}");
entry.close();
assert!(entry.buf().is_empty(), "buffer not cleared");
// SAFETY: `close()` wipes through `Zeroize`, which zeroes the whole
// capacity and *keeps* the allocation (`Vec::zeroize`: zero the
// elements, clear the length, zero the spare capacity). `entry` still
// owns that buffer, so these `cap` bytes are live memory.
let bytes = unsafe { std::slice::from_raw_parts(ptr, cap) };
assert!(
bytes.iter().all(|b| *b == 0),
"typed passphrase survived close(): {bytes:?}"
);
}
/// The first entry of the two-step backup flow is a secret too, and the
/// screen holds it across the second prompt.
#[test]
fn closing_the_passphrase_screen_drops_the_first_entry_copy() {
let mut entry = PassphraseEntry::with_first("first-typed");
assert_eq!(entry.first(), Some("first-typed"));
entry.close();
assert_eq!(
entry.first(),
None,
"first passphrase copy survived close()"
);
}
}

View file

@ -42,8 +42,18 @@ impl std::fmt::Debug for Endpoint {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Wallet { pub struct Wallet {
endpoint: Option<Endpoint>, endpoint: Option<Endpoint>,
no_spend: bool,
} }
/// 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";
/// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in monero's
/// `src/wallet/wallet_rpc_server_error_codes.h`.
const WATCH_ONLY_CODE: i64 = -29;
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransferRow { pub struct TransferRow {
pub txid: String, pub txid: String,
@ -55,10 +65,17 @@ const RPC_TIMEOUT: Duration = Duration::from_secs(5);
impl Wallet { impl Wallet {
pub fn disabled() -> Self { pub fn disabled() -> Self {
Self { endpoint: None } Self {
endpoint: None,
no_spend: 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.
pub fn from_env() -> Self { pub fn from_env() -> Self {
let no_spend = env_flag("ONIONWIRE_WALLET_NO_SPEND");
match std::env::var("ONIONWIRE_WALLET_RPC") { match std::env::var("ONIONWIRE_WALLET_RPC") {
// The URL can carry `user:pass@` in its userinfo: keep it in a // The URL can carry `user:pass@` in its userinfo: keep it in a
// wiping buffer, not a bare `String`. // wiping buffer, not a bare `String`.
@ -71,23 +88,41 @@ impl Wallet {
match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) { match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) {
Ok(endpoint) => Self { Ok(endpoint) => Self {
endpoint: Some(endpoint), endpoint: Some(endpoint),
no_spend,
}, },
Err(e) => { Err(e) => {
eprintln!("ONIONWIRE_WALLET_RPC: {e}"); eprintln!("ONIONWIRE_WALLET_RPC: {e}");
Self::disabled() Self {
endpoint: None,
no_spend,
}
} }
} }
} }
_ => Self::disabled(), _ => Self {
endpoint: None,
no_spend,
},
} }
} }
pub fn from_url(url: &str) -> Result<Self> { pub fn from_url(url: &str) -> Result<Self> {
Ok(Self { Ok(Self {
endpoint: Some(parse_http_url(url, None)?), endpoint: Some(parse_http_url(url, None)?),
no_spend: false,
}) })
} }
/// 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;
self
}
pub fn no_spend(&self) -> bool {
self.no_spend
}
pub fn configured(&self) -> bool { pub fn configured(&self) -> bool {
self.endpoint.is_some() self.endpoint.is_some()
} }
@ -107,7 +142,10 @@ impl Wallet {
} }
pub async fn transfer(&self, address: &str, amount: u64) -> Result<String> { pub async fn transfer(&self, address: &str, amount: u64) -> Result<String> {
let v = self if self.no_spend {
return Err(Error(VIEW_ONLY_MSG.into()));
}
let sent = self
.rpc( .rpc(
"transfer", "transfer",
serde_json::json!({ serde_json::json!({
@ -115,10 +153,36 @@ impl Wallet {
"account_index": 0 "account_index": 0
}), }),
) )
.await?; .await;
let v = match sent {
Ok(v) => v,
// The wallet's own refusal is opaque, so ask the documented
// pre-transfer signal before surfacing it. Fail closed: if the
// probe cannot answer, the original error stands.
Err(e) => {
if self.view_only().await {
return Err(Error(VIEW_ONLY_MSG.into()));
}
return Err(e);
}
};
json_str(&v, "tx_hash") json_str(&v, "tx_hash")
} }
/// View-only detection over RPC: `query_key` with `key_type=spend_key` is
/// the signal monero actually exposes for a wallet with no spend key.
/// A view-only wallet answers `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (-29)
/// ("Cannot retrieve spend key"); a spend-capable wallet returns the key,
/// which this discards.
/// Source: `src/wallet/wallet_rpc_server.cpp` `on_query_key`.
async fn view_only(&self) -> bool {
matches!(
self.rpc("query_key", serde_json::json!({"key_type": "spend_key"}))
.await,
Err(e) if e.to_string() == VIEW_ONLY_MSG
)
}
pub async fn get_transfers(&self) -> Result<Vec<TransferRow>> { pub async fn get_transfers(&self) -> Result<Vec<TransferRow>> {
let v = self let v = self
.rpc( .rpc(
@ -189,6 +253,17 @@ fn credentials_required() -> Error {
Error("wallet RPC requires credentials (user:pass in URL or ONIONWIRE_WALLET_RPC_LOGIN)".into()) Error("wallet RPC requires credentials (user:pass in URL or ONIONWIRE_WALLET_RPC_LOGIN)".into())
} }
/// `1` / `true` / `yes` / `on` (case-insensitive) mean set; anything else (or
/// unset) means off.
fn env_flag(name: &str) -> bool {
matches!(
std::env::var(name)
.map(|v| v.trim().to_ascii_lowercase())
.as_deref(),
Ok("1" | "true" | "yes" | "on")
)
}
fn parse_login(login: &str) -> Result<(String, Zeroizing<String>)> { fn parse_login(login: &str) -> Result<(String, Zeroizing<String>)> {
let (user, pass) = login.split_once(':').ok_or_else(credentials_required)?; let (user, pass) = login.split_once(':').ok_or_else(credentials_required)?;
if user.is_empty() || pass.is_empty() { if user.is_empty() || pass.is_empty() {
@ -455,6 +530,11 @@ fn parse_json_rpc(raw: &[u8]) -> Result<serde_json::Value> {
.get("message") .get("message")
.and_then(|m| m.as_str()) .and_then(|m| m.as_str())
.unwrap_or("rpc error"); .unwrap_or("rpc error");
// The one RPC-level error we translate: a view-only wallet has no
// spend key (monero `WALLET_RPC_ERROR_CODE_WATCH_ONLY`).
if err.get("code").and_then(|c| c.as_i64()) == Some(WATCH_ONLY_CODE) {
return Err(Error(VIEW_ONLY_MSG.into()));
}
return Err(Error(msg.into())); return Err(Error(msg.into()));
} }
json.get("result") json.get("result")

View file

@ -1,10 +1,13 @@
//! Spec implementation tests for docs/TUI.md (this card). //! Spec implementation tests for docs/TUI.md (this card).
//! Does not own `tests/tui_frames.rs` (PR #23). //! Does not own `tests/tui_frames.rs` (PR #23).
use onionwire::Message;
use onionwire::outbox::{OutboxEntry, OutboxStatus};
use onionwire::qr; use onionwire::qr;
use onionwire::tui::{ use onionwire::tui::{
alert_line, ascii_chrome, draw_share, draw_text_overlay, empty_friend_chat_text, OutboxSummary, alert_line, ascii_chrome, chat_with_delivery, delivery_tag, draw_chat,
help_overlay_text, main_footer_hints, main_header_line, paste_screen_text, roster_col_width, 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,
status_footer, wrap_invite, status_footer, wrap_invite,
}; };
use ratatui::Frame; use ratatui::Frame;
@ -376,3 +379,376 @@ fn ascii_switch_80x24_frame_is_pure_ascii() {
println!("===== AFTER ascii share 80x24 =====\n{screen}"); println!("===== AFTER ascii share 80x24 =====\n{screen}");
unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
} }
// ---------------------------------------------------------------------------
// Outbox delivery state (card t_d9a5b065)
//
// States come from the outbox API (`Outbox::pending` → `Queued` / `Sending` /
// `Failed`; delivered rows are deleted, so absence means `Sent`). No new wire
// prefix, no parallel state model.
// ---------------------------------------------------------------------------
fn out_msg(body: &str) -> Message {
Message {
dir: "out".into(),
plaintext: body.as_bytes().to_vec(),
}
}
fn in_msg(body: &str) -> Message {
Message {
dir: "in".into(),
plaintext: body.as_bytes().to_vec(),
}
}
fn pending_row(
body: &str,
status: OutboxStatus,
attempts: u32,
next_in: i64,
now: i64,
) -> OutboxEntry {
OutboxEntry {
id: 1,
friend_pk: vec![9u8; 32],
message_id: 1,
body: body.as_bytes().to_vec(),
attempts,
next_attempt_at: now + next_in,
created_at: now,
status,
last_error: None,
}
}
fn queued_row(body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry {
pending_row(body, OutboxStatus::Queued, attempts, next_in, now)
}
fn sending_row(body: &str, now: i64) -> OutboxEntry {
pending_row(body, OutboxStatus::Sending, 1, 0, now)
}
fn failed_row(body: &str, why: &str, now: i64) -> OutboxEntry {
pending_row(body, OutboxStatus::Failed(why.into()), 8, 0, now)
}
/// Marker is everything after the two-space separator the render helper uses.
fn marker_of(line: &str) -> &str {
line.rsplit(" ").next().unwrap_or("")
}
/// Force the non-ASCII (unicode glyph) path. Caller holds `ASCII_ENV`.
fn force_unicode_mode() {
unsafe {
std::env::remove_var("ONIONWIRE_ASCII");
std::env::remove_var("NO_COLOR");
}
}
#[test]
fn queued_and_delivered_messages_render_different_markers() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
let now = 1_700_000_000;
let msgs = vec![out_msg("ping"), out_msg("pong")];
let pending = vec![queued_row("pong", 2, 45, now)];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
assert!(
lines[0].contains('✓'),
"delivered row lost its mark: {:?}",
lines[0]
);
assert!(!lines[0].contains("queued"), "{:?}", lines[0]);
assert!(
lines[1].contains('◷'),
"queued row lost its glyph: {:?}",
lines[1]
);
assert!(lines[1].contains("queued"), "{:?}", lines[1]);
assert!(
lines[1].contains("try 2/8"),
"attempt count missing: {:?}",
lines[1]
);
assert!(
lines[1].contains("retry 45s"),
"retry age missing: {:?}",
lines[1]
);
assert_ne!(
marker_of(&lines[0]),
marker_of(&lines[1]),
"queued and delivered must not share a marker"
);
assert_eq!(summary.queued, 1);
assert_eq!(summary.failed, 0);
}
#[test]
fn delivery_markers_have_exercised_ascii_fallbacks() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe {
std::env::set_var("ONIONWIRE_ASCII", "1");
std::env::remove_var("NO_COLOR");
}
let now = 500;
let msgs = vec![
out_msg("alpha"),
out_msg("beta"),
out_msg("gamma"),
out_msg("delta"),
in_msg("epsilon"),
];
let pending = vec![
failed_row("alpha", "connect peer.onion:80: connection timed out", now),
queued_row("beta", 1, 30, now),
sending_row("gamma", now),
];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
for line in &lines {
assert!(
line.is_ascii(),
"ASCII fallback missing, non-ASCII in {line:?}"
);
}
assert_eq!(marker_of(&lines[0]), "failed: connection timed out");
assert_eq!(marker_of(&lines[1]), "queued (try 1/8, retry 30s)");
assert_eq!(marker_of(&lines[2]), "sending");
assert_eq!(marker_of(&lines[3]), "ok", "delivered fallback is `ok`");
assert_eq!(lines[4], "them: epsilon", "inbound rows carry no state");
assert_eq!(summary.queued, 2, "queued + sending are both outstanding");
assert_eq!(summary.failed, 1);
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
}
#[test]
fn retry_age_and_failure_reason_are_short_forms() {
assert_eq!(retry_in_text(45), "retry 45s");
assert_eq!(retry_in_text(59), "retry 59s");
assert_eq!(retry_in_text(60), "retry 1m");
assert_eq!(retry_in_text(720), "retry 12m");
assert_eq!(retry_in_text(0), "retry now");
assert_eq!(retry_in_text(-30), "retry now");
assert_eq!(
short_send_reason("connect abcdef.onion:80: connection timed out", 24),
"connection timed out"
);
let long = short_send_reason("a-really-long-failure-description-here", 12);
assert!(long.chars().count() <= 12, "{long:?}");
assert!(
long.contains('…') || long.contains("..."),
"truncation marker missing: {long:?}"
);
assert_eq!(short_send_reason("nope", 24), "nope");
}
#[test]
fn delivery_tag_reads_the_outbox_status_enum() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
assert_eq!(delivery_tag(&OutboxStatus::Sent, 0, 0), "✓");
assert_eq!(
delivery_tag(&OutboxStatus::Queued, 3, 120),
"◷ queued (try 3/8, retry 2m)"
);
assert_eq!(delivery_tag(&OutboxStatus::Sending, 1, 0), "» sending");
assert_eq!(
delivery_tag(&OutboxStatus::Failed("connect x:80: nope".into()), 8, 0),
"✗ failed: nope"
);
}
#[test]
fn footer_summary_counts_queued_and_keeps_fail_closed() {
let none = OutboxSummary::default();
assert_eq!(none.note(), None);
let queued = OutboxSummary {
queued: 2,
failed: 0,
first_error: None,
};
assert_eq!(queued.note().as_deref(), Some("2 queued"));
let failed = OutboxSummary {
queued: 0,
failed: 1,
first_error: Some("connect peer.onion:80: connection timed out".into()),
};
let note = failed.note().expect("failed rows must produce a note");
assert!(note.starts_with("send failed:"), "{note:?}");
assert!(note.contains("connection timed out"), "{note:?}");
let mixed = OutboxSummary {
queued: 3,
failed: 1,
first_error: Some("connect peer.onion:80: connection timed out".into()),
};
let mixed_note = mixed.note().expect("mixed rows must produce a note");
assert!(mixed_note.contains("3 queued"), "{mixed_note:?}");
assert!(mixed_note.contains("send failed"), "{mixed_note:?}");
// Fail-closed copy stays visible in the real footer at the 80-col floor.
let line = status_footer(80, FP, ONION, Some(&note), main_footer_hints());
assert!(
line.chars().count() <= 80,
"{} {line:?}",
line.chars().count()
);
assert!(line.contains("send failed"), "footer dropped it: {line:?}");
assert!(line.contains("TOR") && line.contains("? help"), "{line:?}");
let queued_line = status_footer(80, FP, ONION, queued.note().as_deref(), main_footer_hints());
assert!(queued_line.contains("2 queued"), "{queued_line:?}");
assert!(queued_line.chars().count() <= 80);
// `! ` ornament (colour off) still lands on the derived failing note.
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe { std::env::set_var("NO_COLOR", "1") };
let no_color = status_footer(80, FP, ONION, Some(&note), main_footer_hints());
assert!(no_color.contains("! send failed"), "{no_color:?}");
unsafe { std::env::remove_var("NO_COLOR") };
}
/// The card's width criterion: draw the real helpers at the documented floor
/// (80x24) and prove nothing in the chat/footer region exceeds the width, and
/// that an over-long row wraps in the pane instead of being clipped.
#[test]
fn chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
let now = 1_700_000_000;
let long = "this is a very long chat line that should wrap inside the chat pane instead of running off the right edge of an 80-column terminal and colliding with the roster border";
let msgs = vec![out_msg("ok"), in_msg("pong"), out_msg(long)];
let pending = vec![queued_row(long, 3, 45, now)];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
for line in lines.iter().take(2) {
assert!(
line.chars().count() <= 80,
"short row wider than 80: {} {line:?}",
line.chars().count()
);
}
let footer = status_footer(
80,
FP,
ONION,
summary.note().as_deref(),
main_footer_hints(),
);
assert!(footer.chars().count() <= 80, "{footer:?}");
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| {
let area = f.area();
let cols = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area);
draw_chat(f, cols[0], &lines, Some("alice"), true, 0);
f.render_widget(Paragraph::new(footer.clone()), cols[1]);
})
.expect("draw");
let buf = terminal.backend().buffer();
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');
}
for (y, row) in screen.lines().enumerate() {
assert!(
row.chars().count() <= 80,
"80x24 chat/footer row {y} wider than the terminal: {} {row:?}",
row.chars().count()
);
}
assert!(
screen.contains('◷'),
"queued glyph missing from frame:\n{screen}"
);
assert!(screen.contains("queued"), "queued word missing:\n{screen}");
assert!(screen.contains('✓'), "delivered glyph missing:\n{screen}");
assert!(
screen.contains("with the roster border"),
"long row was clipped, not wrapped:\n{screen}"
);
assert!(
screen.contains("1 queued"),
"footer summary missing:\n{screen}"
);
println!("===== AFTER outbox 80x24 (real draw_chat + status_footer) =====\n{screen}");
}
/// The renderer consumes the real outbox API, not a hand-written fixture: a
/// genuine unreachable-onion send leaves a `Queued` row, and that row is what
/// the chat line and the footer note are built from.
#[tokio::test]
async fn renders_a_queued_row_from_a_real_outbox_send() {
use onionwire::Store;
use onionwire::outbox::{BoxFut, Deliverer, Outbox};
use std::sync::Arc;
struct Dead;
impl Deliverer for Dead {
fn deliver<'a>(
&'a self,
_onion: &'a str,
_pinned_id: &'a [u8],
_prekey: &'a [u8],
_plaintext: &'a [u8],
) -> BoxFut<'a, Result<(), String>> {
Box::pin(async { Err("connect dead.onion:80: timed out".to_string()) })
}
}
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "tui-spec-pass").expect("open store");
let pk = [1u8; 32];
store
.upsert_friend(&pk, "dead.onion", None)
.expect("friend");
store.set_friend_prekey(&pk, &[7u8; 32]).expect("prekey");
let store = Arc::new(std::sync::Mutex::new(store));
let outbox = Outbox::new(Arc::clone(&store), Arc::new(Dead));
assert_eq!(
outbox.send(&pk, b"queued for a dead peer").await,
Ok(OutboxStatus::Queued)
);
let pending = outbox.pending(&pk).expect("pending rows");
assert_eq!(pending.len(), 1, "one queued row");
let msgs = store
.lock()
.expect("store lock")
.list_messages(&pk)
.expect("messages");
let now = pending[0].next_attempt_at - 45;
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
assert_eq!(lines.len(), 1);
assert!(
lines[0].contains("queued (try 1/8, retry 45s)"),
"real outbox row did not render: {:?}",
lines[0]
);
assert_eq!(summary.note().as_deref(), Some("1 queued"));
// And once a send crosses the circuit the row is gone, so the same message
// renders as delivered.
let (delivered, summary) = chat_with_delivery(&msgs, &[], now);
assert!(delivered[0].contains('✓'), "{:?}", delivered[0]);
assert_eq!(summary.note(), None);
}

View file

@ -1,5 +1,7 @@
//! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod. //! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod.
use std::sync::{Arc, Mutex};
use ed25519_dalek::SigningKey; use ed25519_dalek::SigningKey;
use onionwire::pay; use onionwire::pay;
use onionwire::wallet::{self, TransferRow, Wallet}; use onionwire::wallet::{self, TransferRow, Wallet};
@ -8,6 +10,10 @@ use rand::rngs::OsRng;
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener; 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 { fn row(txid: &str, amount: &str, address: &str) -> TransferRow {
TransferRow { TransferRow {
txid: txid.into(), txid: txid.into(),
@ -241,6 +247,233 @@ async fn oversized_rpc_response_is_err() {
); );
} }
/// Records every request the client sends, answers the Digest challenge and
/// then replies per RPC method. Lets a test assert on the *request log*.
async fn serve_recording(
listener: TcpListener,
log: Arc<Mutex<Vec<String>>>,
reply: Arc<dyn Fn(&str) -> String + Send + Sync>,
) {
loop {
let Ok((mut sock, _)) = listener.accept().await else {
return;
};
let mut buf = vec![0u8; 8192];
let n = sock.read(&mut buf).await.unwrap_or(0);
let req = String::from_utf8_lossy(&buf[..n]).to_string();
log.lock().expect("log").push(req.clone());
if req.contains("Authorization:") {
let body = reply(&rpc_method(&req));
let _ = sock.write_all(http_200_body(&body).as_bytes()).await;
} else {
let _ = sock.write_all(digest_401().as_bytes()).await;
}
}
}
fn rpc_method(req: &str) -> String {
let body = req.split_once("\r\n\r\n").map(|(_, b)| b).unwrap_or(req);
serde_json::from_str::<serde_json::Value>(body.trim())
.ok()
.and_then(|v| v.get("method").and_then(|m| m.as_str()).map(str::to_string))
.unwrap_or_default()
}
fn http_200_body(body: &str) -> String {
format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
}
fn rpc_error(code: i64, message: &str) -> String {
format!(r#"{{"jsonrpc":"2.0","id":"0","error":{{"code":{code},"message":"{message}"}}}}"#)
}
/// JSON-RPC body only (the server wraps it in an HTTP 200).
fn rpc_result(result: &str) -> String {
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#)
}
fn recording_wallet(port: u16) -> Wallet {
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("url")
}
/// The wallet mock speaks the two methods `/tip` can reach, and refuses the
/// local `transfer` before any socket is opened.
#[tokio::test]
async fn no_spend_mode_refuses_transfer_with_no_rpc_request() {
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(|_| rpc_result(r#"{"tx_hash":"abc123"}"#)),
));
let w = recording_wallet(port).with_no_spend(true);
assert!(w.no_spend());
let err = w
.transfer(
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
1,
)
.await
.unwrap_err()
.to_string();
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:?}");
// Positive control: the recorder is live, so the emptiness above is real.
let _ = w.get_address().await;
assert!(!log.lock().expect("log").is_empty(), "recorder saw nothing");
}
/// `/pay` (subaddress) and receipt verification (`get_transfers`) keep working
/// with the no-spend flag on — only `transfer` is refused.
#[tokio::test]
async fn no_spend_mode_keeps_invoice_and_receipt_paths_working() {
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 {
"create_address" => rpc_result(
r#"{"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}"#,
),
"get_transfers" => rpc_result(
r#"{"in":[{"txid":"deadbeef","amount":5,"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}],"pending":[]}"#,
),
_ => rpc_result(r#"{}"#),
}),
));
let w = recording_wallet(port).with_no_spend(true);
let created = w.create_address().await.expect("create_address");
assert!(created.starts_with('8'), "got {created}");
let rows = w.get_transfers().await.expect("get_transfers");
assert!(wallet::transfers_match(&rows, "deadbeef", "5", &created));
let seen = log.lock().expect("log").clone();
assert!(
seen.iter()
.any(|r| r.contains("\"method\":\"create_address\"")),
"recorder must have seen the invoice path: {seen:?}"
);
assert!(
!seen.iter().any(|r| r.contains("\"method\":\"transfer\"")),
"transfer must never be dialed in no-spend mode"
);
}
/// A view-only wallet refuses `transfer` with its own opaque error. The
/// pre-transfer signal is `query_key` key_type=spend_key (Monero answers
/// WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29), so /tip must say so plainly.
#[tokio::test]
async fn view_only_wallet_maps_transfer_failure_to_clear_message() {
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 {
"query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."),
_ => rpc_error(-18, "No transaction created"),
}),
));
let w = recording_wallet(port);
assert!(!w.no_spend());
let err = w
.transfer(
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
1,
)
.await
.unwrap_err()
.to_string();
assert!(err.to_ascii_lowercase().contains("view-only"), "got {err}");
let seen = log.lock().expect("log").clone();
assert!(
seen.iter().any(|r| r.contains("\"method\":\"query_key\"")),
"must ask the RPC-side signal: {seen:?}"
);
}
/// A spend-capable wallet must keep its real error: no fabricated detection.
#[tokio::test]
async fn spend_capable_wallet_keeps_the_original_transfer_error() {
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 {
"query_key" => rpc_result(r#"{"key":"00112233"}"#),
_ => rpc_error(-18, "No transaction created"),
}),
));
let err = recording_wallet(port)
.transfer(
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
1,
)
.await
.unwrap_err()
.to_string();
assert!(err.contains("No transaction created"), "got {err}");
assert!(!err.to_ascii_lowercase().contains("view-only"), "got {err}");
}
/// F5 must not regress: an open RPC (HTTP 200, no Digest challenge) is refused.
#[tokio::test]
async fn open_rpc_without_digest_challenge_is_still_refused() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let canned = http_200_body(
r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}}"#,
);
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(canned.as_bytes()).await;
});
let err = recording_wallet(port)
.get_address()
.await
.unwrap_err()
.to_string();
assert!(err.to_ascii_lowercase().contains("digest"), "got {err}");
}
/// `ONIONWIRE_WALLET_NO_SPEND` is the operator-facing switch.
#[test]
fn from_env_reads_no_spend_flag() {
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::set_var("ONIONWIRE_WALLET_NO_SPEND", "1");
}
let on = Wallet::from_env();
assert!(on.no_spend(), "flag 1 must mean no-spend");
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "true") };
assert!(Wallet::from_env().no_spend(), "\"true\" must mean no-spend");
for off in ["0", "no", "off"] {
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", off) };
assert!(!Wallet::from_env().no_spend(), "{off} must be off");
}
unsafe {
std::env::remove_var("ONIONWIRE_WALLET_NO_SPEND");
std::env::remove_var("ONIONWIRE_WALLET_RPC");
}
assert!(!Wallet::from_env().no_spend(), "unset must be off");
}
fn digest_401() -> String { fn digest_401() -> String {
"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into() "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into()
} }

View file

@ -5,6 +5,7 @@
//! Noise handshake/transport state that lives inside `snow`. //! Noise handshake/transport state that lives inside `snow`.
use onionwire::backup::BackupKeys; use onionwire::backup::BackupKeys;
use onionwire::profile;
use onionwire::session::Keys; use onionwire::session::Keys;
use onionwire::wallet::Wallet; use onionwire::wallet::Wallet;
use onionwire::Store; use onionwire::Store;
@ -52,6 +53,20 @@ unsafe fn drop_in_place_and_peek_identity_sk(v: &mut Keys) -> [u8; 32] {
} }
} }
/// Drops a `Zeroizing<[u8; 32]>` in place and reads its buffer back.
///
/// SAFETY: only for `ManuallyDrop<Zeroizing<[u8; 32]>>` locals — same contract
/// as `drop_in_place_and_peek_identity_sk`.
unsafe fn drop_in_place_and_peek_zeroizing_u8x32(v: &mut Zeroizing<[u8; 32]>) -> [u8; 32] {
let p: *const [u8; 32] = &**v;
// SAFETY: the caller guarantees `v` is dropped exactly once and is still
// alive at its own address when read back.
unsafe {
std::ptr::drop_in_place(v as *mut Zeroizing<[u8; 32]>);
std::ptr::read_volatile(p)
}
}
/// Drop behaviour, not a comment: after the value drops, the local secret key /// Drop behaviour, not a comment: after the value drops, the local secret key
/// material that feeds the Noise IK handshake is gone from its memory. /// material that feeds the Noise IK handshake is gone from its memory.
#[test] #[test]
@ -116,3 +131,27 @@ fn wallet_endpoint_debug_redacts_the_rpc_password() {
); );
assert!(dbg.contains("<redacted>"), "{dbg}"); assert!(dbg.contains("<redacted>"), "{dbg}");
} }
/// `profile::sign` needs a raw 32-byte copy of the identity secret to build the
/// dalek `SigningKey`. That copy is a `Zeroizing` buffer, not a bare array that
/// stays on the stack until the function returns.
#[test]
fn profile_signing_key_bytes_are_zeroizing_and_wipe() {
let secret = [0x5au8; 32];
let bytes = profile::signing_key_bytes(&secret).expect("32 bytes");
let _: &Zeroizing<[u8; 32]> = &bytes;
assert_eq!(&bytes[..], &secret[..], "buffer must hold the secret");
let mut probe = std::mem::ManuallyDrop::new(bytes);
let after = unsafe { drop_in_place_and_peek_zeroizing_u8x32(&mut probe) };
assert_eq!(after, [0u8; 32], "identity secret survived its drop");
}
/// A length-mismatched secret is an error, not a truncated/padded key.
#[test]
fn profile_signing_key_bytes_rejects_a_short_secret() {
assert!(profile::signing_key_bytes(&[7u8; 31]).is_err());
assert!(profile::signing_key_bytes(&[7u8; 33]).is_err());
}