wallet: actually open the wallet file, and remember its passphrase
All checks were successful
ci / test (pull_request) Successful in 6m14s
ci / sdk (pull_request) Successful in 1m44s
android-ci / android (pull_request) Successful in 12m56s
ci / fuzz (pull_request) Successful in 5m1s

`monero-wallet-rpc` starts with no wallet open and keeps one only for the
life of its process, so a restart, a Lock/unlock or a wallet re-point left
a live child answering `-13 No wallet file` to every read while the file
sat on disk. The app now opens the configured catalogue file itself
(`Wallet::open_wallet`, over RPC — never `--wallet-file`/`--password` on
argv, which `ps` exposes) after the child is up, and keeps the passphrase
that does it, sealed with the store data key beside the RPC creds under
its own AAD.

- core: `Wallet::open_wallet`, `WalletConfig::wallet_passphrase`
  (+ `with_wallet_passphrase`, redacted Debug, kept out of the endpoint
  config), `Error::is_unreachable` for the one retryable class (the port
  binds a moment after spawn; a timeout is not a start in progress).
- store: `wallet_config.sealed_passphrase` column (additive, AAD
  `onionwire-store-v1:wallet-passphrase`), read-modify-written so the
  endpoint/login survive; `wallet_save_config` keeps the stored one.
- node: `start_wallet_child` opens the file, `open_wallet_with_passphrase`
  opens a file with a passphrase the user just typed and seals it only
  once a live daemon accepted it, `wallet_status` grows `wallet_open` and
  `needs_passphrase`. A child the RPC refuses is stopped rather than left
  inert; an install with no stored passphrase still starts, and says so.
- tui: one-shot prompt (`WalletSetup::UnlockPass`) on a wallet that needs
  it, reachable from the saved-wallet picker and from `s`.
- sdk: `openWalletWithPassphrase`, the two status fields, README flow.
- docs: WALLET/THREAT_MODEL/README — the passphrase is kept, and the
  consequence (the store passphrase is sufficient to spend) is stated
  rather than implied.

Tests: 4 new node tests drive a real child lifecycle against a loopback
wallet RPC (open on restart, no open without a passphrase, refused
passphrase, sealed-on-success), a `tests/wallet.rs` test asserts the bytes
sent (`open_wallet` + filename + password), and `tests/store.rs` covers
the sealed column and the plaintext->encrypted upgrade with it set.
Mutation-checked: stubbing the two open paths fails all four.
This commit is contained in:
agent 2026-09-22 12:52:08 -04:00
commit ed29131a67
No known key found for this signature in database
12 changed files with 1262 additions and 54 deletions

View file

@ -323,8 +323,16 @@ Peer onion down → `/pay` and `/tip` fail. A queued invoice does not exist.
`F6` then `c` / `/wallet create` generates a spend-capable wallet and shows the `F6` then `c` / `/wallet create` generates a spend-capable wallet and shows the
25-word seed **once**. `F6` then `i` / `/wallet import` restores from a seed. 25-word seed **once**. `F6` then `i` / `/wallet import` restores from a seed.
Type `SPEND` then `SEEN` on create. The in-app filename is `onionwire`; the RPC Type `SPEND` then `SEEN` on create. Each wallet gets its own file name
must be started with `--wallet-dir`. (`onionwire-1`, `onionwire-2`, …); the RPC must be started with `--wallet-dir`.
`monero-wallet-rpc` keeps a wallet open only for the life of one process, so the
app opens the configured file itself after the child is up (`open_wallet`) — and
the passphrase that does it is kept, sealed in the store beside the RPC creds.
That is deliberate and it means the store passphrase is enough to spend; see
[docs/THREAT_MODEL.md](docs/THREAT_MODEL.md) and
[docs/WALLET.md](docs/WALLET.md). A wallet the app holds no passphrase for still
starts — the status reports `needs passphrase` and the app prompts for it once.
## Backup / restore ## Backup / restore

View file

@ -111,6 +111,15 @@ val active: String? = wire.activeWalletFilename() // the open file, or null
val open = wallets.firstOrNull { it.walletFilename == active } val open = wallets.firstOrNull { it.walletFilename == active }
wire.openWallet("onionwire-2") // may restart a running wallet child; a name wire.openWallet("onionwire-2") // may restart a running wallet child; a name
// outside the catalogue is refused // outside the catalogue is refused
// A wallet child is up but its file is not open -> the child answers `-13 No
// wallet file` to every read. `walletStatus()` says which:
val st: WalletChildStatus = wire.walletStatus()
if (st.running && !st.walletOpen && st.needsPassphrase) {
val pass = askForTheWalletPassphrase() // your own input surface, echo off
wire.openWalletWithPassphrase(active!!, pass) // stored (sealed) on success;
// a refused passphrase is an
// error and is NOT stored
}
val keys: WalletKeys = wire.walletKeys() // the OPEN wallet's private keys val keys: WalletKeys = wire.walletKeys() // the OPEN wallet's private keys
// keys.spendKey == null -> a view-only wallet (the RPC's -29 watch-only answer). // keys.spendKey == null -> a view-only wallet (the RPC's -29 watch-only answer).
// That is not an error. The seed (`walletSeed()`) and these keys always belong // That is not an error. The seed (`walletSeed()`) and these keys always belong

View file

@ -574,6 +574,35 @@ impl Wire {
self.node()?.open_wallet(&filename).map_err(WireError::new) self.node()?.open_wallet(&filename).map_err(WireError::new)
} }
/// Open a saved wallet with a passphrase the user just typed, and remember
/// it (sealed) once the wallet daemon has accepted it.
///
/// This is what ends a [`WalletChildStatus`] with
/// `needs_passphrase = true` — a wallet created before the passphrase was
/// stored, or created on another install. After it succeeds, every later
/// [`Wire::start_wallet_child`] opens the file on its own.
///
/// Same refusals as [`Wire::open_wallet`]: a `filename` the catalogue does
/// not hold, an empty passphrase, or no configured wallet RPC at all are
/// `WireError.Failed` before anything is dialled. A passphrase the daemon
/// refuses is reported as such, and is **not** stored — the file stays
/// `needs_passphrase`. Runs on `spawn_blocking`: the RPC can wait for a
/// freshly spawned child to bind. `WireError.Stopped` after `shutdown`.
pub async fn open_wallet_with_passphrase(
&self,
filename: String,
passphrase: String,
) -> WResult<()> {
let node = self.node()?;
let blocking = node.clone();
tokio::task::spawn_blocking(move || {
blocking.open_wallet_with_passphrase(&filename, &passphrase)
})
.await
.map_err(|e| WireError::new(format!("open wallet join: {e}")))?
.map_err(WireError::new)
}
/// The wallet file the child is currently pointed at, or `None` when no /// The wallet file the child is currently pointed at, or `None` when no
/// wallet-child settings were ever stored (a fresh install has no open /// wallet-child settings were ever stored (a fresh install has no open
/// wallet). /// wallet).
@ -1029,6 +1058,8 @@ fn child_status(
WalletChildStatus { WalletChildStatus {
state: status.state.as_str().to_string(), state: status.state.as_str().to_string(),
running: status.running, running: status.running,
wallet_open: status.wallet_open,
needs_passphrase: status.needs_passphrase,
configured: status.configured, configured: status.configured,
chain_source: status.chain_source, chain_source: status.chain_source,
chain_in_process: in_process, chain_in_process: in_process,
@ -1322,6 +1353,16 @@ pub struct WalletChildStatus {
pub state: String, pub state: String,
/// A `monero-wallet-rpc` child is alive right now. /// A `monero-wallet-rpc` child is alive right now.
pub running: bool, pub running: bool,
/// The wallet **file** the child is pointed at is open in that RPC. A live
/// child is not a usable wallet: `monero-wallet-rpc` starts with no wallet
/// open, and every read then answers `-13 No wallet file`. `false` for an
/// off/exited child, and while `needs_passphrase` holds.
pub wallet_open: bool,
/// A saved wallet is configured but not open, because this install holds no
/// passphrase that opens it (or the one it holds was refused). Show the
/// passphrase prompt and call [`Wire::open_wallet_with_passphrase`]; it is
/// not a start failure and the child is still running.
pub needs_passphrase: bool,
/// A chain source is configured (anything but receive-only). /// A chain source is configured (anything but receive-only).
pub configured: bool, pub configured: bool,
/// The chain-source label. /// The chain-source label.
@ -2161,6 +2202,8 @@ mod tests {
onionwire::wallet_child::WalletChildStatus { onionwire::wallet_child::WalletChildStatus {
state, state,
running: true, running: true,
wallet_open: true,
needs_passphrase: false,
configured: true, configured: true,
chain_source: "in-process node".to_string(), chain_source: "in-process node".to_string(),
height: 0, height: 0,
@ -2262,6 +2305,42 @@ mod tests {
assert_eq!(status.target_height, 0); assert_eq!(status.target_height, 0);
} }
/// The two states a client has to tell apart, mapped from the core: a child
/// whose wallet file is open, and one that is live but waiting for its
/// passphrase (a wallet created before the passphrase was stored).
#[test]
fn a_locked_wallet_is_reported_as_needing_a_passphrase_not_as_off() {
let locked = onionwire::wallet_child::WalletChildStatus {
state: WalletChildState::Connecting,
running: true,
wallet_open: false,
needs_passphrase: true,
configured: true,
chain_source: "remote daemon".to_string(),
height: 0,
target_height: 0,
last_error: Some("wallet file onionwire-1 is not open".to_string()),
};
let got = child_status(locked, &ChainSource::None);
assert!(
got.running,
"the child is up, it is the wallet that is not open"
);
assert!(!got.wallet_open, "{got:?}");
assert!(got.needs_passphrase, "{got:?}");
assert_eq!(got.state, "connecting");
let open = onionwire::wallet_child::WalletChildStatus {
wallet_open: true,
needs_passphrase: false,
last_error: None,
..core_status(WalletChildState::Ready)
};
let got = child_status(open, &ChainSource::None);
assert!(got.wallet_open, "{got:?}");
assert!(!got.needs_passphrase, "{got:?}");
}
/// A live probe on a node with no child is `off` — the same record the /// A live probe on a node with no child is `off` — the same record the
/// cheap read reports — never an error and never an invented state. /// cheap read reports — never an error and never an invented state.
/// ///
@ -2279,6 +2358,8 @@ mod tests {
let core = onionwire::wallet_child::WalletChildStatus { let core = onionwire::wallet_child::WalletChildStatus {
state: WalletChildState::Off, state: WalletChildState::Off,
running: false, running: false,
wallet_open: false,
needs_passphrase: false,
configured: false, configured: false,
chain_source: "receive-only".to_string(), chain_source: "receive-only".to_string(),
height: 0, height: 0,
@ -2289,6 +2370,8 @@ mod tests {
let want = WalletChildStatus { let want = WalletChildStatus {
state: "off".to_string(), state: "off".to_string(),
running: false, running: false,
wallet_open: false,
needs_passphrase: false,
configured: false, configured: false,
chain_source: "receive-only".to_string(), chain_source: "receive-only".to_string(),
chain_in_process: false, chain_in_process: false,
@ -2307,6 +2390,8 @@ mod tests {
] { ] {
assert_eq!(got.state, want.state); assert_eq!(got.state, want.state);
assert_eq!(got.running, want.running); assert_eq!(got.running, want.running);
assert_eq!(got.wallet_open, want.wallet_open);
assert_eq!(got.needs_passphrase, want.needs_passphrase);
assert_eq!(got.configured, want.configured); assert_eq!(got.configured, want.configured);
assert_eq!(got.chain_source, want.chain_source); assert_eq!(got.chain_source, want.chain_source);
assert_eq!(got.chain_in_process, want.chain_in_process); assert_eq!(got.chain_in_process, want.chain_in_process);

View file

@ -171,6 +171,17 @@ watch-only wallet detected over RPC via `query_key spend_key` → `-29`).
seed-backed spend-capable wallet makes OnionWire a **local spend authority** seed-backed spend-capable wallet makes OnionWire a **local spend authority**
for that file: anyone with the wallet passphrase or the wallet-RPC credentials for that file: anyone with the wallet passphrase or the wallet-RPC credentials
can move the balance, and `/tip` is a supported way for a chat peer to get paid. can move the balance, and `/tip` is a supported way for a chat peer to get paid.
Those credentials are sealed with the store data key (SQLCipher plus a per-row
AEAD), and so is the **wallet-file passphrase**: it is kept in the same sealed
row, because `monero-wallet-rpc` holds a wallet only for the life of one process
and reopening the file needs it. That is a deliberate decision with a real
consequence — **whoever can unlock the store can spend**: the store passphrase
(or its Keystore wrapper) is now sufficient, and there is no second secret
standing between a seized unlocked device and the wallet's balance. Nothing else
changes: `/tip` still refuses on a view-only wallet before any dial, the
spend-authority warning is still unavoidable at create/restore, the passphrase is
never logged, never in an error string and never on a process argv, and `/wipe`
keeps the wallet file and its passphrase exactly as it kept the file before.
The spend-authority warning is unavoidable at that create/restore step. Loopback The spend-authority warning is unavoidable at that create/restore step. Loopback
binding is not an authorization boundary. Back up the seed; do not leave a binding is not an authorization boundary. Back up the seed; do not leave a
spend-capable wallet on a device you do not trust; a separate hot wallet with a spend-capable wallet on a device you do not trust; a separate hot wallet with a

View file

@ -41,7 +41,10 @@ env var:
- **`monero-wallet-rpc`** is spawned with `--rpc-bind-ip 127.0.0.1`, a **random - **`monero-wallet-rpc`** is spawned with `--rpc-bind-ip 127.0.0.1`, a **random
free loopback port**, a generated `--rpc-login` (`user:pass`, random free loopback port**, a generated `--rpc-login` (`user:pass`, random
`[a-z0-9]`), and `--wallet-dir $ONIONWIRE_HOME/wallet`. `[a-z0-9]`), and `--wallet-dir $ONIONWIRE_HOME/wallet`. No `--wallet-file` and
no `--password`: argv is world-readable to the same user through `ps`, so the
wallet is opened **over RPC** (`open_wallet`) once the child is up, and never
named on the command line.
- **`monerod`** is spawned when the chain source is *local*: - **`monerod`** is spawned when the chain source is *local*:
`--non-interactive --data-dir <datadir> --rpc-bind-ip 127.0.0.1 --rpc-bind-port `--non-interactive --data-dir <datadir> --rpc-bind-ip 127.0.0.1 --rpc-bind-port
18081`. The wallet child dials `127.0.0.1:18081`. 18081`. The wallet child dials `127.0.0.1:18081`.
@ -55,21 +58,48 @@ env var:
Generated `user:pass` is sealed with the store data key in the SQLCipher Generated `user:pass` is sealed with the store data key in the SQLCipher
`wallet_child` table. It never appears in `ONIONWIRE_WALLET_RPC`. `wallet_child` table. It never appears in `ONIONWIRE_WALLET_RPC`.
The wallet passphrase for `create_wallet` / `restore_deterministic_wallet` is `monero-wallet-rpc` starts with **no wallet open** and keeps one open only for
your runtime choice, not stored by the app. the life of its process, so a restart (app relaunch, Lock/unlock, a wallet
re-point) would otherwise answer every read with `-13 No wallet file` while the
file sits on disk. After the child is up the app therefore issues `open_wallet`
for the configured catalogue row.
That needs the passphrase, and the app **keeps it**: the passphrase you type at
create/import (or the one you enter once for a wallet that predates this) is
sealed with the store data key in the SQLCipher `wallet_config` row, beside the
RPC creds, under its own AAD. It is never logged, never put in an error string,
and never on a process argv. The consequence is deliberate and stated in
[THREAT_MODEL.md](THREAT_MODEL.md): **the store passphrase is now sufficient to
spend** — an attacker who has it can open the wallet file and move the balance,
without a second secret. The spend-authority warning at create/restore is
unchanged and is not made weaker by this.
Wipe semantics: `/wipe` keeps the wallet file and its passphrase (the file
survives `/wipe` today); `/wipe-all` removes the data dir, as before.
If the stored passphrase does not open the configured file — a wallet the
catalogue holds but whose passphrase changed, or one created on another install —
the app reports it against that file and does **not** overwrite the stored one.
The child is stopped rather than left answering `-13`, and the status reports
`needs passphrase`; open the file once with its real passphrase
(`open_wallet_with_passphrase`, or the TUI/Android prompt) and it is remembered.
Nothing spawns the child at boot. `Node::start_wallet_child` is the only start Nothing spawns the child at boot. `Node::start_wallet_child` is the only start
path. The desktop TUI drives it from `F6`: path. The desktop TUI drives it from `F6`:
| Key | Effect | | Key | Effect |
|---|---| |---|---|
| `s` | Start the child, then probe it once. | | `s` | Start the child, then probe it once. A child whose wallet file needs a passphrase opens the passphrase prompt instead of leaving every read at `-13`. |
| `x` | Stop it (idempotent). | | `x` | Stop it (idempotent). |
| `p` | Probe: is wallet RPC answering, is the chain at the tip? | | `p` | Probe: is wallet RPC answering, is the chain at the tip? |
| `1` / `2` / `3` | Store in-process Cuprate as mainnet-pruned / mainnet-full / testnet. | | `1` / `2` / `3` | Store in-process Cuprate as mainnet-pruned / mainnet-full / testnet. |
State shown: `off` / `connecting` / `syncing` / `ready` / `exited`, plus a State shown: `off` / `connecting` / `syncing` / `ready` / `exited`, plus a
chain-source label. `ready` is never reported for a child that has died. chain-source label, plus `wallet locked` while a catalogue wallet is configured
but not open in the child's RPC. `ready` is never reported for a child that has
died. A live child is not a usable wallet: `wallet_status()` carries
`wallet_open` and `needs_passphrase` so a client can tell "the wallet is open"
from "the child is up and waiting for a passphrase".
Once a probe has read the daemon, the line can include `sync <height>/<target>` Once a probe has read the daemon, the line can include `sync <height>/<target>`
— the **daemon's** height and the tip it is syncing towards (wallet RPC — the **daemon's** height and the tip it is syncing towards (wallet RPC
@ -213,7 +243,11 @@ mark the open row. `open_wallet(filename)` switches to a catalogue row: a
running child is stopped and restarted onto the new file, an idle one is only running child is stopped and restarted onto the new file, an idle one is only
re-pointed (the change applies at the next `start_wallet_child`), and a file the re-pointed (the change applies at the next `start_wallet_child`), and a file the
catalogue does not hold is refused — the catalogue is the only directory this app catalogue does not hold is refused — the catalogue is the only directory this app
keeps wallets in. keeps wallets in. The restarted child then opens that file with the stored
passphrase; when this install has none for it, the call still succeeds and the
status says `needs_passphrase` — that is what the prompt is for, and
`open_wallet_with_passphrase(filename, passphrase)` is the API behind it. It
stores the passphrase only after a live daemon has opened the file with it.
## Secrets belong to the open wallet ## Secrets belong to the open wallet
@ -237,13 +271,15 @@ are displayable on demand".
`/wallet create` (`F6` then `c`) → `create_wallet`, then seed **once** `/wallet create` (`F6` then `c`) → `create_wallet`, then seed **once**
(`query_key mnemonic`). Type `SPEND`, set a passphrase, write the seed, type (`query_key mnemonic`). Type `SPEND`, set a passphrase, write the seed, type
`SEEN`. `SEEN`. The passphrase you set is sealed in the store (above), so the wallet
reopens on the next start without asking for it again.
`/wallet import` (`F6` then `i`) → `restore_deterministic_wallet` from a `/wallet import` (`F6` then `i`) → `restore_deterministic_wallet` from a
25-word seed. Do not put the seed on the composer. 25-word seed. Do not put the seed on the composer.
RPC must be started with `--wallet-dir` (not only `--wallet-file`). Filename: RPC must be started with `--wallet-dir` (not only `--wallet-file`). A created
`onionwire`. wallet gets its own file name (`onionwire-1`, `onionwire-2`, …): `wallet_filename`
is UNIQUE in the catalogue, so a second create must not reuse the first file.
## Recommended topology (view-only) ## Recommended topology (view-only)

View file

@ -32,7 +32,9 @@ use crate::store::{
Friend, FriendProfile, Message, NewWallet, Payment, PaymentWrite, Store, WalletRecord, Friend, FriendProfile, Message, NewWallet, Payment, PaymentWrite, Store, WalletRecord,
}; };
use crate::wallet::{self, ChainNetwork, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus}; use crate::wallet::{self, ChainNetwork, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus};
use crate::wallet_child::{ChildConfig, WalletChild, WalletChildState, WalletChildStatus}; use crate::wallet_child::{
ChildConfig, ChildWalletState, WalletChild, WalletChildState, WalletChildStatus,
};
pub struct RotateResult { pub struct RotateResult {
pub notified: usize, pub notified: usize,
@ -134,6 +136,12 @@ pub struct Node {
child_target: AtomicU64, child_target: AtomicU64,
/// The last child failure, display-ready. Cleared on a successful start. /// The last child failure, display-ready. Cleared on a successful start.
child_error: Mutex<Option<String>>, child_error: Mutex<Option<String>>,
/// Whether the running child's wallet **file** is open. Not derivable from
/// the process: `monero-wallet-rpc` starts with no wallet open, so a live
/// child that answers every call with `-13 No wallet file` is a child
/// waiting for a passphrase, not a healthy one. Only the start path, an
/// explicit open, and a successful probe write it.
child_wallet: Mutex<ChildWalletState>,
incoming_limit: Mutex<TokenBucket>, incoming_limit: Mutex<TokenBucket>,
inbox: Mutex<file::Inbox>, inbox: Mutex<file::Inbox>,
outbox: Arc<Outbox>, outbox: Arc<Outbox>,
@ -206,6 +214,7 @@ impl Node {
child_height: AtomicU64::new(0), child_height: AtomicU64::new(0),
child_target: AtomicU64::new(0), child_target: AtomicU64::new(0),
child_error: Mutex::new(None), child_error: Mutex::new(None),
child_wallet: Mutex::new(ChildWalletState::Unknown),
incoming_limit: Mutex::new(TokenBucket::default()), incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(inbox), inbox: Mutex::new(inbox),
outbox: Arc::clone(&outbox), outbox: Arc::clone(&outbox),
@ -659,23 +668,32 @@ impl Node {
self.set_wallet_child_config(&cfg) self.set_wallet_child_config(&cfg)
} }
/// Start the app-owned wallet child and point this node's wallet at it. /// Start the app-owned wallet child, point this node's wallet at it, and
/// **open its wallet file**.
/// ///
/// Idempotent: a live wallet child is reported, not respawned. Spawning is /// Idempotent: a live wallet child is reported, not respawned. Spawning is
/// synchronous — argv is built, the child is spawned, and a `.onion` chain /// synchronous — argv is built, the child is spawned, and a `.onion` chain
/// source waits up to `SOCKS_READY_TIMEOUT` for the SOCKS listener — which /// source waits up to `SOCKS_READY_TIMEOUT` for the SOCKS listener — which
/// is why callers block on it (`rt.block_on` in the TUI). /// is why callers block on it (`rt.block_on` in the TUI).
///
/// The open is the whole point: `monero-wallet-rpc` starts with no wallet
/// open, so a child that came up and was left alone answered every read
/// with `-13 No wallet file` — a restart, a Lock/unlock, or a wallet
/// re-point silently produced an inert wallet manager. The stored
/// passphrase ([`Self::seal_wallet_passphrase`]) opens it.
pub fn start_wallet_child(&self) -> Result<(), String> { pub fn start_wallet_child(&self) -> Result<(), String> {
self.start_wallet_child_with(None)
}
/// [`Self::start_wallet_child`], with a passphrase the caller just collected
/// instead of the stored one. Used by [`Self::open_wallet_with_passphrase`]:
/// a passphrase is only trusted once a live RPC has opened a file with it.
fn start_wallet_child_with(&self, passphrase: Option<&str>) -> Result<(), String> {
let cfg = self.wallet_child_config(); let cfg = self.wallet_child_config();
if !cfg.is_enabled() { if !cfg.is_enabled() {
return Err("no chain source configured — the wallet child is receive-only".into()); return Err("no chain source configured — the wallet child is receive-only".into());
} }
let already_running = self let already_running = self.child_running();
.wallet_child
.lock()
.map_err(|e| e.to_string())?
.as_ref()
.is_some_and(|child| child.wallet_rpc_running());
if already_running { if already_running {
return Ok(()); return Ok(());
} }
@ -699,9 +717,152 @@ impl Node {
*self.child_error.lock().map_err(|e| e.to_string())? = None; *self.child_error.lock().map_err(|e| e.to_string())? = None;
self.reset_child_probe(); self.reset_child_probe();
*self.wallet_child.lock().map_err(|e| e.to_string())? = Some(child); *self.wallet_child.lock().map_err(|e| e.to_string())? = Some(child);
*self.child_wallet.lock().map_err(|e| e.to_string())? = ChildWalletState::Unknown;
if let Err(e) = self.open_child_wallet(passphrase) {
// A child whose wallet the RPC would not open is not a child to
// leave running: every read answers `-13`, which is exactly the
// inert state this path exists to end, so stop it and report why.
// A failure to *store* the passphrase is a different thing — the
// wallet is open — so that child keeps running and the error says
// what was lost.
let state = self
.child_wallet
.lock()
.map(|s| *s)
.unwrap_or_default();
if state != ChildWalletState::Open {
self.stop_wallet_child()?;
}
*self.child_error.lock().map_err(|e| e.to_string())? = Some(e.clone());
return Err(e);
}
Ok(()) Ok(())
} }
/// Is a wallet child process alive right now?
fn child_running(&self) -> bool {
self.wallet_child
.lock()
.map(|guard| guard.as_ref().is_some_and(|c| c.wallet_rpc_running()))
.unwrap_or(false)
}
/// Does the catalogue hold this file name? The catalogue is the only
/// directory this app has, so it decides what may be opened at all.
fn catalogue_holds(&self, filename: &str) -> Result<bool, String> {
Ok(self
.list_wallets()?
.iter()
.any(|w| w.wallet_filename == filename))
}
/// The wallet-file passphrase this install remembers, or empty. A store
/// read: it never dials, and it works with the wallet off.
fn stored_wallet_passphrase(&self) -> Result<Zeroizing<String>, String> {
let cfg = self
.store
.lock()
.map_err(|e| e.to_string())?
.load_wallet_config()
.map_err(|e| e.to_string())?;
Ok(match cfg {
Some(cfg) => cfg.wallet_passphrase,
None => Zeroizing::new(String::new()),
})
}
/// Remember the passphrase that opens the wallet file, sealed beside the
/// RPC creds. A read-modify-write: the stored endpoint, login, view-only
/// flag and the generated child creds are all untouched.
///
/// This is the deliberate part of the design (see `docs/THREAT_MODEL.md`):
/// the wallet file is only reopenable with its passphrase, `/wipe` keeps
/// the wallet file, and a passphrase the user must re-type after every
/// restart is a passphrase they will not use. Keeping it makes the store
/// passphrase sufficient to spend.
fn seal_wallet_passphrase(&self, passphrase: &str) -> Result<(), String> {
if passphrase.is_empty() {
return Ok(());
}
let store = self.store.lock().map_err(|e| e.to_string())?;
let mut cfg = store
.load_wallet_config()
.map_err(|e| e.to_string())?
.unwrap_or_default();
if cfg.wallet_passphrase.as_str() == passphrase {
return Ok(());
}
cfg.wallet_passphrase = Zeroizing::new(passphrase.to_string());
store.save_wallet_config(&cfg).map_err(|e| e.to_string())
}
/// Open the wallet file the configured child is pointed at, when this
/// install can. `supplied` is a passphrase the user just handed over;
/// `None` means "use the stored one".
///
/// Four outcomes, one of which is an error:
/// * the configured file is not in the catalogue → nothing to open
/// ([`ChildWalletState::Unknown`], `Ok`);
/// * no passphrase is known → the child stays wallet-less and reports
/// [`ChildWalletState::NeedsPassphrase`], `Ok`. An install whose wallet
/// predates the stored passphrase must still start — the alternative is
/// turning a missing secret into a start failure;
/// * the file opens → [`ChildWalletState::Open`], and the passphrase is
/// sealed;
/// * the RPC refuses it → `Err` naming the file, never a generic start
/// failure, and the caller stops the child.
fn open_child_wallet(&self, supplied: Option<&str>) -> Result<(), String> {
let filename = self.wallet_child_config().wallet_filename;
if !self.catalogue_holds(&filename)? {
*self.child_wallet.lock().map_err(|e| e.to_string())? = ChildWalletState::Unknown;
return Ok(());
}
let passphrase = match supplied {
Some(p) => Zeroizing::new(p.to_string()),
None => self.stored_wallet_passphrase()?,
};
if passphrase.is_empty() {
*self.child_wallet.lock().map_err(|e| e.to_string())? =
ChildWalletState::NeedsPassphrase;
return Ok(());
}
self.open_wallet_file(&filename, passphrase.as_str())
}
/// Issue `open_wallet` against the RPC this node is talking to, and seal the
/// passphrase only once a live daemon has accepted it. An unverified
/// passphrase is never stored: the next start would then fail on a secret
/// the user believed was right.
fn open_wallet_file(&self, filename: &str, passphrase: &str) -> Result<(), String> {
let wallet = self.wallet_snapshot();
match open_wallet_blocking(&wallet, filename, passphrase) {
Ok(()) => {
*self.child_wallet.lock().map_err(|e| e.to_string())? = ChildWalletState::Open;
*self.child_error.lock().map_err(|e| e.to_string())? = None;
self.seal_wallet_passphrase(passphrase).map_err(|e| {
format!("wallet {filename} opened but its passphrase was not stored: {e}")
})
}
Err(failure) => {
let msg = failure.message(filename);
*self.child_wallet.lock().map_err(|e| e.to_string())? =
ChildWalletState::NeedsPassphrase;
*self.child_error.lock().map_err(|e| e.to_string())? = Some(msg.clone());
Err(msg)
}
}
}
/// The wallet file this process just created or imported is the one the
/// child holds open — but only while a child is actually up to hold it.
fn mark_child_wallet_open(&self) {
if self.child_running()
&& let Ok(mut state) = self.child_wallet.lock()
{
*state = ChildWalletState::Open;
}
}
/// Stop the app-owned wallet child (idempotent) and put the wallet back on /// Stop the app-owned wallet child (idempotent) and put the wallet back on
/// the stored/env config, if any. The next launch starts the child again — /// the stored/env config, if any. The next launch starts the child again —
/// nothing promises it stays up across a restart, and Android will not. /// nothing promises it stays up across a restart, and Android will not.
@ -711,6 +872,10 @@ impl Node {
child.stop().map_err(|e| e.to_string())?; child.stop().map_err(|e| e.to_string())?;
} }
self.reset_child_probe(); self.reset_child_probe();
// No process, no open wallet file. Whatever the last child managed is
// gone with it, and claiming otherwise would make the UI skip the
// prompt that opens the next one.
*self.child_wallet.lock().map_err(|e| e.to_string())? = ChildWalletState::Unknown;
let stored = self let stored = self
.store .store
.lock() .lock()
@ -766,9 +931,27 @@ impl Node {
self.child_target.load(Ordering::Relaxed), self.child_target.load(Ordering::Relaxed),
), ),
}; };
let child_wallet = self
.child_wallet
.lock()
.map(|state| *state)
.unwrap_or_default();
// A child that has exited holds nothing, whatever the last run managed.
// An `off` node is not the same statement: with no app-owned child the
// node may be talking to a remote-mode RPC the user runs themselves, and
// an open wallet file there is a real open.
let (wallet_open, needs_passphrase) = match state {
WalletChildState::Exited => (false, child_wallet == ChildWalletState::NeedsPassphrase),
_ => (
child_wallet == ChildWalletState::Open,
child_wallet == ChildWalletState::NeedsPassphrase,
),
};
WalletChildStatus { WalletChildStatus {
state, state,
running, running,
wallet_open,
needs_passphrase,
configured: cfg.is_enabled(), configured: cfg.is_enabled(),
chain_source: cfg.source_label(), chain_source: cfg.source_label(),
height: heights.0, height: heights.0,
@ -813,6 +996,13 @@ impl Node {
} else { } else {
None None
}; };
// A wallet RPC that answers has a wallet open: `get_address` cannot
// answer without one. That is the honest signal that the file is open,
// whoever opened it (this node, or the user's own client against a
// remote-mode endpoint).
if connected && let Ok(mut slot) = self.child_wallet.lock() {
*slot = ChildWalletState::Open;
}
let synced = progress.as_ref().is_some_and(wallet::ChainInfo::ready); let synced = progress.as_ref().is_some_and(wallet::ChainInfo::ready);
let (height, target_height) = match progress { let (height, target_height) = match progress {
Some(info) => (info.height, info.target_height), Some(info) => (info.height, info.target_height),
@ -873,9 +1063,13 @@ impl Node {
/// config leaves the running wallet exactly as it was. /// config leaves the running wallet exactly as it was.
pub fn wallet_save_config(&self, cfg: &WalletConfig) -> Result<(), String> { pub fn wallet_save_config(&self, cfg: &WalletConfig) -> Result<(), String> {
Wallet::from_config(cfg).map_err(|e| wallet::redact(&e.to_string(), cfg.secret()))?; Wallet::from_config(cfg).map_err(|e| wallet::redact(&e.to_string(), cfg.secret()))?;
let mut cfg = cfg.clone();
// The passphrase is the *file's*, not this screen's: keep whatever is
// stored, or an F7 save would lock the wallet out of itself.
cfg.wallet_passphrase = self.stored_wallet_passphrase()?;
{ {
let store = self.store.lock().map_err(|e| e.to_string())?; let store = self.store.lock().map_err(|e| e.to_string())?;
store.save_wallet_config(cfg).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. // Re-read from the store rather than trusting the caller's copy.
let stored = self let stored = self
@ -1217,6 +1411,14 @@ impl Node {
self.point_child_at(&filename).map_err(|e| { self.point_child_at(&filename).map_err(|e| {
format!("wallet {filename} created but the child is not pointed at it: {e}") format!("wallet {filename} created but the child is not pointed at it: {e}")
})?; })?;
// The passphrase that opens the file is a thing this app needs again on
// the next start: the RPC drops the open wallet when the process goes.
self.seal_wallet_passphrase(password).map_err(|e| {
format!("wallet {filename} created but its passphrase was not stored: {e}")
})?;
// This process just created the file, so the RPC has it open — while a
// child is running to hold it.
self.mark_child_wallet_open();
Ok(CreatedWallet { record, seed }) Ok(CreatedWallet { record, seed })
} }
@ -1287,6 +1489,12 @@ impl Node {
self.point_child_at(&filename).map_err(|e| { self.point_child_at(&filename).map_err(|e| {
format!("wallet {filename} imported but the child is not pointed at it: {e}") format!("wallet {filename} imported but the child is not pointed at it: {e}")
})?; })?;
// Import is a creation path too: remember the passphrase the RPC just
// opened the file with, so the next start can open it again.
self.seal_wallet_passphrase(password).map_err(|e| {
format!("wallet {filename} imported but its passphrase was not stored: {e}")
})?;
self.mark_child_wallet_open();
Ok(record) Ok(record)
} }
@ -1300,27 +1508,24 @@ impl Node {
.map_err(|e| e.to_string()) .map_err(|e| e.to_string())
} }
/// Switch the wallet child to a catalogue wallet's file. /// Switch the wallet child to a catalogue wallet's file and open it.
/// ///
/// The catalogue is the only directory this app has, so a file it does not /// The catalogue is the only directory this app has, so a file it does not
/// hold is refused instead of pointing a spend-capable child at a path. A /// hold is refused instead of pointing a spend-capable child at a path. A
/// running child is restarted onto the new file; an idle one is only /// running child is restarted onto the new file and opens it with the
/// re-pointed, and the change applies on the next `start_wallet_child`. The /// stored passphrase; an idle one is only re-pointed, and the change
/// write is a read-modify-write, so the generated RPC creds survive. /// applies on the next `start_wallet_child`. The write is a
/// read-modify-write, so the generated RPC creds survive.
///
/// When this install holds no passphrase for the file, the child comes up
/// with no wallet open and the status reports `needs_passphrase` — not an
/// error: [`Self::open_wallet_with_passphrase`] is the one-time fix, and
/// after it the passphrase is stored.
pub fn open_wallet(&self, filename: &str) -> Result<(), String> { pub fn open_wallet(&self, filename: &str) -> Result<(), String> {
if !self if !self.catalogue_holds(filename)? {
.list_wallets()?
.iter()
.any(|w| w.wallet_filename == filename)
{
return Err(format!("no saved wallet in {filename}")); return Err(format!("no saved wallet in {filename}"));
} }
let running = self let running = self.child_running();
.wallet_child
.lock()
.map_err(|e| e.to_string())?
.as_ref()
.is_some_and(|child| child.wallet_rpc_running());
if running { if running {
self.stop_wallet_child()?; self.stop_wallet_child()?;
} }
@ -1331,6 +1536,41 @@ impl Node {
Ok(()) Ok(())
} }
/// Open a catalogue wallet with a passphrase the user just supplied, and
/// remember it (sealed) once the RPC has accepted it.
///
/// This is the counterpart of a `needs_passphrase` status: a wallet created
/// before the passphrase was stored, or created on another install, is
/// opened once here and then reopens on every later start. A passphrase is
/// only *verified* by a live RPC, so with a running child this restarts the
/// child (opening the file as part of the start); with an idle child it
/// dials the RPC this node is already talking to. With nothing to dial it
/// refuses rather than sealing an unverified secret.
pub fn open_wallet_with_passphrase(
&self,
filename: &str,
passphrase: &str,
) -> Result<(), String> {
if passphrase.is_empty() {
return Err("wallet passphrase required".into());
}
if !self.catalogue_holds(filename)? {
return Err(format!("no saved wallet in {filename}"));
}
if !self.wallet_snapshot().configured() {
return Err(wallet::NOT_CONFIGURED_MSG.into());
}
let running = self.child_running();
if running {
self.stop_wallet_child()?;
}
self.point_child_at(filename)?;
if running {
return self.start_wallet_child_with(Some(passphrase));
}
self.open_wallet_file(filename, passphrase)
}
/// The file name a wallet created now should live in. `wallet_filename` is /// The file name a wallet created now should live in. `wallet_filename` is
/// UNIQUE and the catalogue is the only directory the app has, so this is /// UNIQUE and the catalogue is the only directory the app has, so this is
/// `<default>-<n>` for the first `n` the catalogue does not already hold. /// `<default>-<n>` for the first `n` the catalogue does not already hold.
@ -1852,6 +2092,84 @@ impl Node {
} }
} }
/// How long a freshly spawned child's wallet RPC gets to start answering before
/// an `open_wallet` attempt is a failure rather than a start still in progress.
/// `monero-wallet-rpc` binds its port well inside this; a child that never
/// answers is reported, not waited on forever.
const WALLET_OPEN_WAIT: Duration = Duration::from_secs(10);
const WALLET_OPEN_POLL: Duration = Duration::from_millis(100);
/// Why an `open_wallet` did not happen. Split because the two want opposite
/// treatment: one is a child still coming up, the other is the RPC's own answer
/// and retrying it would only repeat it.
enum OpenFailure {
/// The RPC never answered inside the budget.
NotAnswering(String),
/// The RPC answered and refused — a wrong passphrase for that file.
Refused(String),
}
impl OpenFailure {
/// Display copy. Names the file and the RPC's own reason; carries no secret
/// (the passphrase never enters an error string).
fn message(&self, filename: &str) -> String {
match self {
OpenFailure::Refused(detail) => format!(
"wallet file {filename} is not open — the RPC refused its passphrase ({detail})"
),
OpenFailure::NotAnswering(detail) => format!(
"wallet file {filename} is not open — the wallet RPC never answered ({detail})"
),
}
}
}
/// Run one `open_wallet` from a synchronous caller, retrying only while the
/// child's RPC is still coming up.
///
/// `Node::start_wallet_child` is synchronous (the TUI's key handler, and the
/// SDK's `spawn_blocking` wrapper) while the wallet client is `tokio`, and a
/// synchronous caller is not always somewhere the thread may be parked: a
/// current-thread runtime (every `#[tokio::test]` here) shares its single thread
/// with the reactor the future needs, so a nested `block_on` there would
/// deadlock. The RPC therefore runs on a scratch thread with its own runtime —
/// no nested runtime, no assumption about the caller.
fn open_wallet_blocking(
wallet: &Wallet,
filename: &str,
passphrase: &str,
) -> std::result::Result<(), OpenFailure> {
let wallet = wallet.clone();
let filename = filename.to_string();
let passphrase = Zeroizing::new(passphrase.to_string());
std::thread::scope(|scope| {
scope
.spawn(|| {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| OpenFailure::NotAnswering(format!("runtime: {e}")))?;
rt.block_on(async {
let deadline = tokio::time::Instant::now() + WALLET_OPEN_WAIT;
loop {
match wallet.open_wallet(&filename, passphrase.as_str()).await {
Ok(()) => return Ok(()),
Err(e) if e.is_unreachable() => {
if tokio::time::Instant::now() >= deadline {
return Err(OpenFailure::NotAnswering(e.to_string()));
}
tokio::time::sleep(WALLET_OPEN_POLL).await;
}
Err(e) => return Err(OpenFailure::Refused(e.to_string())),
}
}
})
})
.join()
.map_err(|_| OpenFailure::NotAnswering("open_wallet thread panicked".into()))?
})
}
/// HKDF info strings for the bootstrap derivation (see [`bootstrap_ratchet`]). /// HKDF info strings for the bootstrap derivation (see [`bootstrap_ratchet`]).
const RATCHET_BOOTSTRAP_SALT: &[u8] = b"onionwire-ratchet-v1-bootstrap"; const RATCHET_BOOTSTRAP_SALT: &[u8] = b"onionwire-ratchet-v1-bootstrap";
const RATCHET_BOOTSTRAP_ROOT_INFO: &[u8] = b"root"; const RATCHET_BOOTSTRAP_ROOT_INFO: &[u8] = b"root";
@ -2213,6 +2531,7 @@ pub(crate) mod tests {
child_height: AtomicU64::new(0), child_height: AtomicU64::new(0),
child_target: AtomicU64::new(0), child_target: AtomicU64::new(0),
child_error: Mutex::new(None), child_error: Mutex::new(None),
child_wallet: Mutex::new(ChildWalletState::Unknown),
incoming_limit: Mutex::new(TokenBucket::default()), incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(file::Inbox::new(home.join("inbox"))), inbox: Mutex::new(file::Inbox::new(home.join("inbox"))),
outbox, outbox,
@ -3225,6 +3544,12 @@ pub(crate) mod tests {
vec![created.record], vec![created.record],
"the wallet just created is the catalogue" "the wallet just created is the catalogue"
); );
assert_eq!(
sealed_passphrase(&node),
"hunter2",
"the passphrase that opens the file is remembered, or the next \
start cannot open it"
);
} }
/// The second half of the bug: a second create reused the one hardcoded file /// The second half of the bug: a second create reused the one hardcoded file
@ -3498,4 +3823,320 @@ pub(crate) mod tests {
"the RPC's -29 is the wallet's answer, not a failure" "the RPC's -29 is the wallet's answer, not a failure"
); );
} }
/// A loopback wallet RPC that records every request it is asked and answers
/// what a reopened wallet needs: `open_wallet`, `get_address` /
/// `get_balance`, and a synced `get_info`. The request log is the evidence —
/// a mock that answers whatever it is asked cannot tell a client that opened
/// the file from one that never asked.
fn recording_wallet_reply(
requests: Arc<Mutex<Vec<String>>>,
) -> Arc<dyn Fn(&str) -> String + Send + Sync> {
Arc::new(move |req: &str| {
requests.lock().expect("requests").push(req.to_string());
if req.contains("open_wallet") {
r#"{"jsonrpc":"2.0","id":"0","result":{}}"#.to_string()
} else if req.contains("get_address") {
format!(
r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#,
addr = xmr_addr()
)
} else if req.contains("get_info") {
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"#
.to_string()
} else {
r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0","unlocked_balance":"0"}}"#
.to_string()
}
})
}
/// The port the fake child was spawned with. The fake bin writes its argv one
/// argument per line, so `--rpc-bind-port` is followed by the number; the
/// write happens right after `spawn` returns, hence the wait.
async fn wait_for_child_rpc_port(argv_log: &Path) -> u16 {
for _ in 0..600 {
if let Ok(raw) = std::fs::read_to_string(argv_log) {
let lines: Vec<&str> = raw.lines().collect();
if let Some(i) = lines.iter().position(|line| *line == "--rpc-bind-port")
&& let Some(port) = lines.get(i + 1).and_then(|p| p.trim().parse::<u16>().ok())
{
return port;
}
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!(
"the fake child never wrote an --rpc-bind-port to {}",
argv_log.display()
);
}
/// The wallet-file passphrase this install remembers, `""` when none.
fn sealed_passphrase(node: &Node) -> String {
node.store
.lock()
.expect("store")
.load_wallet_config()
.expect("load wallet config")
.map(|cfg| cfg.wallet_passphrase.as_str().to_string())
.unwrap_or_default()
}
/// The bug this card exists for: `monero-wallet-rpc` keeps a wallet open
/// only for the life of its process, so a restarted child answered every
/// read with `-13 No wallet file` while the file sat on disk. The second
/// start must issue `open_wallet` with the file and the stored passphrase,
/// and the read after it must take the success path.
///
/// Multi-threaded on purpose: the start path is synchronous and blocks, so
/// only another worker can answer on the restarted child's port while it
/// waits for its RPC to come up.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_restart_opens_the_stored_wallet_file() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("child");
let argv_log = dir.path().join("argv.log");
let bin = fake_child_bin(
&dir.path().join("fake-bins"),
"monero-wallet-rpc",
&argv_log,
"sleep 30",
);
let node = Arc::new(offline_node(&home, Arc::new(NoDial)));
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire-1"))
.expect("set config");
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
// First start: the catalogue holds the file, but this install holds no
// passphrase for it. That is a state, not a failure.
node.start_wallet_child().expect("first start");
let status = node.wallet_child_status();
assert!(status.running, "{status:?}");
assert!(!status.wallet_open, "{status:?}");
assert!(status.needs_passphrase, "{status:?}");
assert!(status.last_error.is_none(), "{status:?}");
// Restart it with the passphrase the user supplied. The child picks a
// fresh port, so the mock is bound to what the new argv names while the
// open waits for the RPC to answer.
std::fs::write(&argv_log, b"").expect("clear the argv log");
let requests = Arc::new(Mutex::new(Vec::new()));
let starter = Arc::clone(&node);
let started = tokio::task::spawn_blocking(move || {
starter.open_wallet_with_passphrase("onionwire-1", "walletfile-pass")
});
let port = wait_for_child_rpc_port(&argv_log).await;
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
.await
.unwrap_or_else(|e| panic!("bind the restarted child's mock on {port}: {e}"));
tokio::spawn(serve_mock_rpc(
listener,
recording_wallet_reply(Arc::clone(&requests)),
));
started
.await
.expect("join the start")
.expect("open the wallet with a passphrase");
let sent = requests.lock().unwrap().join("\n");
assert!(
sent.contains(r#""method":"open_wallet""#),
"the restart never asked the RPC to open the file: {sent}"
);
assert!(
sent.contains(r#""filename":"onionwire-1""#),
"the restart opened the wrong file: {sent}"
);
assert!(
sent.contains(r#""password":"walletfile-pass""#),
"the restart did not send the passphrase it was handed: {sent}"
);
assert_eq!(
sealed_passphrase(&node),
"walletfile-pass",
"a verified passphrase is kept, or the next restart cannot open the file"
);
// The read after the restart takes the success path: the same mock
// answers `get_address`/`get_balance`/`get_info`.
let status = node.wallet_child_refresh().await;
assert!(status.wallet_open, "{status:?}");
assert!(!status.needs_passphrase, "{status:?}");
assert_eq!(status.state, WalletChildState::Ready, "{status:?}");
assert!(
requests
.lock()
.unwrap()
.iter()
.any(|r| r.contains("get_balance")),
"the wallet was read back through the reopened file"
);
node.stop_wallet_child().expect("stop");
}
/// No stored passphrase: the child starts with no wallet open and the status
/// says `needs passphrase`. It must not fail the start — a wallet created
/// before the passphrase was stored still has a working node — and it must
/// not send an `open_wallet` it has no passphrase for.
///
/// Multi-threaded so the mock can answer while the start blocks, which is
/// what makes "no `open_wallet` was sent" a measurement rather than a
/// consequence of nothing being able to listen.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_catalogue_wallet_without_a_sealed_passphrase_never_asks_to_open() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("child");
let argv_log = dir.path().join("argv.log");
let bin = fake_child_bin(
&dir.path().join("fake-bins"),
"monero-wallet-rpc",
&argv_log,
"sleep 30",
);
let node = Arc::new(offline_node(&home, Arc::new(NoDial)));
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire-1"))
.expect("set config");
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
node.start_wallet_child()
.expect("a wallet-less child still starts");
let status = node.wallet_child_status();
assert!(status.running, "{status:?}");
assert!(!status.wallet_open, "{status:?}");
assert!(status.needs_passphrase, "{status:?}");
node.stop_wallet_child().expect("stop");
// A second start, this time with an RPC listening on the port it was
// spawned with: had the start tried to open a file it would have dialed
// this and left the request in the log (or died trying, and failed).
std::fs::write(&argv_log, b"").expect("clear the argv log");
let requests = Arc::new(Mutex::new(Vec::new()));
let starter = Arc::clone(&node);
let started = tokio::task::spawn_blocking(move || starter.start_wallet_child());
let port = wait_for_child_rpc_port(&argv_log).await;
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
.await
.unwrap_or_else(|e| panic!("bind the fake child's mock on {port}: {e}"));
tokio::spawn(serve_mock_rpc(
listener,
recording_wallet_reply(Arc::clone(&requests)),
));
started
.await
.expect("join the start")
.expect("second start");
let status = node.wallet_child_status();
assert!(status.running, "{status:?}");
assert!(status.needs_passphrase, "{status:?}");
assert!(
!requests
.lock()
.unwrap()
.iter()
.any(|r| r.contains("open_wallet")),
"there is no passphrase to open with, so no open_wallet may be sent"
);
node.stop_wallet_child().expect("stop");
}
/// A refused passphrase is its own error, not a generic start failure, and
/// an unverified passphrase is never stored: the next start must not be
/// broken by a secret the user believed was right.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_refused_passphrase_is_a_distinct_error_and_is_not_sealed() {
let dir = tempfile::tempdir().unwrap();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind mock wallet");
let port = listener.local_addr().expect("mock wallet addr").port();
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(|req: &str| {
if req.contains("open_wallet") {
r#"{"jsonrpc":"2.0","id":"0","error":{"code":-1,"message":"Failed to open wallet"}}"#
.to_string()
} else {
r#"{"jsonrpc":"2.0","id":"0","result":{}}"#.to_string()
}
});
tokio::spawn(serve_mock_rpc(listener, reply));
let node = offline_node_with_wallet(
&dir.path().join("bob"),
Arc::new(NoDial),
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url"),
);
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
let err = node
.open_wallet_with_passphrase("onionwire-1", "wrong-pass")
.expect_err("the RPC refuses the wrong passphrase");
assert!(
err.contains("onionwire-1"),
"the error names the file: {err}"
);
assert!(
err.contains("Failed to open wallet"),
"the RPC's own reason is carried through: {err}"
);
assert!(!err.contains("wrong-pass"), "no secret in an error: {err}");
let status = node.wallet_child_status();
assert!(status.needs_passphrase, "{status:?}");
assert!(!status.wallet_open, "{status:?}");
assert!(
sealed_passphrase(&node).is_empty(),
"a passphrase no daemon accepted must not be stored"
);
assert_eq!(
node.wallet_child_config().wallet_filename,
"onionwire-1",
"the child is still pointed at the wallet the user is unlocking"
);
}
/// The one-time path that ends the `needs passphrase` state: the passphrase
/// is verified by a live RPC, then stored, and the status flips to open. The
/// catalogue still refuses a file it does not hold.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn open_wallet_with_passphrase_seals_what_a_daemon_verified() {
let dir = tempfile::tempdir().unwrap();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind mock wallet");
let port = listener.local_addr().expect("mock wallet addr").port();
let requests = Arc::new(Mutex::new(Vec::new()));
tokio::spawn(serve_mock_rpc(
listener,
recording_wallet_reply(Arc::clone(&requests)),
));
let node = offline_node_with_wallet(
&dir.path().join("bob"),
Arc::new(NoDial),
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url"),
);
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
let err = node
.open_wallet_with_passphrase("onionwire-1", "")
.expect_err("no passphrase to open with");
assert!(err.contains("passphrase"), "{err}");
let err = node
.open_wallet_with_passphrase("onionwire-9", "walletfile-pass")
.expect_err("not a saved wallet");
assert!(err.contains("no saved wallet"), "{err}");
node.open_wallet_with_passphrase("onionwire-1", "walletfile-pass")
.expect("open a saved wallet");
let sent = requests.lock().unwrap().join("\n");
assert!(
sent.contains(r#""method":"open_wallet""#),
"no open_wallet request: {sent}"
);
assert!(sent.contains(r#""filename":"onionwire-1""#), "{sent}");
assert_eq!(sealed_passphrase(&node), "walletfile-pass");
let status = node.wallet_child_status();
assert!(status.wallet_open, "{status:?}");
assert!(!status.needs_passphrase, "{status:?}");
}
} }

View file

@ -294,13 +294,17 @@ impl Store {
updated_at INTEGER NOT NULL updated_at INTEGER NOT NULL
); );
-- Remote-mode wallet config the user set in-app (F7): the endpoint, -- 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 -- the login, the view-only flag, and the passphrase that opens the
-- with the store data key (see `save_wallet_config`). -- wallet file the child is pointed at. One row; the login and the
-- passphrase are each sealed with the store data key under their
-- own AAD (see `save_wallet_config`), so one ciphertext cannot be
-- swapped for the other.
CREATE TABLE IF NOT EXISTS wallet_config ( CREATE TABLE IF NOT EXISTS wallet_config (
id INTEGER PRIMARY KEY CHECK (id = 1), id INTEGER PRIMARY KEY CHECK (id = 1),
rpc_url TEXT NOT NULL, rpc_url TEXT NOT NULL,
sealed_login BLOB NOT NULL, sealed_login BLOB NOT NULL,
no_spend INTEGER NOT NULL, no_spend INTEGER NOT NULL,
sealed_passphrase BLOB,
updated_at INTEGER NOT NULL updated_at INTEGER NOT NULL
); );
-- The wallet catalogue: one row per wallet file this install knows -- The wallet catalogue: one row per wallet file this install knows
@ -410,26 +414,49 @@ impl Store {
/// Persist the remote-mode wallet config the F7 screen saved. One row, /// 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 /// replaced in place; an empty `rpc_url` clears it (that is how a user
/// turns the stored wallet off again). /// turns the stored wallet off again) — unless a wallet **passphrase** is
/// remembered in the row, which the endpoint has nothing to do with and
/// must survive: it belongs to the wallet file, not to the RPC endpoint.
/// ///
/// The login is `user:pass` for a wallet that can spend, so it is sealed /// The login is `user:pass` for a wallet that can spend and the passphrase
/// with the store data key on top of the whole-db SQLCipher layer — the /// opens the wallet file, so both are sealed with the store data key on top
/// same discipline as the wallet-child creds. /// of the whole-db SQLCipher layer — the same discipline as the wallet-child
/// creds — and under separate AADs, so neither ciphertext can be replayed
/// into the other's column.
pub fn save_wallet_config(&self, cfg: &crate::wallet::WalletConfig) -> Result<()> { pub fn save_wallet_config(&self, cfg: &crate::wallet::WalletConfig) -> Result<()> {
if cfg.rpc_url.trim().is_empty() { if cfg.rpc_url.trim().is_empty() && cfg.wallet_passphrase.is_empty() {
self.conn.execute("DELETE FROM wallet_config", [])?; self.conn.execute("DELETE FROM wallet_config", [])?;
return Ok(()); return Ok(());
} }
let sealed = let sealed =
crate::backup::aead_encrypt(&self.msg_key, cfg.rpc_login.as_bytes(), WALLET_CONFIG_AAD) crate::backup::aead_encrypt(&self.msg_key, cfg.rpc_login.as_bytes(), WALLET_CONFIG_AAD)
.map_err(Error)?; .map_err(Error)?;
let sealed_pass = if cfg.wallet_passphrase.is_empty() {
None
} else {
Some(
crate::backup::aead_encrypt(
&self.msg_key,
cfg.wallet_passphrase.as_bytes(),
WALLET_PASSPHRASE_AAD,
)
.map_err(Error)?,
)
};
self.conn.execute( self.conn.execute(
"INSERT INTO wallet_config (id, rpc_url, sealed_login, no_spend, updated_at) "INSERT INTO wallet_config (id, rpc_url, sealed_login, no_spend, sealed_passphrase, updated_at)
VALUES (1, ?1, ?2, ?3, ?4) VALUES (1, ?1, ?2, ?3, ?4, ?5)
ON CONFLICT(id) DO UPDATE SET rpc_url = excluded.rpc_url, ON CONFLICT(id) DO UPDATE SET rpc_url = excluded.rpc_url,
sealed_login = excluded.sealed_login, no_spend = excluded.no_spend, sealed_login = excluded.sealed_login, no_spend = excluded.no_spend,
sealed_passphrase = excluded.sealed_passphrase,
updated_at = excluded.updated_at", updated_at = excluded.updated_at",
params![cfg.rpc_url.trim(), sealed, cfg.no_spend as i64, unix_now()], params![
cfg.rpc_url.trim(),
sealed,
cfg.no_spend as i64,
sealed_pass,
unix_now()
],
)?; )?;
Ok(()) Ok(())
} }
@ -437,27 +464,42 @@ impl Store {
/// Read the stored remote-mode config, or `None` when none was ever saved. /// 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. /// A blob that does not decrypt is an error, never a guess.
pub fn load_wallet_config(&self) -> Result<Option<crate::wallet::WalletConfig>> { pub fn load_wallet_config(&self) -> Result<Option<crate::wallet::WalletConfig>> {
let row: Option<(String, Vec<u8>, i64)> = self type WalletConfigRow = (String, Vec<u8>, i64, Option<Vec<u8>>);
let row: Option<WalletConfigRow> = self
.conn .conn
.query_row( .query_row(
"SELECT rpc_url, sealed_login, no_spend FROM wallet_config WHERE id = 1", "SELECT rpc_url, sealed_login, no_spend, sealed_passphrase
FROM wallet_config WHERE id = 1",
[], [],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
) )
.optional()?; .optional()?;
let Some((rpc_url, sealed, no_spend)) = row else { let Some((rpc_url, sealed, no_spend, sealed_pass)) = row else {
return Ok(None); return Ok(None);
}; };
let login = crate::backup::aead_decrypt(&self.msg_key, &sealed, WALLET_CONFIG_AAD) let login = crate::backup::aead_decrypt(&self.msg_key, &sealed, WALLET_CONFIG_AAD)
.map_err(|_| Error("wallet config decrypt failed".into()))?; .map_err(|_| Error("wallet config decrypt failed".into()))?;
// The login is a secret: it must not survive in a bare `String`. // Both are secrets: neither may survive in a bare `String`.
let login = Zeroizing::new( let login = Zeroizing::new(
String::from_utf8(login).map_err(|_| Error("wallet config is not utf-8".into()))?, String::from_utf8(login).map_err(|_| Error("wallet config is not utf-8".into()))?,
); );
let wallet_passphrase = match sealed_pass {
None => Zeroizing::new(String::new()),
Some(blob) => {
let plain =
crate::backup::aead_decrypt(&self.msg_key, &blob, WALLET_PASSPHRASE_AAD)
.map_err(|_| Error("wallet passphrase decrypt failed".into()))?;
Zeroizing::new(
String::from_utf8(plain)
.map_err(|_| Error("wallet passphrase is not utf-8".into()))?,
)
}
};
Ok(Some(crate::wallet::WalletConfig { Ok(Some(crate::wallet::WalletConfig {
rpc_url, rpc_url,
rpc_login: login, rpc_login: login,
no_spend: no_spend != 0, no_spend: no_spend != 0,
wallet_passphrase,
})) }))
} }
@ -595,6 +637,14 @@ impl Store {
"hs_nickname", "hs_nickname",
"ALTER TABLE self ADD COLUMN hs_nickname TEXT NOT NULL DEFAULT 'ow0'", "ALTER TABLE self ADD COLUMN hs_nickname TEXT NOT NULL DEFAULT 'ow0'",
)?; )?;
// The wallet file's passphrase (sealed). NULL on an install that has
// never been told one — a wallet created before this column, or a
// remote-mode wallet the user opens themselves.
self.add_column_if_missing(
"wallet_config",
"sealed_passphrase",
"ALTER TABLE wallet_config ADD COLUMN sealed_passphrase BLOB",
)?;
// Opaque send payload for rows that cannot re-derive their bytes (a // Opaque send payload for rows that cannot re-derive their bytes (a
// chat send's ratchet frame). NULL means "send the message body", the // chat send's ratchet frame). NULL means "send the message body", the
// pre-payload behaviour, so locator/profile/payment rows are unchanged. // pre-payload behaviour, so locator/profile/payment rows are unchanged.
@ -1813,6 +1863,10 @@ const WALLET_CHILD_AAD: &[u8] = b"onionwire/wallet-child/v1";
/// AAD for the sealed remote-mode wallet config row. Same reasoning as the /// AAD for the sealed remote-mode wallet config row. Same reasoning as the
/// wallet-child AAD: one store key, many domains. /// wallet-child AAD: one store key, many domains.
const WALLET_CONFIG_AAD: &[u8] = b"onionwire/wallet-config/v1"; const WALLET_CONFIG_AAD: &[u8] = b"onionwire/wallet-config/v1";
/// The wallet-file passphrase's own AAD: same key and construction as the
/// login, a different binding, so the two sealed columns are not
/// interchangeable.
const WALLET_PASSPHRASE_AAD: &[u8] = b"onionwire/wallet-passphrase/v1";
fn fingerprint(pubkey: &[u8]) -> String { fn fingerprint(pubkey: &[u8]) -> String {
pubkey.iter().map(|b| format!("{b:02x}")).collect() pubkey.iter().map(|b| format!("{b:02x}")).collect()

View file

@ -1307,6 +1307,14 @@ enum WalletSetup {
CreateSeed { seed: Zeroizing<String>, typed: String }, CreateSeed { seed: Zeroizing<String>, typed: String },
ImportSeed { buf: Zeroizing<String> }, ImportSeed { buf: Zeroizing<String> },
ImportPass { seed: Zeroizing<String>, entry: PassphraseEntry }, ImportPass { seed: Zeroizing<String>, entry: PassphraseEntry },
/// The wallet file the child is pointed at is not open because this install
/// has no passphrase for it. Same prompt idiom as the create path: one
/// hidden entry, `Enter` submits, `Esc` cancels, and the buffer is zeroized
/// on every exit.
UnlockPass {
filename: String,
entry: PassphraseEntry,
},
} }
/// A function key the TUI answers before the per-screen `match`; the screen's /// A function key the TUI answers before the per-screen `match`; the screen's
@ -2112,8 +2120,26 @@ impl App {
let opened = self.select_wallet(index); let opened = self.select_wallet(index);
match opened { match opened {
Ok(label) => { Ok(label) => {
self.status_note = Some(format!("opened wallet {label}")); // The child is pointed at the file either way; whether
self.screen = Screen::Main; // it could *open* it is a separate fact, and the one the
// user has to answer for when this install holds no
// passphrase (a wallet created before one was stored).
if self.node.wallet_child_status().needs_passphrase {
let filename = self
.node
.active_wallet_filename()
.ok()
.flatten()
.unwrap_or_default();
self.status_note = Some(format!("wallet {label} needs its passphrase"));
self.screen = Screen::WalletSetup(WalletSetup::UnlockPass {
filename,
entry: PassphraseEntry::new(),
});
} else {
self.status_note = Some(format!("opened wallet {label}"));
self.screen = Screen::Main;
}
} }
Err(e) => self.alert = Some(e), Err(e) => self.alert = Some(e),
} }
@ -2247,6 +2273,26 @@ impl App {
Ok(()) => self.wallet_child_note(), Ok(()) => self.wallet_child_note(),
Err(e) => format!("wallet child: {e}"), Err(e) => format!("wallet child: {e}"),
}); });
self.prompt_for_wallet_passphrase();
}
/// A started child whose wallet file is not open: ask for the passphrase
/// instead of leaving the user with a child that answers `-13` to every
/// read. Reuses the create path's prompt.
fn prompt_for_wallet_passphrase(&mut self) {
if !self.node.wallet_child_status().needs_passphrase {
return;
}
let filename = self
.node
.active_wallet_filename()
.ok()
.flatten()
.unwrap_or_default();
self.screen = Screen::WalletSetup(WalletSetup::UnlockPass {
filename,
entry: PassphraseEntry::new(),
});
} }
/// Key `x`: stop the child (idempotent) and drop back to the stored/env /// Key `x`: stop the child (idempotent) and drop back to the stored/env
@ -2341,7 +2387,9 @@ impl App {
}; };
if key.code == KeyCode::Esc { if key.code == KeyCode::Esc {
match setup { match setup {
WalletSetup::CreatePass { entry } | WalletSetup::ImportPass { entry, .. } => { WalletSetup::CreatePass { entry }
| WalletSetup::ImportPass { entry, .. }
| WalletSetup::UnlockPass { entry, .. } => {
entry.close(); entry.close();
} }
WalletSetup::CreateSeed { seed, .. } => seed.zeroize(), WalletSetup::CreateSeed { seed, .. } => seed.zeroize(),
@ -2476,6 +2524,33 @@ impl App {
} }
_ => {} _ => {}
}, },
WalletSetup::UnlockPass { filename, entry } => match key.code {
KeyCode::Backspace => entry.backspace(),
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
entry.push(c);
}
KeyCode::Enter => {
// One entry, no confirm: this passphrase is already the
// file's, and a re-type would only be a second chance to
// typo it.
let pass = entry.take_buf();
let filename = filename.clone();
match self
.node
.open_wallet_with_passphrase(&filename, pass.as_str())
{
Ok(()) => {
self.status_note = Some(format!("opened wallet {filename}"));
self.screen = Screen::Main;
}
Err(e) => {
self.alert = Some(e);
self.screen = Screen::Main;
}
}
}
_ => {}
},
} }
Ok(()) Ok(())
} }
@ -3326,7 +3401,11 @@ match screen {
"c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help" "c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help"
} }
Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help",
Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => { Screen::WalletSetup(
WalletSetup::CreatePass { .. }
| WalletSetup::ImportPass { .. }
| WalletSetup::UnlockPass { .. },
) => {
"Enter submit Esc cancel ? help" "Enter submit Esc cancel ? help"
} }
Screen::WalletSetup(WalletSetup::CreateSeed { .. }) => "type SEEN Esc cancel ? help", Screen::WalletSetup(WalletSetup::CreateSeed { .. }) => "type SEEN Esc cancel ? help",
@ -5222,6 +5301,14 @@ fn draw_wallet_setup(f: &mut Frame, setup: &WalletSetup) {
"passphrase for the imported wallet file\n\nEnter continues Esc cancels".into() "passphrase for the imported wallet file\n\nEnter continues Esc cancels".into()
}, },
), ),
WalletSetup::UnlockPass { filename, .. } => (
"wallet passphrase",
format!(
"the wallet file {filename} is not open\n\
enter its passphrase to open it (it is then remembered, sealed)\n\n\
Enter submits Esc cancels"
),
),
}; };
draw_text_overlay(f, title, &body); draw_text_overlay(f, title, &body);
} }

