wallet: unlocked balance, restore height, outgoing rows, send, view-only import
All checks were successful
ci / test (pull_request) Successful in 6m39s
ci / sdk (pull_request) Successful in 1m31s
android-ci / android (pull_request) Successful in 12m57s
ci / fuzz (pull_request) Successful in 5m3s

`get_balance` carries two numbers and the wallet screen only showed one:
`Node::wallet_balance_line` now reads both out of a single answer
(`balance {total} XMR · unlocked {unlocked} XMR`, the `balance 0 XMR` prefix
kept, total-only when the RPC reports no unlocked half), and
`Node::wallet_unlocked_balance` reports the unlocked half on its own with
`wallet_balance`'s `off` / `err` sentinels. `wallet_balance` keeps its shape.

`get_transfers` sends `out: true` and parses the `out` bucket, so `TransferRow`
carries `direction` (`in`, `out`, `pending`; a pending item's own `type` wins)
and the screen can tell a spent transfer from a received one.

`Wallet::restore_wallet` / `Node::wallet_restore` take an optional
`restore_height` beside the seed offset: blank omits the field, a typed `0` is
sent as `0`, `Some(n)` is a JSON number, and a non-numeric height is a local
refusal (`restore height must be a block number`). A height after the first
receive hides the older funds and this version has no rescan — the TUI says so
on its own step, whose footer is not the offset's.

`Node::wallet_send` spends to a pasted address: `check_address`, then
`xmr_to_atomic`, then `Wallet::transfer` — no friend, no `tip` frame, no chat
line, no payment row. The outgoing transfer list is the record. `pay::check_address`
and `Wallet::transfer` own the gates, so a view-only or unsynced refusal is the
string they already return.

`Wallet::import_view_only` / `Node::wallet_import_view_only` watch an address
through `generate_from_keys` with no `spendkey` in the request at all: same
filename/password refusals, `check_address`, a 64-hex view key or a local
refusal, no 64th catalogue column. The view key is typed into a hidden entry
(twice), is never sealed, never logged and never on an argv, and the screen
wipes it on every exit.

TUI: `n` sends (address, amount, then `SEND`; Esc spends nothing), `y` copies
the receive address over OSC 52, `v` imports a view-only wallet (no seed, so no
`SEEN` gate), and the seed import gained a `restore height` step between the
offset and the file passphrase. The wallet footer and its help line carry the
new keys and keep every old token. The F6 body renders in the flexible region —
a bordered block in the two-row slot it used drew its borders and clipped the
whole body, address and balance line included.

SDK: `wallet_unlocked_balance`, `wallet_send`, `wallet_view_only`,
`import_seed(password, seed, offset, height)` and
`import_view_only(password, address, view_key, height)`, plus
`TransferRow.direction`. `wallet_balance`, `import_wallet` and
`import_wallet_with_offset` are untouched.

Docs: WALLET (unlocked vs total, restore height, outgoing rows, local send,
view-only import), THREAT_MODEL (a view key entered at import is a secret and a
view-only file is not a spend authority), TUI (footer + the new keys and steps),
README (one sentence).

Tests: recorded-request cases in `tests/wallet.rs` (height as a number and
omitted when blank, `generate_from_keys` carries the view key and no spendkey,
`get_transfers` asks for `out`, `wallet_send` reaches `transfer` and never
`tip`, a bad view key never dials), node-level line/unlocked pairs from one
dial, and TUI step tests for the send, copy, height and view-only flows.

No new crate, no Cargo change, no android/ change.
This commit is contained in:
agent 2026-09-25 02:23:09 -04:00
commit 93deaa5309
No known key found for this signature in database
9 changed files with 1891 additions and 58 deletions

View file

@ -478,6 +478,11 @@ pub struct TransferRow {
pub txid: String,
pub amount: String,
pub address: String,
/// Which `get_transfers` bucket the row came from: `in`, `out`, or
/// `pending` — a pending item that names its own `type` carries that
/// instead. Not a dedupe key: a txid may appear in two buckets and both
/// rows are real.
pub direction: String,
}
/// Wallet file name used for in-app create/import (`--wallet-dir` on the RPC).
@ -739,29 +744,54 @@ impl Wallet {
/// ("Cannot retrieve spend key"); a spend-capable wallet returns the key,
/// which this discards.
/// Source: `src/wallet/wallet_rpc_server.cpp` `on_query_key`.
async fn view_only(&self) -> bool {
matches!(
self.rpc("query_key", serde_json::json!({"key_type": "spend_key"}))
.await,
Err(e) if e.to_string() == VIEW_ONLY_MSG
)
pub async fn view_only_wallet(&self) -> Result<bool> {
match self
.rpc("query_key", serde_json::json!({"key_type": "spend_key"}))
.await
{
// A spend key came back. It is discarded here: never returned,
// never logged, never persisted.
Ok(_) => Ok(false),
Err(e) if e.to_string() == VIEW_ONLY_MSG => Ok(true),
Err(e) => Err(e),
}
}
/// [`Self::view_only_wallet`] as the bool the transfer path wants: a probe
/// that cannot answer is not a view-only wallet, so the transfer's own
/// error stands.
async fn view_only(&self) -> bool {
self.view_only_wallet().await.unwrap_or(false)
}
/// Incoming, outgoing and pending transfers, each row labelled with the
/// bucket it came from — the wallet screen shows a send as well as a
/// receive. A txid that appears in two buckets stays twice: the buckets are
/// not the same event.
pub async fn get_transfers(&self) -> Result<Vec<TransferRow>> {
let v = self
.chain_rpc(
"get_transfers",
serde_json::json!({"in": true, "pending": true}),
serde_json::json!({"in": true, "out": true, "pending": true}),
)
.await?;
let mut out = Vec::new();
for key in ["in", "pending"] {
for key in ["in", "out", "pending"] {
if let Some(arr) = v.get(key).and_then(|x| x.as_array()) {
for item in arr {
// A pending item says what it will become; that is a better
// label than the bucket's own name. Anything else is the
// bucket name.
let direction = if key == "pending" {
json_str(item, "type").unwrap_or_else(|_| key.to_string())
} else {
key.to_string()
};
out.push(TransferRow {
txid: json_str(item, "txid").unwrap_or_default(),
amount: json_amount(item),
address: json_str(item, "address").unwrap_or_default(),
direction,
});
}
}
@ -790,6 +820,22 @@ impl Wallet {
.map_err(|_| Error("wallet RPC returned a non-numeric unlocked_balance".into()))
}
/// One `get_balance` round trip carrying both numbers the wallet screen
/// prints: the total piconero, and the unlocked piconero when the RPC
/// reported it as a number. `None` for the unlocked half means the field
/// was absent or not a number, and the line then shows the total alone.
/// Two numbers, one dial — the screen must not ask twice.
pub async fn balances(&self) -> Result<(String, Option<u64>)> {
let v = self
.rpc("get_balance", serde_json::json!({"account_index": 0}))
.await?;
let total = json_str(&v, "balance")?;
let unlocked = json_str(&v, "unlocked_balance")
.ok()
.and_then(|s| s.trim().parse::<u64>().ok());
Ok((total, unlocked))
}
/// The real readiness predicate: the daemon has reached the chain tip and
/// the wallet has scanned up to it. `synchronized` must be explicitly true —
/// a missing field is not-ready, never a silent pass.
@ -969,12 +1015,18 @@ impl Wallet {
/// `None`, empty or whitespace-only leaves `seed_offset` out of the request
/// entirely (never `"seed_offset":""`). Otherwise the ends are trimmed and
/// the value is sent beside the seed; interior spaces are kept.
/// `restore_height` is `restore_deterministic_wallet`'s optional block
/// number, forwarded beside the offset: `None` leaves the field out
/// entirely (never `0`), which is what a plain import wants — the wallet
/// scans from the beginning. A height *after* the first receive hides the
/// older funds, and this version has no rescan to undo that.
pub async fn restore_wallet(
&self,
filename: &str,
password: &str,
seed: &str,
seed_offset: Option<&str>,
restore_height: Option<u64>,
) -> Result<()> {
let filename = filename.trim();
if filename.is_empty() {
@ -996,10 +1048,61 @@ impl Wallet {
if let Some(offset) = seed_offset.map(str::trim).filter(|s| !s.is_empty()) {
params["seed_offset"] = serde_json::Value::String(offset.to_string());
}
if let Some(height) = restore_height {
// A JSON number, not a string: the RPC types this field as an
// integer.
params["restore_height"] = serde_json::Value::Number(height.into());
}
self.rpc("restore_deterministic_wallet", params).await?;
Ok(())
}
/// Import an address to **watch**, not to spend: `generate_from_keys` with
/// the address and its private view key, and no `spendkey` in the request
/// at all.
///
/// The view key is a secret — anyone holding it and the address can see the
/// incoming transfers — so it is trimmed, shape-checked (`64` hex
/// characters) and never echoed in an error. It is not sealed, not stored,
/// not logged and never on the argv; only the file `password` is sealed by
/// the caller. A watch-only file is not a spend authority: `transfer`
/// refuses it with the RPC's own `-29`.
///
/// `restore_height` is the same optional block number as
/// [`Self::restore_wallet`]'s: `None` omits it.
pub async fn import_view_only(
&self,
filename: &str,
password: &str,
address: &str,
view_key: &str,
restore_height: Option<u64>,
) -> 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()));
}
let view_key = view_key.trim();
if view_key.len() != 64 || !view_key.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(Error("view key must be 64 hex characters".into()));
}
crate::pay::check_address(address).map_err(|e| Error(e.to_string()))?;
let mut params = serde_json::json!({
"filename": filename,
"password": password,
"address": address,
"viewkey": view_key,
});
if let Some(height) = restore_height {
params["restore_height"] = serde_json::Value::Number(height.into());
}
self.rpc("generate_from_keys", params).await?;
Ok(())
}
/// Loopback management call: the wallet child is on the same box, so it gets
/// the short budget.
async fn rpc(&self, method: &str, params: serde_json::Value) -> Result<serde_json::Value> {