Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8eed7b1e7e |
||
| ee5b25488b | |||
|
|
d7e91f850a |
||
| 7cd316b65f | |||
| 3f62734efd | |||
|
|
8331a2dde6 |
||
|
|
2ab4b69574 |
9 changed files with 2900 additions and 144 deletions
|
|
@ -115,7 +115,17 @@ the app does not pick a public remote node for them.
|
|||
- **Loopback** — same privacy as (1); the user owns `monerod`.
|
||||
- **`.onion`** — chain traffic over Tor through a localhost SOCKS5 listener
|
||||
the app provides for the wallet child (not the messenger’s Arti
|
||||
`connect()`, and not a C-tor fallback for chat). Tor hides the transport.
|
||||
`connect()`, and not a C-tor fallback for chat). That listener is the
|
||||
bundled `arti` **binary** run as a child (`arti proxy -p <port>`) — a
|
||||
second, separate Tor client with its own state and cache dirs, because
|
||||
`arti-client` 0.46 exposes no SOCKS listener API. It is TCP loopback only
|
||||
(`arti proxy -p` binds `127.0.0.1`/`::1`; arti 2.6.0 / `tor-config` 0.46
|
||||
have no Unix-socket listen target — arti#1965), and the port is usable by
|
||||
any local process at the user's privilege level: it is an app-private port,
|
||||
not an access-controlled one. The app gates the spawn on the unlocked store
|
||||
and waits ≤20s for the listener to accept before starting the wallet child,
|
||||
so a dead proxy fails visibly instead of hanging. The SOCKS child stops
|
||||
with the wallet child. Tor hides the transport.
|
||||
The daemon operator still sees the wallet’s addresses during sync. The
|
||||
host is the trust boundary.
|
||||
- **Clearnet** — only if the user typed it. Not a default, not implied.
|
||||
|
|
@ -145,7 +155,11 @@ That socket is the app talking to the wallet process, not to the chain.
|
|||
**Chain** traffic is the wallet child’s connection to a Monero daemon. It is
|
||||
off unless the user opted into a wallet and chose a chain source: spawned local
|
||||
`monerod` (loopback), or a daemon address they entered. A `.onion` daemon is
|
||||
reached through a localhost SOCKS5 proxy used only by that wallet child. A
|
||||
reached through a localhost SOCKS5 proxy used only by that wallet child: the
|
||||
bundled `arti` binary run as `arti proxy -p <port>`, whose `--proxy` target is
|
||||
`127.0.0.1` and whose `.onion` name travels inside the SOCKS request (Monero's
|
||||
SOCKS5 client sends the domain-name form, so no local DNS runs on it). The
|
||||
messenger's in-process Arti client is never handed to the wallet child. A
|
||||
clearnet daemon address is an explicit user choice — a clearnet socket they
|
||||
asked for — not the messenger path and not a hidden default.
|
||||
|
||||
|
|
|
|||
231
docs/WALLET.md
231
docs/WALLET.md
|
|
@ -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,224 @@ 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`.
|
||||
- **`arti`** is spawned as a SOCKS child only when the chain source is a
|
||||
`.onion` daemon: `arti proxy -p <port>` (see below).
|
||||
- `--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 (see *Chain traffic over Tor* below). 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.
|
||||
|
||||
### Chain traffic over Tor (`.onion` daemons)
|
||||
|
||||
A `.onion` daemon cannot be dialled directly, and OnionWire does not fall back
|
||||
to a clearnet resolve. The wallet child is an external C++ binary, so it reaches
|
||||
Tor the only way it can: through a SOCKS proxy the app provides.
|
||||
|
||||
- The app runs the **bundled `arti` binary** as a child:
|
||||
`arti proxy -p <random free loopback port>`. `arti-client` 0.46 has no SOCKS
|
||||
listener API — the SOCKS listener lives in the `arti` *binary* — so this is a
|
||||
second, separate Tor client, not the messenger's in-process one. There is no
|
||||
C-tor and no system `tor`.
|
||||
- The listener is **TCP loopback only**. `arti proxy -p <port>` binds localhost
|
||||
(`127.0.0.1` and `::1`) and nothing else, and there is nothing safer to
|
||||
prefer: `arti` 2.6.0 / `tor-config` 0.46 have no Unix-socket listen target
|
||||
(`Listen` is IP-only; arti's own port record calls AF_UNIX future work,
|
||||
arti#1965). The port is app-private in practice, but any local process with
|
||||
user-level access can also use it — that is the honest statement of the
|
||||
boundary, not a claim of access control.
|
||||
- The wallet child is then spawned with
|
||||
`--proxy socks5://127.0.0.1:<port>` **and** `--daemon-address <onion>:<port>`.
|
||||
The `socks5://` scheme is explicit: Monero's `--proxy` defaults to SOCKS4a for
|
||||
a bare `host:port` (`docs/proxies.md` in the Monero tree). The `.onion` name
|
||||
goes to the proxy inside the SOCKS request — Monero's SOCKS5 client uses the
|
||||
domain-name form — so **no local DNS** runs on the onion target.
|
||||
- The SOCKS child gets **its own state and cache dirs**
|
||||
(`$ONIONWIRE_HOME/wallet/arti-socks/{state,cache}`). The messenger's Arti
|
||||
state is not shared with it.
|
||||
- Starting it is gated on the same credential material as everything else: the
|
||||
SOCKS child is only spawned from `WalletChild::start(&store)`, which needs the
|
||||
already-unlocked store.
|
||||
- The app waits **up to 20s** for the SOCKS listener to accept a connection
|
||||
before it spawns the wallet child. A dead proxy is a visible error, not a
|
||||
wallet screen that hangs dialling a daemon. Arti binds its listener before it
|
||||
bootstraps, so this is a listener check, not a Tor-bootstrap check.
|
||||
- The SOCKS child stops with the wallet child; a killed wallet child leaves no
|
||||
orphaned listener behind.
|
||||
|
||||
**Tor hides the transport, not the host.** The daemon operator still sees the
|
||||
wallet's addresses (and the transaction set it is scanning) during sync. A
|
||||
`.onion` address protects the path between you and that operator, nothing more.
|
||||
|
||||
The TUI copy for a chain source says this in one line
|
||||
(`WalletChild::chain_copy`): `.onion` → "over Tor … the daemon operator still
|
||||
sees your addresses during sync"; clearnet → "the daemon operator and your ISP
|
||||
see the traffic".
|
||||
|
||||
### 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 +269,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 /
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
185
src/node.rs
185
src/node.rs
|
|
@ -24,7 +24,7 @@ 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::wallet::{self, Readiness, Wallet, WalletConfig, WalletStatus};
|
||||
|
||||
pub struct RotateResult {
|
||||
pub notified: usize,
|
||||
|
|
@ -77,7 +77,12 @@ 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>,
|
||||
incoming_limit: Mutex<TokenBucket>,
|
||||
inbox: Mutex<file::Inbox>,
|
||||
outbox: Arc<Outbox>,
|
||||
|
|
@ -111,6 +116,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 +148,8 @@ 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),
|
||||
incoming_limit: Mutex::new(TokenBucket::default()),
|
||||
inbox: Mutex::new(inbox),
|
||||
outbox: Arc::clone(&outbox),
|
||||
|
|
@ -251,7 +261,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 +458,113 @@ impl Node {
|
|||
.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(())
|
||||
}
|
||||
|
||||
/// 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 +665,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 +680,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 +719,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 +740,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 +758,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 +780,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 +797,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 +809,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 +947,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 +1169,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,
|
||||
|
|
@ -1219,4 +1337,3 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool {
|
|||
}
|
||||
false
|
||||
}
|
||||
|
||||
|
|
|
|||
219
src/store.rs
219
src/store.rs
|
|
@ -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"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
501
src/wallet.rs
501
src/wallet.rs
|
|
@ -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()))?
|
||||
}
|
||||
|
|
|
|||
1320
src/wallet_child.rs
Normal file
1320
src/wallet_child.rs
Normal file
File diff suppressed because it is too large
Load diff
560
tests/wallet.rs
560
tests/wallet.rs
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue