wallet: land the file-name picker fix and the wallet manager on main (from t_67879b98) #153

Merged
sirius merged 8 commits from onionwire/t_67879b98-wallet-actually-open-the-wallet-file-and into main 2026-09-23 02:33:40 +00:00
2 changed files with 190 additions and 20 deletions
Showing only changes of commit 6edcd65e96 - Show all commits

tests: take the restart's port from the child that dials it
All checks were successful
ci / test (pull_request) Successful in 6m3s
ci / sdk (pull_request) Successful in 1m14s
ci / fuzz (pull_request) Successful in 4m53s
android-ci / android (pull_request) Successful in 12m15s

`a_restart_opens_the_stored_wallet_file` failed on the Pi runner twice in a
row — CI run 905 job 1373 and run 901 job 1365 — and passed 3/3 on a 16-core
host:

  open the wallet with a passphrase: "wallet file onionwire-1 is not open —
  the wallet RPC never answered (wallet connect: Connection refused (os error
  111))"

The whole `WALLET_OPEN_WAIT` was burned on refusals, so the mock was bound on
a port the restarted child never dialled. Production is not the suspect:
`WalletChild::start_children` builds the child's argv and the `WalletClient`
URL from the same `pick_port` value, and `start_wallet_child_with` installs
that client in `self.wallet` before `open_child_wallet` dials it, so the client
can never carry the previous child's port.

The harness is the suspect. It learned the restarted child's port from the
*shared* argv log — a file every child writes — and cleared that file first.
A clear is not a synchronisation: on a loaded runner the killed child's write
lands after it, so the poller read the port of a child that was already dead
and bound the mock there. Reproduced deterministically with a stand-in whose
exec is late; with the old read the new test fails with the CI message, byte
for byte.

Each fake child now writes `<log>.<pid>` as well, and the shared copy lands
first, so a pid-named file implies the shared one is complete. A test that
spans two children reads the pid-named file: only that child can write it, so
the port belongs to the child that dials it. `WalletChild::wallet_rpc_pid`
(test-only) supplies the pid.

`open_wallet_blocking` already retries while the RPC is unreachable and gives
up after a bounded wait with a typed `OpenFailure::NotAnswering`, so it cannot
refuse forever against a merely slow child: no production change.

new test: node::tests::a_restart_is_not_given_the_stopped_childs_port
agent 2026-09-22 15:37:55 -04:00
No known key found for this signature in database

View file