View file

@ -19,6 +19,20 @@ impl std::fmt::Display for Error {
impl std::error::Error for Error {} impl std::error::Error for Error {}
impl Error {
/// Is this failure "the wallet RPC is not answering yet"? That is the one
/// class a retry can fix — a freshly spawned `monero-wallet-rpc` binds its
/// port a moment after `spawn` returns. Everything else (a refused
/// passphrase, a protocol error) is the RPC's own answer and retrying it
/// would only repeat it.
///
/// Deliberately *not* the timeout: a hung child is not a start in progress.
pub fn is_unreachable(&self) -> bool {
let msg = self.0.as_str();
msg.starts_with("wallet connect:") || msg.starts_with("wallet write:")
}
}
/// Which Monero network an on-device daemon follows. /// Which Monero network an on-device daemon follows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChainNetwork { pub enum ChainNetwork {
@ -147,6 +161,17 @@ pub struct WalletConfig {
pub rpc_login: Zeroizing<String>, pub rpc_login: Zeroizing<String>,
/// View-only deployment: `/tip` is refused locally, before any dial. /// View-only deployment: `/tip` is refused locally, before any dial.
pub no_spend: bool, pub no_spend: bool,
/// The passphrase that opens the wallet *file* the child is pointed at
/// ([`Wallet::open_wallet`]). Sealed at rest beside `rpc_login`; empty when
/// this install has never been told one (a wallet that predates the field,
/// or a remote-mode wallet the user runs themselves).
///
/// Keeping it is deliberate: it makes the store passphrase sufficient to
/// spend, and it is why the app can reopen a wallet file across a restart
/// at all — `monero-wallet-rpc` holds an open file only for the life of the
/// process, and re-opening it needs the passphrase. See
/// `docs/THREAT_MODEL.md`.
pub wallet_passphrase: Zeroizing<String>,
} }
impl WalletConfig { impl WalletConfig {
@ -155,9 +180,19 @@ impl WalletConfig {
rpc_url: rpc_url.trim().to_string(), rpc_url: rpc_url.trim().to_string(),
rpc_login: Zeroizing::new(rpc_login.trim().to_string()), rpc_login: Zeroizing::new(rpc_login.trim().to_string()),
no_spend, no_spend,
wallet_passphrase: Zeroizing::new(String::new()),
} }
} }
/// Set the passphrase that opens the wallet file this config's child is
/// pointed at. Chainable, and the only way to supply it from outside the
/// crate: the field is public too, but a builder keeps a caller from
/// forgetting that it is sealed beside the login.
pub fn with_wallet_passphrase(mut self, passphrase: &str) -> Self {
self.wallet_passphrase = Zeroizing::new(passphrase.to_string());
self
}
/// The password half of `user:pass` (the whole string when there is no /// The password half of `user:pass` (the whole string when there is no
/// colon), for redaction. Never rendered anywhere. /// colon), for redaction. Never rendered anywhere.
pub fn secret(&self) -> &str { pub fn secret(&self) -> &str {
@ -176,6 +211,14 @@ impl std::fmt::Debug for WalletConfig {
.field("rpc_url", &self.rpc_url) .field("rpc_url", &self.rpc_url)
.field("rpc_login", &"<redacted>") .field("rpc_login", &"<redacted>")
.field("no_spend", &self.no_spend) .field("no_spend", &self.no_spend)
.field(
"wallet_passphrase",
&if self.wallet_passphrase.is_empty() {
"<none>"
} else {
"<redacted>"
},
)
.finish() .finish()
} }
} }
@ -185,6 +228,7 @@ impl PartialEq for WalletConfig {
self.rpc_url == other.rpc_url self.rpc_url == other.rpc_url
&& self.rpc_login.as_str() == other.rpc_login.as_str() && self.rpc_login.as_str() == other.rpc_login.as_str()
&& self.no_spend == other.no_spend && self.no_spend == other.no_spend
&& self.wallet_passphrase.as_str() == other.wallet_passphrase.as_str()
} }
} }
@ -525,6 +569,10 @@ impl Wallet {
rpc_url: format!("http://{}{}", host_header(&ep.host, ep.port), ep.path), rpc_url: format!("http://{}{}", host_header(&ep.host, ep.port), ep.path),
rpc_login: Zeroizing::new(format!("{}:{}", ep.user, ep.pass.as_str())), rpc_login: Zeroizing::new(format!("{}:{}", ep.user, ep.pass.as_str())),
no_spend: self.no_spend, no_spend: self.no_spend,
// Not known here: the passphrase is the *file's*, and this builds
// the config of the RPC endpoint in use. Callers that persist a
// config do a read-modify-write so the stored one survives.
wallet_passphrase: Zeroizing::new(String::new()),
}) })
} }
@ -809,6 +857,41 @@ impl Wallet {
json_str(&v, "key") json_str(&v, "key")
} }
/// Open a wallet *file* on the RPC (`open_wallet`).
///
/// `monero-wallet-rpc` starts with no wallet open, and `create_wallet` /
/// `restore_deterministic_wallet` leave theirs open for that process only:
/// after a restart every read answers `-13 No wallet file` even though the
/// file is on disk. This is the call that opens it, and the only way a
/// wallet survives the child being restarted.
///
/// The passphrase travels in the JSON-RPC body, never on the argv: `ps` is
/// world-readable for the same user, and `--wallet-file`/`--password`
/// would put the secret there. `filename` is a name inside the child's
/// `--wallet-dir`, never a path.
///
/// A wrong passphrase is the RPC's own error (the daemon does not open a
/// file it cannot decrypt); it is surfaced as-is, never retried into a
/// generic failure by the caller.
pub async fn open_wallet(&self, filename: &str, password: &str) -> Result<()> {
let filename = filename.trim();
if filename.is_empty() {
return Err(Error("wallet filename required".into()));
}
if password.is_empty() {
return Err(Error("wallet passphrase required".into()));
}
self.rpc(
"open_wallet",
serde_json::json!({
"filename": filename,
"password": password,
}),
)
.await?;
Ok(())
}
/// Re-read the seed of the wallet file the RPC has open (`query_key /// Re-read the seed of the wallet file the RPC has open (`query_key
/// mnemonic`). After `create_wallet` this is the **only** way to recover a /// mnemonic`). After `create_wallet` this is the **only** way to recover a
/// created wallet's seed, so the UI can offer a backup action instead of /// created wallet's seed, so the UI can offer a backup action instead of

