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

@ -32,7 +32,9 @@ use crate::store::{
Friend, FriendProfile, Message, NewWallet, Payment, PaymentWrite, Store, WalletRecord,
};
use crate::wallet::{self, ChainNetwork, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus};
use crate::wallet_child::{ChildConfig, WalletChild, WalletChildState, WalletChildStatus};
use crate::wallet_child::{
ChildConfig, ChildWalletState, WalletChild, WalletChildState, WalletChildStatus,
};
pub struct RotateResult {
pub notified: usize,
@ -134,6 +136,12 @@ pub struct Node {
child_target: AtomicU64,
/// The last child failure, display-ready. Cleared on a successful start.
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>,
inbox: Mutex<file::Inbox>,
outbox: Arc<Outbox>,
@ -206,6 +214,7 @@ impl Node {
child_height: AtomicU64::new(0),
child_target: AtomicU64::new(0),
child_error: Mutex::new(None),
child_wallet: Mutex::new(ChildWalletState::Unknown),
incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(inbox),
outbox: Arc::clone(&outbox),
@ -659,23 +668,32 @@ impl Node {
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
/// synchronous — argv is built, the child is spawned, and a `.onion` chain
/// source waits up to `SOCKS_READY_TIMEOUT` for the SOCKS listener — which
/// 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> {
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();
if !cfg.is_enabled() {
return Err("no chain source configured — the wallet child is receive-only".into());
}
let already_running = self
.wallet_child
.lock()
.map_err(|e| e.to_string())?
.as_ref()
.is_some_and(|child| child.wallet_rpc_running());
let already_running = self.child_running();
if already_running {
return Ok(());
}
@ -699,9 +717,152 @@ impl Node {
*self.child_error.lock().map_err(|e| e.to_string())? = None;
self.reset_child_probe();
*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(())
}
/// 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
/// 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.
@ -711,6 +872,10 @@ impl Node {
child.stop().map_err(|e| e.to_string())?;
}
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
.store
.lock()
@ -766,9 +931,27 @@ impl Node {
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 {
state,
running,
wallet_open,
needs_passphrase,
configured: cfg.is_enabled(),
chain_source: cfg.source_label(),
height: heights.0,
@ -813,6 +996,13 @@ impl Node {
} else {
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 (height, target_height) = match progress {
Some(info) => (info.height, info.target_height),
@ -873,9 +1063,13 @@ impl Node {
/// 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 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())?;
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.
let stored = self
@ -1217,6 +1411,14 @@ impl Node {
self.point_child_at(&filename).map_err(|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 })
}
@ -1287,6 +1489,12 @@ impl Node {
self.point_child_at(&filename).map_err(|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)
}
@ -1300,27 +1508,24 @@ impl Node {
.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
/// hold is refused instead of pointing a spend-capable child at a path. A
/// running child is restarted onto the new file; an idle one is only
/// re-pointed, and the change applies on the next `start_wallet_child`. The
/// write is a read-modify-write, so the generated RPC creds survive.
/// running child is restarted onto the new file and opens it with the
/// stored passphrase; an idle one is only re-pointed, and the change
/// applies on the next `start_wallet_child`. The write is a
/// read-modify-write, so the generated RPC creds survive.
///
/// 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> {
if !self
.list_wallets()?
.iter()
.any(|w| w.wallet_filename == filename)
{
if !self.catalogue_holds(filename)? {
return Err(format!("no saved wallet in {filename}"));
}
let running = self
.wallet_child
.lock()
.map_err(|e| e.to_string())?
.as_ref()
.is_some_and(|child| child.wallet_rpc_running());
let running = self.child_running();
if running {
self.stop_wallet_child()?;
}
@ -1331,6 +1536,41 @@ impl Node {
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
/// 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.
@ -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`]).
const RATCHET_BOOTSTRAP_SALT: &[u8] = b"onionwire-ratchet-v1-bootstrap";
const RATCHET_BOOTSTRAP_ROOT_INFO: &[u8] = b"root";
@ -2213,6 +2531,7 @@ pub(crate) mod tests {
child_height: AtomicU64::new(0),
child_target: AtomicU64::new(0),
child_error: Mutex::new(None),
child_wallet: Mutex::new(ChildWalletState::Unknown),
incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(file::Inbox::new(home.join("inbox"))),
outbox,
@ -3225,6 +3544,12 @@ pub(crate) mod tests {
vec![created.record],
"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
@ -3498,4 +3823,320 @@ pub(crate) mod tests {
"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:?}");
}
}