@ -3079,13 +3079,33 @@ pub(crate) mod tests {
/// appended: a poller must never read half of it. It did — the port was
/// parsed while it was still being written, so `42765` read as `427`, and
/// the mock was bound on a port nothing dialled.
///
/// Every child also writes its own copy at `<log>.<pid>`, which no other
/// child can touch, and the shared copy lands first, so a pid-named file
/// implies the shared one is already complete. The shared path is what the
/// single-child tests read; a test that spans two children reads the
/// pid-named one, because a previous child's write into the shared path is
/// unsequenced against the test (see [`wait_for_child_rpc_port`]).
fn fake_child_bin(dir: &Path, name: &str, log: &Path, body: &str) -> PathBuf {
fake_child_bin_after(dir, name, log, "", body)
}
/// [`fake_child_bin`] with `prelude` run *before* the argv is written: the
/// stand-in for a runner that schedules this child's exec late.
fn fake_child_bin_after(
dir: &Path,
name: &str,
log: &Path,
prelude: &str,
body: &str,
) -> PathBuf {
std::fs::create_dir_all(dir).expect("fake bin dir");
let path = dir.join(name);
let script = format!(
"#!/bin/sh\ntmp='{}'.$$\n: > \"$tmp\"\nprintf '%s\\n' \"$0\" >> \"$tmp\"\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> \"$tmp\"; done\nmv -f \"$tmp\" '{}'\n{body}\n",
log.display(),
log.display()
"#!/bin/sh\n{prelude}\ntmp='{log}'.$$.writing\n: > \"$tmp\"\nprintf '%s\\n' \"$0\" >> \"$tmp\"\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> \"$tmp\"; done\ncp -f \"$tmp\" '{log}'.$$.shared\nmv -f '{log}'.$$.shared '{log}'\nmv -f \"$tmp\" '{log}'.$$\n{body}\n",
prelude = prelude,
log = log.display(),
body = body
);
std::fs::write(&path, script).expect("write fake bin");
let mut perms = std::fs::metadata(&path).expect("stat").permissions();
@ -3956,24 +3976,71 @@ pub(crate) mod tests {
})
}
/// 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 {
/// The pid of the running wallet child. Panics when there is none: every
/// caller has just started one.
fn child_pid(node: &Node) -> u32 {
node.wallet_child
.lock()
.ok()
.and_then(|guard| guard.clone())
.and_then(|child| child.wallet_rpc_pid())
.expect("a running wallet child")
}
/// Wait for the pid of a child that is not `previous` — the restart's.
async fn wait_for_new_child_pid(node: &Node, previous: u32) -> u32 {
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;
}
let pid = node
.wallet_child
.lock()
.ok()
.and_then(|guard| guard.clone())
.and_then(|child| child.wallet_rpc_pid());
if let Some(pid) = pid
&& pid != previous
{
return pid;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("the restart never reported a new wallet-child pid");
}
/// `--rpc-bind-port <port>` out of a fake child's argv log.
fn rpc_port_in(raw: &str) -> Option<u16> {
let lines: Vec<&str> = raw.lines().collect();
let i = lines.iter().position(|line| *line == "--rpc-bind-port")?;
lines
.get(i + 1)
.and_then(|port| port.trim().parse::<u16>().ok())
}
/// The port the child with this pid was spawned with, read out of the argv
/// log that child alone writes — `<log>.<pid>`, `mv`d into place in one step.
///
/// The shared path must not be used for this. Every child writes it and a
/// previous child's write is unsequenced against the test, so on a loaded
/// runner it lands after a poller has cleared the file: the poller then binds
/// its mock on the port of a child that has already been killed, and the
/// restarted child's `open_wallet` is refused for the whole
/// `WALLET_OPEN_WAIT` (CI run 905, job 1373 — the same message in run 901,
/// green 3/3 on a 16-core host). A pid in the file name is a handshake the
/// child cannot lose.
async fn wait_for_child_rpc_port(argv_log: &Path, pid: u32) -> u16 {
let mut name = argv_log.as_os_str().to_owned();
name.push(format!(".{pid}"));
let path = PathBuf::from(name);
for _ in 0..600 {
if let Ok(raw) = std::fs::read_to_string(&path)
&& let Some(port) = rpc_port_in(&raw)
{
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 fake child {pid} never wrote an --rpc-bind-port to {}",
path.display()
);
}
@ -4023,15 +4090,19 @@ pub(crate) mod tests {
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.
// fresh port, so the mock is bound to the port *this* spawn named while
// the open waits for its RPC to answer — read from the argv log the new
// pid owns, never from the shared path the previous child wrote: a loaded
// runner lands that write after a clear (CI run 905, job 1373).
let first_pid = child_pid(&node);
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 pid = wait_for_new_child_pid(&node, first_pid).await;
let port = wait_for_child_rpc_port(&argv_log, pid).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}"));
@ -4081,6 +4152,89 @@ pub(crate) mod tests {
node.stop_wallet_child().expect("stop");
}
/// The port the restarted child's mock listens on must come from *that*
/// child, not from the shared argv path a previous child has already written.
/// The old harness cleared that path and read it anyway, and the clear is not
/// a synchronisation: on a loaded runner the killed child's write lands after
/// it, so the mock was bound on a port nothing dialled and the restarted
/// child's `open_wallet` was refused for the whole `WALLET_OPEN_WAIT` (CI run
/// 905, job 1373; the same message in run 901, green 3/3 on a 16-core host).
/// Here the killed child's argv is left in place — the worst case of that
/// race — and the restart still reaches the mock on its own port.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_restart_is_not_given_the_stopped_childs_port() {
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("first start");
let first_pid = child_pid(&node);
// The killed child's argv is in the shared path (its own log lands first,
// so this waits for both) — the content the old harness would read.
let stale_port = wait_for_child_rpc_port(&argv_log, first_pid).await;
// The restart's exec is late here, the way a loaded runner delays it, so
// the shared path still holds the killed child's argv while the restarted
// child is already being dialled.
let restart = fake_child_bin_after(
&dir.path().join("fake-bins-restart"),
"monero-wallet-rpc",
&argv_log,
"sleep 2",
"sleep 30",
);
node.set_wallet_child_config(&loopback_child_config(restart, "onionwire-1"))
.expect("re-point the child at the late-write stand-in");
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 pid = wait_for_new_child_pid(&node, first_pid).await;
// The premise of the test: the shared path still holds the killed
// child's argv, so a harness that reads it binds the mock on the wrong
// port. Reading the restarted child's own log instead is what the fix
// is — with the shared read, this test fails on the port above after the
// whole `WALLET_OPEN_WAIT`.
assert_eq!(
rpc_port_in(&std::fs::read_to_string(&argv_log).unwrap_or_default()),
Some(stale_port),
"the restarted child must not have written the shared path yet"
);
let port = wait_for_child_rpc_port(&argv_log, pid).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");
assert!(
requests
.lock()
.unwrap()
.iter()
.any(|request| request.contains("open_wallet")),
"the restart never reached the mock on the port it dialled"
);
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
@ -4111,6 +4265,7 @@ pub(crate) mod tests {
assert!(status.running, "{status:?}");
assert!(!status.wallet_open, "{status:?}");
assert!(status.needs_passphrase, "{status:?}");
let first_pid = child_pid(&node);
node.stop_wallet_child().expect("stop");
// A second start, this time with an RPC listening on the port it was
@ -4120,7 +4275,8 @@ pub(crate) mod tests {
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 pid = wait_for_new_child_pid(&node, first_pid).await;
let port = wait_for_child_rpc_port(&argv_log, pid).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}"));

View file

@ -207,6 +207,20 @@ impl WalletChild {
self.wallet_rpc.lock().map(|g| g.is_some()).unwrap_or(false)
}
/// The pid of the running `monero-wallet-rpc` child, when there is one.
///
/// Test-only: the lib test harness names *this* spawn's argv log with it.
/// The shared log path is written by every child and a previous child's
/// write is unsequenced against anything a test does, so a restarted
/// child's port cannot be learned from it (see `node::tests`).
#[cfg(test)]
pub(crate) fn wallet_rpc_pid(&self) -> Option<u32> {
self.wallet_rpc
.lock()
.ok()
.and_then(|guard| guard.as_ref().map(std::process::Child::id))
}
/// Is a tracked child still alive? Polls the process table; an exited child
/// is reaped here so a later `stop` is a no-op.
///