View file

@ -892,12 +892,49 @@ impl WalletChildState {
} }
} }
/// Whether the wallet **file** the child is pointed at is open in the running
/// `monero-wallet-rpc`.
///
/// This is not the same question as "is the RPC up": the daemon starts with no
/// wallet open, so a live child that answers every call with `-13 No wallet
/// file` is `NeedsPassphrase`, not a start failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ChildWalletState {
/// Nothing to open, or nothing attempted yet: no catalogue wallet under the
/// configured file name, or no child.
#[default]
Unknown,
/// The wallet file is open (`open_wallet` succeeded, or this process just
/// created it).
Open,
/// A wallet file the catalogue holds is not open, and this install holds no
/// passphrase that could open it. Not an error: the user supplies it once.
NeedsPassphrase,
}
impl ChildWalletState {
pub fn as_str(self) -> &'static str {
match self {
ChildWalletState::Unknown => "unknown",
ChildWalletState::Open => "open",
ChildWalletState::NeedsPassphrase => "needs-passphrase",
}
}
}
/// One snapshot of the child. Cheap to read: no dial, no lock held across work. /// One snapshot of the child. Cheap to read: no dial, no lock held across work.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalletChildStatus { pub struct WalletChildStatus {
pub state: WalletChildState, pub state: WalletChildState,
/// A child process is alive right now. /// A child process is alive right now.
pub running: bool, pub running: bool,
/// The wallet file the child is pointed at is open in its RPC. `false` is
/// the honest answer for an off/exited child and for one whose
/// `open_wallet` has not succeeded.
pub wallet_open: bool,
/// A catalogue wallet is configured but not open, so a passphrase is needed
/// before any read can work. Distinct from a failed start.
pub needs_passphrase: bool,
/// A chain source is configured (not receive-only), whether or not it runs. /// A chain source is configured (not receive-only), whether or not it runs.
pub configured: bool, pub configured: bool,
/// The chain-source label: `receive-only` / `local node` / /// The chain-source label: `receive-only` / `local node` /
@ -921,6 +958,9 @@ impl WalletChildStatus {
return String::new(); return String::new();
} }
let mut line = format!("child {} · {}", self.state.as_str(), self.chain_source); let mut line = format!("child {} · {}", self.state.as_str(), self.chain_source);
if self.needs_passphrase {
line.push_str(" · wallet locked");
}
// A probe that read nothing says nothing: the line is unchanged until a // A probe that read nothing says nothing: the line is unchanged until a
// daemon (or the wallet's daemon) actually reported numbers. No // daemon (or the wallet's daemon) actually reported numbers. No
// percentage is derived — `target_height == 0` is "the daemon told us // percentage is derived — `target_height == 0` is "the daemon told us
@ -1997,6 +2037,8 @@ mod tests {
WalletChildStatus { WalletChildStatus {
state, state,
running: true, running: true,
wallet_open: true,
needs_passphrase: false,
configured: true, configured: true,
chain_source: "in-process node".to_string(), chain_source: "in-process node".to_string(),
height, height,

View file

@ -663,3 +663,83 @@ fn a_wallet_without_a_label_or_locator_stores_nulls_and_rejects_a_blank_filename
.expect_err("an empty filename cannot name a wallet file"); .expect_err("an empty filename cannot name a wallet file");
assert!(err.to_string().contains("filename"), "{err}"); assert!(err.to_string().contains("filename"), "{err}");
} }
/// The wallet file's passphrase lives in the same sealed row as the RPC login
/// and survives a re-open — the wallet child is restarted far more often than
/// the store is created, and a wallet nobody can open is the bug this exists
/// for. A wrong store passphrase still must not open the store at all.
#[test]
fn the_wallet_passphrase_round_trips_sealed_and_a_wrong_store_passphrase_does_not_open_it() {
use onionwire::wallet::WalletConfig;
let dir = tempfile::tempdir().expect("tempdir");
let cfg = WalletConfig::new("http://127.0.0.1:18083", "ow:cfg-secret-xyz", false)
.with_wallet_passphrase("walletfile-pass-abc");
{
let store = Store::open_at_with_passphrase(dir.path(), "store-pass").expect("open");
assert!(
store.load_wallet_config().expect("load").is_none(),
"a fresh store remembers no passphrase"
);
store.save_wallet_config(&cfg).expect("save");
}
let store = Store::open_at_with_passphrase(dir.path(), "store-pass").expect("reopen");
let got = store.load_wallet_config().expect("load").expect("stored");
assert_eq!(got.wallet_passphrase.as_str(), "walletfile-pass-abc");
assert_eq!(got.rpc_login.as_str(), "ow:cfg-secret-xyz");
// Sealed on disk, like the login: the passphrase is not in the db in the
// clear, and neither is the login.
for name in ["onionwire.db", "onionwire.db-wal", "onionwire.db-shm"] {
let Ok(bytes) = fs::read(dir.path().join(name)) else {
continue;
};
assert!(
!contains(&bytes, b"walletfile-pass-abc"),
"{name} holds the wallet passphrase in the clear"
);
assert!(
!contains(&bytes, b"cfg-secret-xyz"),
"{name} holds the RPC login in the clear"
);
}
// The wrong store passphrase is still refused outright.
assert!(
Store::open_at_with_passphrase(dir.path(), "not-the-store-pass").is_err(),
"a wrong store passphrase must not open the store"
);
// Clearing the F7 endpoint (an empty rpc_url) must not throw the wallet
// passphrase away: it belongs to the wallet file, not to the endpoint.
let store = Store::open_at_with_passphrase(dir.path(), "store-pass").expect("reopen");
let cleared = WalletConfig::new("", "", false).with_wallet_passphrase(
store
.load_wallet_config()
.expect("load")
.expect("stored")
.wallet_passphrase
.as_str(),
);
store.save_wallet_config(&cleared).expect("save cleared");
let got = store
.load_wallet_config()
.expect("load")
.expect("a remembered passphrase keeps the row");
assert_eq!(got.rpc_url, "");
assert_eq!(got.wallet_passphrase.as_str(), "walletfile-pass-abc");
// And with nothing left to remember, the row goes away.
store
.save_wallet_config(&WalletConfig::new("", "", false))
.expect("save empty");
assert!(
store.load_wallet_config().expect("load").is_none(),
"an empty endpoint and no passphrase is an empty row"
);
}
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
haystack.windows(needle.len()).any(|w| w == needle)
}

