Merge pull request 'tui: F7 can save and start an app-owned chain source' (#170) from onionwire/t_fcd38efc-onionwire-tui-f7-can-save-and-start-an-a into main
All checks were successful
ci / test (push) Successful in 6m45s
ci / sdk (push) Successful in 1m25s
android-ci / android (push) Successful in 12m6s

Reviewed-on: #170
This commit is contained in:
sirius 2026-09-28 05:09:45 +00:00
commit c550a197ac
4 changed files with 339 additions and 23 deletions

View file

@ -212,10 +212,23 @@ last save/test answer. The live row is the node's answer, never the draft above
it, and it is re-read by `Ctrl-R`. it, and it is re-read by `Ctrl-R`.
`Enter` saves and answers on the status row: `saved · not dialled yet — ctrl-s `Enter` saves and answers on the status row: `saved · not dialled yet — ctrl-s
starts it, ctrl-t tests the endpoint`, or the node's own refusal in its own starts it, ctrl-t tests the endpoint`, or, when a half is refused, `not saved ·
words. The endpoint is validated by `Node::wallet_save_config` — loopback host, wallet config: <why> · chain source: <why>` — one line shape either way round,
login required — and a rejected form is rejected **before** it is written: and the half that did write says so. Both halves are attempted even when one is
nothing in the sealed record moves and a running wallet is not re-dialled. refused: a wallet-RPC refusal must not silently drop a chain source the user
just picked. The endpoint's own validator is `Node::wallet_save_config`
(`Wallet::from_config` behind it) — loopback host, login required — and a
rejected form is rejected **before** it is written: nothing in the sealed record
moves and a running wallet is not re-dialled.
The one exception is an **app-owned** chain source (local `monerod`, in-process
Cuprate) with an empty `url`: the child the app spawns generates its own creds
and picks its own port (`creds()` / `pick_port()`,
`Node::start_wallet_child_with` replaces the stored client after the spawn), so
the `url`/`login` rows describe no endpoint the app dials and an empty pair must
not veto the save. A *typed* endpoint with no login is still refused — that is
the externally run RPC path (`ONIONWIRE_WALLET_RPC`), where the refusal is true.
`Ctrl-T` dials the endpoint and answers with the sanitized `PingResult` line `Ctrl-T` dials the endpoint and answers with the sanitized `PingResult` line
(never the password). `Ctrl-U` clears the focused field, which is how a hidden (never the password). `Ctrl-U` clears the focused field, which is how a hidden
login gets replaced. login gets replaced.
@ -233,6 +246,13 @@ so in the same frame — `a daemon you do not run sees this wallet's chain
traffic` — because that is the pick that moves chain trust off this box. The traffic` — because that is the pick that moves chain trust off this box. The
address must parse as `host:port` first. address must parse as `host:port` first.
A build without `cuprate-daemon` says so on the `chain` row, where the choice is
made, rather than offering it and refusing at start: the in-process wording is
followed by `this build has no in-process chain daemon — rebuild with --features
cuprate-daemon` (`crate::cuprate::NO_FEATURE_MSG`, clamped to the frame width).
The pick is still offered — builds with the feature exist, and a stored
in-process source must still be readable.
Esc is the single exit and wipes the login buffer (`Zeroizing<String>`). Esc is the single exit and wipes the login buffer (`Zeroizing<String>`).
## Wallets & settings (`F9` / `/settings`) ## Wallets & settings (`F9` / `/settings`)

View file

@ -98,7 +98,7 @@ the screen that picks the chain source:
| `Ctrl-X` | Stop it (idempotent). | | `Ctrl-X` | Stop it (idempotent). |
| `Ctrl-R` | Re-read the live node line (`off` / `connecting` / `syncing` / `ready` / `exited`). | | `Ctrl-R` | Re-read the live node line (`off` / `connecting` / `syncing` / `ready` / `exited`). |
| `Enter` | Save the endpoint and chain source without dialling or starting anything. | | `Enter` | Save the endpoint and chain source without dialling or starting anything. |
| `chain` row + `space` | Receive-only / local `monerod` / remote daemon / in-process Cuprate. | | `chain` row + `space` | Receive-only / local `monerod` / remote daemon / in-process Cuprate. In a build without `cuprate-daemon` the row carries the `rebuild with --features cuprate-daemon` wording; the pick is still offered. |
| `network` row + `space` | In-process network: mainnet (unvalidated) or testnet. | | `network` row + `space` | In-process network: mainnet (unvalidated) or testnet. |
State shown: `off` / `connecting` / `syncing` / `ready` / `exited`, plus a State shown: `off` / `connecting` / `syncing` / `ready` / `exited`, plus a
@ -113,7 +113,22 @@ Once a probe has read the daemon, the line can include `sync <height>/<target>`
`get_info`, or the local daemon's `get_info` when wallet RPC does not answer). `get_info`, or the local daemon's `get_info` when wallet RPC does not answer).
`sync 0/0` or no segment means **unknown**, not caught up. `sync 0/0` or no segment means **unknown**, not caught up.
`start` is idempotent: a live child is reported, not respawned. `start` is idempotent: a live child is reported, not respawned. A start that
fails part way is **all or nothing**: whatever that call spawned — the in-process
daemon, a `monerod`, the SOCKS child, the wallet RPC — is stopped before the
error is handed back (`WalletChild::start_with_creds`), because the caller
receives the error rather than the client, so a daemon left running would have no
owner and no handle, and would hold `18081` against the next start. The same
contract is asserted one level up
(`node::tests::a_missing_binary_fails_the_start_and_leaves_no_child`), and what a
retry reuses is the chain **datadir** on disk, never a process that outlived its
owner.
A save on an app-owned source needs no `url`/`login`: the child the app spawns
generates its own RPC creds and picks its own port, and
`Node::start_wallet_child_with` replaces the stored client after the spawn. A
typed endpoint with no login is still refused (`Wallet::from_config`), and the
screen reports both halves of a save on one line. See `docs/TUI.md`.
## Chain source ## Chain source

View file

@ -1377,8 +1377,19 @@ impl SetupSource {
} }
} }
/// The value the `chain` row prints. Every case spells itself out — colour /// Does the app spawn the wallet child for this source itself?
/// is never the only signal. ///
/// Both local cases are app-owned: `ChainSource::Local` (this box's
/// `monerod`) and `ChainSource::InProcessCuprate` (in this app) bring up a
/// `monero-wallet-rpc` of the app's own, with generated creds on a port it
/// picked, so the `url`/`login` rows describe no endpoint the app dials.
fn is_app_owned(self) -> bool {
matches!(self, Self::Local | Self::InProcess)
}
/// The chain source's own label. Every case spells itself out — colour is
/// never the only signal. `WalletSetupConfigState::chain_display` adds what
/// this build can actually do with it.
fn word(self) -> &'static str { fn word(self) -> &'static str {
match self { match self {
Self::ReceiveOnly => "receive-only · no chain, no spend", Self::ReceiveOnly => "receive-only · no chain, no spend",
@ -1619,12 +1630,44 @@ impl WalletSetupConfigState {
/// Persist the draft through the node's own validators and answer with the /// Persist the draft through the node's own validators and answer with the
/// line the status row shows. Nothing is written by hand here: a rejected /// line the status row shows. Nothing is written by hand here: a rejected
/// form leaves the running wallet and the stored chain source untouched. /// form leaves the running wallet and the stored chain source untouched.
///
/// Both halves are attempted even when one is refused — a wallet-RPC refusal
/// must not silently drop a chain source the user just picked — and the
/// answer names each half, so one line shape covers every outcome.
fn save(&mut self, node: &Node) -> String { fn save(&mut self, node: &Node) -> String {
let cfg = WalletConfig::new(&self.rpc_url, self.rpc_login.as_str(), self.no_spend); let wallet = self.save_wallet_config(node);
if let Err(e) = node.wallet_save_config(&cfg) { let chain = self.save_chain_source(node);
return format!("not saved · {e}"); if wallet.is_ok() && chain.is_ok() {
return "saved · not dialled yet — ctrl-s starts it, ctrl-t tests the endpoint"
.to_string();
} }
let chain = match self.source { format!(
"not saved · {} · {}",
saved_half("wallet config", &wallet),
saved_half("chain source", &chain)
)
}
/// The wallet RPC half of a save.
///
/// An app-owned chain source (see [`SetupSource::is_app_owned`]) brings up
/// its own `monero-wallet-rpc`: the child generates its own creds and port,
/// and `Node::start_wallet_child_with` replaces the stored client after the
/// spawn, so an empty `url` describes an endpoint the app never dials and
/// must not veto the write. `Wallet::from_config` keeps refusing an empty
/// endpoint — that is the externally run RPC path, where it is the truth.
fn save_wallet_config(&self, node: &Node) -> Result<(), String> {
if self.rpc_url.trim().is_empty() && self.source.is_app_owned() {
return Ok(());
}
let cfg = WalletConfig::new(&self.rpc_url, self.rpc_login.as_str(), self.no_spend);
node.wallet_save_config(&cfg)
}
/// The chain-source half of a save. `Ok(())` with nothing written is the
/// untouched in-process row: it keeps whatever F6 stored.
fn save_chain_source(&self, node: &Node) -> Result<(), String> {
match self.source {
SetupSource::ReceiveOnly => node.set_receive_only(), SetupSource::ReceiveOnly => node.set_receive_only(),
SetupSource::Local => node.set_local_monerod_at( SetupSource::Local => node.set_local_monerod_at(
Path::new(&self.monerod_bin), Path::new(&self.monerod_bin),
@ -1633,18 +1676,12 @@ impl WalletSetupConfigState {
), ),
SetupSource::Remote => match parse_daemon_addr(&self.daemon) { SetupSource::Remote => match parse_daemon_addr(&self.daemon) {
Some((host, port)) => node.set_remote_daemon(&host, port), Some((host, port)) => node.set_remote_daemon(&host, port),
None => return "not saved · daemon address must be host:port".to_string(), None => Err("daemon address must be host:port".to_string()),
}, },
SetupSource::InProcess if !self.chain_touched => Ok(()),
// Untouched: leave whatever held it before, including the in-process // Untouched: leave whatever held it before, including the in-process
// choice F6 used to own, rather than silently rewriting its datadir. // choice F6 used to own, rather than silently rewriting its datadir.
SetupSource::InProcess if !self.chain_touched => Ok(()),
SetupSource::InProcess => node.set_in_process_cuprate(self.cuprate_network, self.prune), SetupSource::InProcess => node.set_in_process_cuprate(self.cuprate_network, self.prune),
};
match chain {
Ok(()) => {
"saved · not dialled yet — ctrl-s starts it, ctrl-t tests the endpoint".to_string()
}
Err(e) => format!("wallet config saved · chain source: {e}"),
} }
} }
@ -1690,6 +1727,23 @@ impl WalletSetupConfigState {
} }
} }
/// The value the `chain` row prints, including the one thing this build may
/// not be able to do: without `cuprate-daemon` the in-process choice cannot
/// start anything at all, so the row says so where the choice is made rather
/// than leaving the refusal for the start (`crate::cuprate::NO_FEATURE_MSG`).
/// The choice itself is never removed — builds with the feature exist.
fn chain_display(&self) -> String {
if self.source == SetupSource::InProcess && !crate::cuprate::available() {
format!(
"{} — {}",
self.source.word(),
crate::cuprate::NO_FEATURE_MSG
)
} else {
self.source.word().to_string()
}
}
fn status_display(&self) -> String { fn status_display(&self) -> String {
self.note self.note
.clone() .clone()
@ -1711,6 +1765,15 @@ fn parse_daemon_addr(raw: &str) -> Option<(String, u16)> {
Some((host.trim().to_string(), port)) Some((host.trim().to_string(), port))
} }
/// One half of the F7 `last` line. A success says so; a failure carries the
/// validator's own words, so both halves read the same way whichever failed.
fn saved_half(what: &str, result: &Result<(), String>) -> String {
match result {
Ok(()) => format!("{what} saved"),
Err(e) => format!("{what}: {e}"),
}
}
/// 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
/// own key handler never sees it. /// own key handler never sees it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@ -4810,7 +4873,7 @@ pub fn wallet_setup_config_lines(width: u16, s: &WalletSetupConfigState) -> Vec<
s, s,
SETUP_ROW_CHAIN, SETUP_ROW_CHAIN,
"chain", "chain",
&format!("{} (space changes)", s.source.word()), &format!("{} (space changes)", s.chain_display()),
)); ));
if s.source == SetupSource::Remote { if s.source == SetupSource::Remote {
out.push(Line::from( out.push(Line::from(
@ -7724,6 +7787,161 @@ mod wallet_setup_config_tests {
} }
} }
/// The app-owned chain source is the one path that needs no external wallet
/// RPC: `url`/`login` name an endpoint only `monero-wallet-rpc` uses, and on
/// this path the app spawns the child with its own generated creds and port
/// (`Node::start_wallet_child_with` replaces the stored client after the
/// spawn). An empty pair must therefore not veto the save — that refusal is
/// `Wallet::from_config`'s, and it is about an *externally run* endpoint.
#[test]
fn an_app_owned_source_saves_without_a_typed_wallet_rpc() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("home");
let (mut app, _rt) = app(&home);
app.handle_key(key(KeyCode::F(7))).expect("F7");
pick_source(&mut app, SetupSource::InProcess);
focus_row(&mut app, SETUP_ROW_NETWORK);
app.handle_key(key(KeyCode::Char(' '))).expect("space");
assert_eq!(state_of(&app).cuprate_network, ChainNetwork::Testnet);
let state = state_of(&app);
assert!(
state.rpc_url.is_empty() && state.rpc_login.is_empty(),
"this test is only meaningful with an empty endpoint: {state:?}"
);
assert_eq!(
app.node.wallet_child_config().source,
ChainSource::None,
"nothing is stored before the save"
);
app.handle_key(key(KeyCode::Enter)).expect("enter");
let note = state_of(&app)
.note
.as_deref()
.expect("a status line")
.to_string();
assert!(note.starts_with("saved"), "the save must land: {note}");
match &app.node.wallet_child_config().source {
ChainSource::InProcessCuprate { network, .. } => assert_eq!(
*network,
ChainNetwork::Testnet,
"the network pick must reach the stored source"
),
other => panic!("expected the in-process source to be stored, got {other:?}"),
}
}
/// One write must not cancel the other: a wallet-config refusal still leaves
/// the chain-source write done, and the `last` line says both.
#[test]
fn a_wallet_rpc_refusal_does_not_cancel_the_chain_source_write() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
pick_source(&mut app, SetupSource::Remote);
focus_row(&mut app, SETUP_ROW_DAEMON);
app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL))
.expect("ctrl-u");
type_str(&mut app, "127.0.0.1:18089");
assert!(state_of(&app).rpc_url.is_empty());
app.handle_key(key(KeyCode::Enter)).expect("enter");
let note = state_of(&app)
.note
.as_deref()
.expect("a status line")
.to_string();
assert!(
note.contains("wallet RPC endpoint required"),
"the endpoint refusal must be reported: {note}"
);
assert!(
note.contains("chain source saved"),
"the chain-source write must be reported, not dropped: {note}"
);
match &app.node.wallet_child_config().source {
ChainSource::Remote { host, port } => {
assert_eq!(host, "127.0.0.1");
assert_eq!(*port, 18089);
}
other => panic!("the remote source must still be written, got {other:?}"),
}
}
/// The other half of the same rule: a *typed* endpoint with no login is a
/// broken wallet config, and saying so is the point. The app-owned source
/// does not excuse a half-typed endpoint.
#[test]
fn a_typed_endpoint_without_a_login_is_still_refused() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
type_str(&mut app, URL);
pick_source(&mut app, SetupSource::InProcess);
app.handle_key(key(KeyCode::Enter)).expect("enter");
let note = state_of(&app)
.note
.as_deref()
.expect("a status line")
.to_string();
assert!(
note.contains("credentials"),
"a typed endpoint with no login must still be refused: {note}"
);
assert!(
app.node.wallet_config().is_none(),
"a refused endpoint must not be stored"
);
}
/// A build without `cuprate-daemon` cannot start the in-process daemon at
/// all, so the `chain` row has to say that where the choice is made rather
/// than offering one whose only answer is `cuprate::NO_FEATURE_MSG`.
#[cfg(not(feature = "cuprate-daemon"))]
#[test]
fn a_build_without_the_daemon_says_so_on_the_chain_row() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
pick_source(&mut app, SetupSource::InProcess);
let body = wallet_setup_config_text(200, state_of(&app));
assert!(
body.contains("in-process node"),
"the choice is still offered:\n{body}"
);
assert!(
body.contains("--features cuprate-daemon"),
"the row must name the feature this build lacks:\n{body}"
);
}
/// The same row in a build that *can* start it: no unavailable wording, and
/// the choice still reaches the store.
#[cfg(feature = "cuprate-daemon")]
#[test]
fn a_build_with_the_daemon_does_not_disown_the_in_process_choice() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
pick_source(&mut app, SetupSource::InProcess);
let body = wallet_setup_config_text(200, state_of(&app));
assert!(
body.contains("in-process node · cuprate in this app"),
"the row keeps the plain wording:\n{body}"
);
assert!(
!body.contains("rebuild with --features cuprate-daemon"),
"a build that can start it must not say it cannot:\n{body}"
);
}
/// F6 is the wallet again: the chain picker and the child's start/stop keys /// F6 is the wallet again: the chain picker and the child's start/stop keys
/// moved to F7, so pressing them there changes nothing and the store is not /// moved to F7, so pressing them there changes nothing and the store is not
/// touched behind the user's back. /// touched behind the user's back.

View file

@ -527,6 +527,13 @@ impl WalletChild {
Err(e) => { Err(e) => {
// A failure after the SOCKS child came up must not leave the // A failure after the SOCKS child came up must not leave the
// listener (or monerod) orphaned behind the error. // listener (or monerod) orphaned behind the error.
//
// That includes the in-process chain daemon, deliberately: this
// call hands back the error instead of the client, so nothing
// would own a daemon left running — and the next start could not
// bind the port it was holding. The chain *datadir* is what
// outlives a failed start and what a retry reuses, never a
// daemon that no longer has an owner.
let _ = self.stop(); let _ = self.stop();
Err(e) Err(e)
} }
@ -2151,8 +2158,14 @@ mod tests {
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log)); .with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
// The wallet RPC child is fake, so `start` reaches only the daemon: the // The wallet RPC child is fake, so `start` reaches only the daemon: the
// whole point of the in-process source is that the daemon *is* us. // whole point of the in-process source is that the daemon *is* us. The
let _ = child.start(&store); // hold is what a `sh` fake cannot do itself — binding the port the gate
// probes — so this test exercises the successful start it is named for
// (see [`test_support::PublishedPortHold`]).
let _hold = PublishedPortHold::watching(std::slice::from_ref(&rpc_log));
child
.start(&store)
.expect("the daemon and the fake wallet RPC both come up");
let addr = format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}"); let addr = format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}");
assert!( assert!(
waits_for_tcp(&addr, Duration::from_secs(20)), waits_for_tcp(&addr, Duration::from_secs(20)),
@ -2174,6 +2187,56 @@ mod tests {
assert!(closed, "the daemon's RPC listener outlived stop()"); assert!(closed, "the daemon's RPC listener outlived stop()");
} }
/// The other half of the same contract, and the reason `start_with_creds`
/// stops what it started on *any* failure after the children came up: an
/// in-process daemon survives a wallet-RPC failure only inside a `WalletChild`
/// somebody still owns, and this call is about to hand the error back instead
/// of the client — so a daemon left behind would have no owner, no handle and
/// no way to stop it, while the next `start` could not bind its port. The
/// chain datadir is what outlives a failed start; the process does not.
/// `node::tests::a_missing_binary_fails_the_start_and_leaves_no_child`
/// asserts the same contract one level up.
///
/// Nothing holds the fake wallet RPC's port here, so its readiness gate times
/// out *after* the in-process daemon is already up — the failure path this
/// pins. The error naming `monero-wallet-rpc` (not the chain daemon) is what
/// proves the daemon had come up first.
#[cfg(feature = "cuprate-daemon")]
#[test]
fn a_start_that_fails_after_the_daemon_came_up_leaves_nothing_running() {
let dir = tmp_dir("cuprate-late-failure");
let store = open_store(&dir);
let rpc_log = dir.join("wallet-rpc.argv");
let child = WalletChild::new(in_process_source(&dir), dir.join("wallet"), None)
.unwrap()
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
let err = child
.start(&store)
.expect_err("a wallet RPC that never binds its port fails the start")
.to_string();
assert!(err.contains("monero-wallet-rpc"), "{err}");
assert!(
!child.running(),
"a failed start must not leave a daemon running: {err}"
);
assert!(
dir.join("chain").exists(),
"the chain datadir is the part that outlives a failed start"
);
let addr = format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}");
let mut closed = false;
for _ in 0..60 {
if std::net::TcpStream::connect(&addr).is_err() {
closed = true;
break;
}
std::thread::sleep(Duration::from_millis(250));
}
assert!(closed, "the daemon's RPC listener outlived a failed start");
}
fn probe_status(state: WalletChildState, height: u64, target_height: u64) -> WalletChildStatus { fn probe_status(state: WalletChildState, height: u64, target_height: u64) -> WalletChildStatus {
WalletChildStatus { WalletChildStatus {
state, state,