View file

@ -1761,3 +1761,75 @@ async fn an_in_process_cuprate_node_answers_the_typed_daemon_client() {
"the unrestricted RPC was still accepting after shutdown" "the unrestricted RPC was still accepting after shutdown"
); );
} }
/// The call the whole restart story hangs on. Assert the bytes the client
/// **sent**: a mock that answers whatever it is asked stays green for a client
/// that never issued `open_wallet` at all — which is exactly how a wallet came
/// back from a restart answering `-13 No wallet file` while the suite passed.
#[tokio::test]
async fn open_wallet_issues_the_rpc_method_with_the_file_and_passphrase() {
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(|_: &str| rpc_result("{}")),
));
recording_wallet(port)
.open_wallet("onionwire-1", "walletfile-pass")
.await
.expect("open_wallet");
let sent = log.lock().unwrap().join("\n");
assert!(
sent.contains(r#""method":"open_wallet""#),
"the client never asked to open the file: {sent}"
);
assert!(sent.contains(r#""filename":"onionwire-1""#), "{sent}");
assert!(sent.contains(r#""password":"walletfile-pass""#), "{sent}");
}
/// Same refusals as `create_wallet`: an empty file name or an empty passphrase
/// is a local error, before any socket is opened.
#[tokio::test]
async fn open_wallet_refuses_a_blank_filename_or_passphrase_locally() {
let w = Wallet::disabled();
let err = w.open_wallet(" ", "pw").await.expect_err("no filename");
assert!(err.to_string().contains("filename"), "{err}");
let err = w
.open_wallet("onionwire-1", "")
.await
.expect_err("no passphrase");
assert!(err.to_string().contains("passphrase"), "{err}");
}
/// A refused passphrase is the RPC's own message, not a rewritten generic one:
/// the caller has to be able to tell it apart from a daemon that never answered.
#[tokio::test]
async fn open_wallet_surfaces_the_rpcs_own_refusal() {
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(|_: &str| {
r#"{"jsonrpc":"2.0","id":"0","error":{"code":-1,"message":"Failed to open wallet"}}"#
.to_string()
}),
));
let err = recording_wallet(port)
.open_wallet("onionwire-1", "wrong-pass")
.await
.expect_err("the RPC refused");
assert!(
err.to_string().contains("Failed to open wallet"),
"the RPC's own reason is what a caller needs: {err}"
);
assert!(
!err.to_string().contains("wrong-pass"),
"the passphrase must never be echoed back in an error: {err}"
);
}