wallet: unlocked balance, restore height, outgoing rows, send, view-only import #158

9 changed files with 1891 additions and 58 deletions

View file

@ -328,6 +328,9 @@ wallet-file passphrase; blank skips it, a wrong one opens a different wallet and
does not fail).
Type `SPEND` then `SEEN` on create. Each wallet gets its own file name
(`onionwire-1`, `onionwire-2`, …); the RPC must be started with `--wallet-dir`.
`F6` then `n` sends to a pasted address as a plain local `transfer` (no chat
frame), and `F6` then `v` imports an address to watch from its view key with no
spend key at all.
`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

View file

@ -498,7 +498,10 @@ impl Wire {
/// Current wallet balance as a display string, or `"off"` / `"err"`.
///
/// Returns `"off"` when the wallet is not configured (no `ONIONWIRE_WALLET_RPC`),
/// `"err"` when the wallet RPC call failed, and `"balance X.X XMR"` on success.
/// `"err"` when the wallet RPC call failed, and the amount in XMR as a bare
/// number on success (the core's `atomic_to_xmr_str`, e.g. `"0.5"`) — the
/// sentinels are what a caller branches on, so the number is not wrapped in
/// any label here.
/// A stopped node (shut-down handle) returns `"off"` — the wallet is not
/// accessible without a live node, and the UI treats "off" as "wallet not
/// available" rather than an error state.
@ -509,6 +512,59 @@ impl Wire {
}
}
/// The spendable part of the balance, as a display string with exactly the
/// same sentinels as [`Wire::wallet_balance`]: `"off"` when the wallet is not
/// configured or the node is gone, `"err"` when the RPC did not answer with
/// a number, else the bare XMR number. The rest of the balance is either
/// locked (unconfirmed income) or immature (recent coinbase), so a UI shows
/// both: funds that exist, and funds that can move now.
pub async fn wallet_unlocked_balance(&self) -> String {
match self.node() {
Ok(node) => node.wallet_unlocked_balance().await,
Err(_) => "off".to_string(),
}
}
/// Is the wallet file the child has open **watch-only** (imported from an
/// address and a view key, so it holds no spend key)?
///
/// Proven over RPC: `query_key` for the spend key is refused with monero's
/// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (`-29`) exactly on a wallet that
/// cannot spend; a spend key that does come back is discarded inside the
/// node, never returned and never logged. An unconfigured wallet — or a
/// stopped node — is an error, **not** `true`: claiming a watch-only wallet
/// exists when there is none would be a lie. `WireError.Failed` carries the
/// core's own not-configured message, `WireError.Stopped` a shut-down node.
///
/// The Kotlin binding is `Wire.walletViewOnly()`.
pub async fn wallet_view_only(&self) -> WResult<bool> {
self.node()?
.wallet_view_only()
.await
.map_err(WireError::new)
}
/// Send XMR to a pasted address. Returns the transaction hash.
///
/// A **local** transfer on this node's own wallet: no friend, no `tip`
/// frame, no chat line and no payment row — the wallet's outgoing transfer
/// list is the record. `address` and `amount_xmr` are checked here first, so
/// an empty field, an invalid address or an unparsable amount fails without
/// touching the RPC (`WireError.Failed` with the core's own message).
///
/// The spend gates are the core's and are surfaced as they are: a wallet
/// configured `ONIONWIRE_WALLET_NO_SPEND=1` or a watch-only file is refused
/// with the view-only message, and a wallet that has not reached the chain
/// tip is refused rather than allowed to fail opaquely.
///
/// The Kotlin binding is `Wire.walletSend(address, amountXmr)`.
pub async fn wallet_send(&self, address: String, amount_xmr: String) -> WResult<String> {
self.node()?
.wallet_send(&address, &amount_xmr)
.await
.map_err(WireError::new)
}
/// Receive address for the wallet screen: a freshly created subaddress when
/// the wallet is configured, else the profile `xmr_addr` fallback.
///
@ -536,6 +592,7 @@ impl Wire {
txid: r.txid,
amount: pay::atomic_to_xmr_str(&r.amount),
address: r.address,
direction: r.direction,
})
.collect())
}
@ -770,7 +827,7 @@ impl Wire {
/// seed-offset passphrase.
pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> {
self.node()?
.wallet_restore(&password, &seed, None)
.wallet_restore(&password, &seed, None, None)
.await
.map_err(WireError::new)
.map(|_| ())
@ -800,7 +857,78 @@ impl Wire {
Some(offset)
};
self.node()?
.wallet_restore(&password, &seed, offset)
.wallet_restore(&password, &seed, offset, None)
.await
.map_err(WireError::new)
.map(|_| ())
}
/// Import a wallet from an existing 25-word seed, with the two optional
/// inputs the core takes beside it: Monero's seed-offset passphrase and a
/// restore height.
///
/// This is the call a first-run import screen makes: it supersedes
/// [`Wire::import_wallet`] and [`Wire::import_wallet_with_offset`] without
/// changing either of them, so an existing caller keeps compiling.
///
/// `seed_offset` is Monero's second spend secret (not the file passphrase):
/// blank or whitespace means "no offset" and the request carries no
/// `seed_offset` field. `restore_height` is a block number as typed:
/// blank means "scan from 0" and the request carries no `restore_height`
/// field either — never a `0`. Anything else that is not a block number is
/// refused locally with `restore height must be a block number`.
///
/// A height *after* the first receive hides the older funds, and this
/// version has no rescan to undo that: the UI has to say so, not fix it.
pub async fn import_seed(
&self,
password: String,
seed: String,
seed_offset: String,
restore_height: String,
) -> WResult<()> {
let offset = seed_offset.trim();
let offset = if offset.is_empty() {
None
} else {
Some(offset)
};
let height = restore_height_arg(&restore_height)?;
self.node()?
.wallet_restore(&password, &seed, offset, height)
.await
.map_err(WireError::new)
.map(|_| ())
}
/// Import an address to **watch**: `generate_from_keys` with the address and
/// its private view key, and no spend key at all. The wallet file this
/// creates can see incoming transfers and cannot spend — it is not a spend
/// authority, and `Wire::walletSend` on it is refused with the view-only
/// message.
///
/// `view_key` is trimmed and must be 64 hex characters; the request never
/// carries a `spendkey` field, and the key is neither stored nor sealed
/// (`password` is the wallet *file* passphrase and is what gets sealed, so
/// the file reopens on the next start). A wrong-shape key is refused locally
/// with `view key must be 64 hex characters` and the typed key is never part
/// of that message.
///
/// `restore_height` behaves exactly as in [`Wire::import_seed`]: blank omits
/// the field, and a non-numeric value is the same local refusal.
///
/// The Kotlin binding is `Wire.importViewOnly(password, address, viewKey,
/// restoreHeight)`.
pub async fn import_view_only(
&self,
password: String,
address: String,
view_key: String,
restore_height: String,
) -> WResult<()> {
let height = restore_height_arg(&restore_height)?;
self.node()?
.wallet_import_view_only(&password, &address, &view_key, height)
.await
.map_err(WireError::new)
.map(|_| ())
@ -1247,6 +1375,11 @@ pub struct TransferRow {
pub txid: String,
pub amount: String,
pub address: String,
/// Which bucket the row came from: `in`, `out`, or `pending` — a pending
/// item that names its own `type` carries that instead. A client renders the
/// sign of the amount from this, and must not treat it as a dedupe key: a
/// txid may appear in two buckets and both rows are real.
pub direction: String,
}
/// One row of the saved-wallet catalogue, for the wallet picker.
@ -1602,6 +1735,23 @@ pub fn verify_tip(pubkey_hex: String, tip: Tip) -> bool {
}
}
/// A typed restore height as the core's `Option<u64>`.
///
/// Blank (or whitespace) is `None` — "scan from the beginning", and the request
/// carries no `restore_height` field at all. A typed `0` is `Some(0)` and *is*
/// sent: the user asked for it. Anything that is not a block number is refused
/// here, before any dial; the message says what a block number is and never
/// echoes the typed text back.
fn restore_height_arg(text: &str) -> WResult<Option<u64>> {
let text = text.trim();
if text.is_empty() {
return Ok(None);
}
text.parse::<u64>()
.map(Some)
.map_err(|_| WireError::new("restore height must be a block number"))
}
/// Convert a user-facing XMR amount string to a piconero string.
///
/// Accepts `"0.5"`, `"1"`, `"0.001"` etc. Returns the piconero string on
@ -1877,6 +2027,60 @@ mod tests {
assert_eq!(block_on(stopped_wire().wallet_balance()), "off");
}
#[test]
fn wallet_unlocked_balance_on_stopped_handle_returns_off() {
assert_eq!(block_on(stopped_wire().wallet_unlocked_balance()), "off");
}
#[test]
fn wallet_send_on_stopped_handle_is_stopped_error() {
let err = block_on(stopped_wire().wallet_send(
"4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge"
.to_string(),
"1".to_string(),
))
.expect_err("must fail");
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
}
#[test]
fn wallet_view_only_on_stopped_handle_is_stopped_error() {
let err = block_on(stopped_wire().wallet_view_only()).expect_err("must fail");
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
}
/// A blank height is "no field", a typed number is that number, and a typo
/// is a local refusal — never a silent `0`.
#[test]
fn restore_height_arg_blanks_omits_and_refuses_a_typo() {
assert_eq!(restore_height_arg("").unwrap(), None);
assert_eq!(restore_height_arg(" ").unwrap(), None);
assert_eq!(restore_height_arg("3210000").unwrap(), Some(3_210_000));
assert_eq!(restore_height_arg(" 42 ").unwrap(), Some(42));
assert_eq!(
restore_height_arg("0").unwrap(),
Some(0),
"a typed 0 is what the user asked for, not an omission"
);
let err = restore_height_arg("block 42").expect_err("not a block number");
assert_eq!(err.to_string(), "restore height must be a block number");
}
/// The import refuses a bad height before it ever reaches the node, so the
/// message is the SDK's own and no dial is implied.
#[test]
fn import_seed_refuses_a_non_numeric_height_locally() {
let err = block_on(stopped_wire().import_seed(
"pw".to_string(),
"lumber tacit lemon ivory risk".to_string(),
String::new(),
"not-a-height".to_string(),
))
.expect_err("must fail");
assert_eq!(err.to_string(), "restore height must be a block number");
assert!(matches!(err, WireError::Failed { .. }), "got {err:?}");
}
#[test]
fn wallet_receive_address_on_stopped_handle_is_stopped_error() {
let err = block_on(stopped_wire().wallet_receive_address()).expect_err("must fail");

View file

@ -299,6 +299,30 @@ now one of the places a spending secret can be read from.
Treat any screen that shows a seed or a private key the way you treat the
wallet file itself.
## A view key entered at import is a secret, and a view-only file cannot spend
Importing an address to watch means typing that address's **private view key**
into OnionWire. It is a secret of a different kind from a seed: it cannot spend,
but anyone holding it *and* the address sees every incoming transfer — amounts,
timing, and which outputs belong to the wallet.
- It is entered on a hidden entry (the TUI asks for it twice; a mismatch is
`view keys do not match` and never dials), travels in the `generate_from_keys`
request body, and is kept nowhere else: never sealed, never in the wallet
catalogue, never logged, never on an argv. The core wipes its own copy when the
call returns and the screen wipes the typed buffer on every exit, `Esc`
included.
- The request carries **no `spendkey` field**, so the file the RPC writes is not
a spend authority: `transfer` on it is the RPC's own `-29` watch-only refusal.
- The file **passphrase** is still sealed, exactly as for a created or
seed-imported wallet — that is what reopens the file on the next start, and an
attacker with the store passphrase and a spend-capable file can move the
balance. The seal protects the file passphrase; it is not a protection for the
view key, and a view-only file is not a spend authority either way.
- What this does **not** stop: a view key pasted from a clipboard, a shoulder
surfer, a screen recorder, or a compromised wallet host. Import a view key only
on a machine you would trust with your incoming-transfer history.
## Backup file is the identity
`/backup` writes the identity and Noise static secrets. Treat the file like `onionwire.db`. Restore overwrites self keys and does **not** rewrite the friends table.

View file

@ -24,7 +24,7 @@ ASCII chrome.
| `ConfirmKeys` / `Passphrase` | `/backup`, `/restore` | Type `BACKUP`/`RESTORE`, then passphrase |
| `Wallet` | `F6` | Receive QR, balance, transfers, child, chain source |
| `WalletSelect` | `F6` `w` | Saved wallets, pick one or create one |
| `WalletSetup` | `F6` `c` / `i`, or `/wallet create` / `import` | Spend warning, seed, optional seed-offset passphrase, import |
| `WalletSetup` | `F6` `c` / `i` / `n` / `v`, or `/wallet create` / `import` | Spend warning, seed, optional seed-offset passphrase, restore height, import, send, view-only import |
| `WalletsSettings` | `F9` or `/settings` | Discovery menu (does not replace F-keys) |
| `PeerPayments` | F9 then `p` | Peer-scoped `/pay` / `/tip` history |
| `Quit` | `Ctrl-Q` | Type `CLEAR` or `QUIT` |
@ -110,7 +110,7 @@ Pane-specific (`pane_footer_hints`):
Footer:
```
c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help
c create i import v view-only y copy n send r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help
```
| Key | Effect |
@ -118,7 +118,10 @@ c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc
| `r` or Enter | Toggle receive-address QR |
| `w` | Saved wallets (`WalletSelect`) |
| `c` | Create wallet (`SPEND` then seed once, type `SEEN`) |
| `i` | Import 25-word seed |
| `i` | Import 25-word seed (then an optional seed-offset passphrase and restore height) |
| `v` | Import an address to **watch** (address, view key twice, restore height, file passphrase) |
| `y` | Copy the receive address (OSC 52). Never a seed, never a view key |
| `n` | Send to a pasted address (address, amount, then `SEND`) — a local `transfer`, not a `/tip` |
| `s` | Start app-owned wallet child |
| `x` | Stop child (idempotent) |
| `p` | Probe child (RPC answering? chain at tip?) |
@ -132,8 +135,20 @@ The chain line for an in-process source always carries
Cuprate needs `--features cuprate-daemon`; without it, start fails with that
feature name.
`F6` shows one balance line — `balance 0.9 XMR · unlocked 0.45 XMR`, the total
and the part a spend can use out of a single `get_balance` (`wallet off` when no
wallet RPC is configured, `balance —` when the RPC did not answer with a total).
Create/import require the wallet RPC started with `--wallet-dir`. Filename:
`onionwire`. Seed is never collected on the composer.
`onionwire`. Seed is never collected on the composer, and never copied.
The import's two optional steps have their own footers: the offset step says
`blank Enter skips Esc cancel ? help`, the restore-height step says
`blank Enter scans from 0 Esc cancel ? help` (blank means "scan from 0"; a
height after your first receive hides the older funds and this version has no
rescan). The send confirmation says `type SEND Esc cancel ? help`, and `Esc`
there spends nothing. The view-only import has no seed, so it has no `SEEN`
step.
## Saved wallets (`F6` then `w`)

View file

@ -289,10 +289,57 @@ wallet actually holds (the derived seed), so a later seed backup restores this
wallet **without** the offset; the original words plus the offset are the other
backup, and the app keeps neither.
The import asks for an optional **restore height** after the offset step. Blank
`Enter` scans from block 0, which is what a plain import wants. A height *after*
your first receive **hides the older funds** — the wallet never scans below it —
and this version has **no rescan** to undo that, so set a height at or before the
first incoming transfer or leave it blank. The request carries a `restore_height`
field only when you typed one (a typed `0` is sent as `0`); a height that is not
a block number is refused locally with `restore height must be a block number`.
`F6` then `v` imports an address to **watch** instead: `generate_from_keys` with
the address and its private **view key**, and no `spendkey` in the request at
all. The file it writes can see incoming transfers and cannot spend — `transfer`
on it is the RPC's own `-29`, surfaced as the view-only message. The view key is
a secret (anyone holding it and the address sees the incoming transfers): it is
typed into a hidden entry (twice — a mismatch is `view keys do not match` with no
dial), goes to the RPC, and is kept nowhere else — not sealed, not in the
catalogue, not logged, never on an argv. What *is* sealed is the wallet-file
passphrase, exactly as for a created or seed-imported wallet, so the file reopens
on the next start. There is no seed on this path, so there is no `SEEN` step.
RPC must be started with `--wallet-dir` (not only `--wallet-file`). A created
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.
## Balance: total and unlocked
`get_balance` answers with two numbers and OnionWire exposes both: the **total**
(`wallet_balance`, everything the wallet has scanned, including amounts still
locked behind confirmations or immature) and the **unlocked** part
(`wallet_unlocked_balance`), the funds a spend can use right now. The wallet
screen shows them on one line, from one request:
balance 0.9 XMR · unlocked 0.45 XMR
`Node::wallet_balance_line` builds it, and the two sentinels are its own:
`wallet off` when no wallet RPC is configured, `balance —` when the RPC did not
answer with a total. (`wallet_balance` and `wallet_unlocked_balance` keep the
bare `off` / `err` words the WALLETS & SETTINGS menu tones and the SDK read.) A
wallet that shows a balance but refuses to spend is usually this distinction: the
incoming transfer is still confirming. Both numbers come out of one `get_balance`
request, never two.
## Send to a pasted address (`F6` then `n`)
A **local** `transfer` on the wallet this install has configured: an address, an
amount, then `SEND` to confirm. There is no friend, no `tip` frame, no chat line
and no payment row — the wallet's own outgoing transfer list is the record, so
`n` works with no peer online and leaves nothing in a conversation. A view-only
or unsynced wallet is refused with the same strings `/tip` uses. The receive
address has its own key, `y`, which copies it through the terminal's clipboard
(OSC 52); the seed path stays clipboard-free.
## Recommended topology (view-only)
```
@ -340,6 +387,7 @@ Restore from a height at or before the first incoming transaction.
| Receipt verification (`get_transfers`) | works, if daemon is synced | works, if daemon is synced |
| Profile `xmr_addr` fallback when RPC is down | works | works |
| `/tip <xmr>` (`transfer`) | **cannot work** | works |
| send to a pasted address (`F6` `n`, `transfer`) | **cannot work** | works |
| OnionWire copies your spend key into its own process | never | never (it stays in the wallet file / RPC) |
| Show the backup (seed via `query_key mnemonic`) | **no seed to show** (the RPC answers `-29`) | works |
| Show the private keys (`wallet_keys`) | view key only, `spend_key` is `None` | view + spend key |

View file

@ -1097,6 +1097,22 @@ impl Node {
}
}
/// The spendable part of the balance, as a human-readable XMR string, with
/// the same sentinels as [`Self::wallet_balance`]: `off` when the wallet is
/// not configured, `err` when the RPC did not answer with a number, else
/// the unlocked piconero formatted the same way. One `get_balance` call
/// carries both numbers, so this does not dial twice.
pub async fn wallet_unlocked_balance(&self) -> String {
let w = self.wallet_snapshot();
if !w.configured() {
return "off".into();
}
match w.balances().await {
Ok((_, Some(unlocked))) => crate::pay::atomic_to_xmr_str(&unlocked.to_string()),
_ => "err".into(),
}
}
pub fn wipe_messages(&self) -> Result<(), String> {
self.store
.lock()
@ -1319,7 +1335,7 @@ impl Node {
}
let profile_addr = self.self_profile()?.xmr_addr;
if profile_addr.is_empty() {
return Err("no receive address — set profile xmr or ONIONWIRE_WALLET_RPC".into());
return Err(NO_RECEIVE_ADDRESS_MSG.into());
}
pay::check_address(&profile_addr).map_err(|e| e.to_string())?;
Ok(profile_addr)
@ -1342,30 +1358,73 @@ impl Node {
pay::check_address(&profile_addr).map_err(|e| e.to_string())?;
return Ok(profile_addr);
}
Err("no receive address — set profile xmr or ONIONWIRE_WALLET_RPC".into())
Err(NO_RECEIVE_ADDRESS_MSG.into())
}
/// Formatted balance for the wallet screen, or "off" when the wallet is not
/// configured. Calls `pay::atomic_to_xmr_str` so the UI never parses
/// piconero itself.
/// The wallet screen's balance line. One `get_balance` answer carries both
/// numbers, so it shows the total and the part a spend can use:
/// `balance {total} XMR · unlocked {unlocked} XMR`. The `balance 0 XMR`
/// prefix stays when the total is 0, with the unlocked segment beside it; an
/// unlocked half the RPC did not report leaves the total-only line. The two
/// sentinels are not `Node::wallet_balance`'s: `wallet off` when no wallet
/// RPC is configured, and `balance —` when the RPC did not answer with a
/// total. `pay::atomic_to_xmr_str` formats the numbers, so the UI never
/// parses piconero itself.
pub async fn wallet_balance_line(&self) -> String {
let w = self.wallet_snapshot();
if w.configured() {
match w.get_balance().await {
Ok(b) if !b.is_empty() => {
let xmr = pay::atomic_to_xmr_str(&b);
if xmr == "0" {
"balance 0 XMR".to_string()
} else {
format!("balance {xmr} XMR")
}
}
Ok(_) => "balance —".to_string(),
Err(_) => "balance —".to_string(),
}
} else {
"wallet off".to_string()
if !w.configured() {
return "wallet off".to_string();
}
let (total, unlocked) = match w.balances().await {
Ok(pair) => pair,
Err(_) => return "balance —".to_string(),
};
if total.is_empty() {
return "balance —".to_string();
}
let xmr = pay::atomic_to_xmr_str(&total);
let head = if xmr == "0" {
"balance 0 XMR".to_string()
} else {
format!("balance {xmr} XMR")
};
match unlocked {
Some(unlocked) => {
let unlocked = pay::atomic_to_xmr_str(&unlocked.to_string());
format!("{head} · unlocked {unlocked} XMR")
}
None => head,
}
}
/// Send XMR to a pasted address. A **local** `transfer` on the wallet this
/// node has configured: no friend, no `tip` frame, no chat line and no
/// payment row — the outgoing transfer list is the record of it.
///
/// The address and the amount are checked first, so an empty field, a bad
/// address or an unparsable amount is a local refusal with no dial. Returns
/// the tx hash. `Wallet::transfer` owns the gates that matter and surfaces
/// them as they are: an explicit no-spend wallet, an unsynced chain, and the
/// RPC's own view-only refusal.
pub async fn wallet_send(&self, address: &str, amount_xmr: &str) -> Result<String, String> {
let address = address.trim();
let amount_xmr = amount_xmr.trim();
if address.is_empty() {
return Err("address required".into());
}
if amount_xmr.is_empty() {
return Err("amount required".into());
}
pay::check_address(address).map_err(|e| e.to_string())?;
let atomic = pay::xmr_to_atomic(amount_xmr).map_err(|e| e.to_string())?;
let amount: u64 = atomic
.parse()
.map_err(|_| "amount too large for wallet RPC".to_string())?;
let w = self.wallet_snapshot();
if !w.configured() {
return Err(wallet::NOT_CONFIGURED_MSG.into());
}
w.transfer(address, amount).await.map_err(|e| e.to_string())
}
/// Recent in/out transfers for the wallet screen, newest first, capped to a
@ -1480,18 +1539,23 @@ impl Node {
/// never logged, never on the argv, and a wrong one is not an error — the
/// RPC succeeds and the wallet is a different one. Only `password` is sealed
/// here, into the same record the next start opens the file with.
/// `restore_height` is the import's optional block number, forwarded beside
/// the offset: `None` omits the field and the wallet scans from the
/// beginning. A height after the first receive hides the older funds, and
/// this version has no rescan.
pub async fn wallet_restore(
&self,
password: &str,
seed: &str,
seed_offset: Option<&str>,
restore_height: Option<u64>,
) -> Result<WalletRecord, String> {
let w = self.wallet_snapshot();
if !w.configured() {
return Err(wallet::NOT_CONFIGURED_MSG.into());
}
let filename = self.next_wallet_filename()?;
w.restore_wallet(&filename, password, seed, seed_offset)
w.restore_wallet(&filename, password, seed, seed_offset, restore_height)
.await
.map_err(|e| e.to_string())?;
let record = self
@ -1509,6 +1573,70 @@ impl Node {
Ok(record)
}
/// Import an address to **watch**: a wallet file with a view key and no
/// spend key. Same shape as [`Self::wallet_restore`] — its own file name, a
/// catalogue row, the child pointed at it, the *file* passphrase sealed and
/// marked open — because a watch-only file is still a wallet the app has to
/// reopen on the next start.
///
/// The view key is a secret: it goes to the RPC and nowhere else. It is not
/// sealed, not written to the catalogue (which grows no column for it) and
/// never logged; the node's own copy is a `Zeroizing` that is wiped when the
/// call returns. `generate_from_keys` is sent without a spend key, so the
/// resulting file is not a spend authority — `transfer` refuses it with the
/// RPC's own view-only answer.
///
/// `restore_height` is the same optional block number as
/// [`Self::wallet_restore`]'s: `None` omits it.
pub async fn wallet_import_view_only(
&self,
password: &str,
address: &str,
view_key: &str,
restore_height: Option<u64>,
) -> Result<WalletRecord, String> {
let w = self.wallet_snapshot();
if !w.configured() {
return Err(wallet::NOT_CONFIGURED_MSG.into());
}
let filename = self.next_wallet_filename()?;
let imported = {
let key = Zeroizing::new(view_key.to_string());
w.import_view_only(&filename, password, address, key.as_str(), restore_height)
.await
};
imported.map_err(|e| e.to_string())?;
let record = self
.record_wallet(&filename)
.map_err(|e| format!("wallet {filename} imported but not remembered: {e}"))?;
self.point_child_at(&filename).map_err(|e| {
format!("wallet {filename} imported but the child is not pointed at it: {e}")
})?;
// The file passphrase and nothing else: `seal_wallet_passphrase` opens
// this file on the next start, exactly as it does for a created wallet.
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)
}
/// Is the wallet file the child has open **watch-only**?
///
/// `query_key spend_key` is the signal monero exposes for a wallet with no
/// spend key: `true` for the `-29` refusal, `false` when a spend key comes
/// back — that key is discarded, never returned and never logged. An
/// unconfigured wallet is refused locally with the same message the other
/// wallet calls use, *not* `true`: claiming a view-only wallet exists when
/// none does would be a lie.
pub async fn wallet_view_only(&self) -> Result<bool, String> {
let w = self.wallet_snapshot();
if !w.configured() {
return Err(wallet::NOT_CONFIGURED_MSG.into());
}
w.view_only_wallet().await.map_err(|e| e.to_string())
}
/// Every wallet this install remembers, oldest first. A store read: it must
/// work with no wallet RPC configured, and it never dials.
pub fn list_wallets(&self) -> Result<Vec<WalletRecord>, String> {
@ -2426,6 +2554,12 @@ fn session_err(e: session::Error) -> String {
}
}
/// The one wording for "this install has no address to receive to". The wallet
/// screen's copy action and the receive-address accessors all say it, so a user
/// never has to work out whether two strings are the same problem.
pub const NO_RECEIVE_ADDRESS_MSG: &str =
"no receive address — set profile xmr or ONIONWIRE_WALLET_RPC";
pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool {
let mut stack = vec![dir.to_path_buf()];
while let Some(p) = stack.pop() {
@ -3628,6 +3762,33 @@ pub(crate) mod tests {
assert!(gone, "shutdown must not leave the wallet child behind");
}
/// [`mock_wallet_setup`] with its request log kept: for tests that assert on
/// *which* RPC method a path called, not only on the answer. `reply` runs
/// once per authenticated request, so the log holds one line per RPC call.
async fn recording_wallet_setup(log: Arc<std::sync::Mutex<Vec<String>>>) -> Wallet {
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(move |req: &str| {
log.lock().expect("log").push(req.to_string());
if req.contains("get_info") {
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"#
.to_string()
} else if req.contains("get_balance") {
r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"900000000000","unlocked_balance":"450000000000"}}"#
.to_string()
} else if req.contains("query_key") {
r#"{"jsonrpc":"2.0","id":"0","result":{"key":"lumber tacit lemon ivory risk"}}"#
.to_string()
} else {
r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#.to_string()
}
});
tokio::spawn(serve_mock_rpc(listener, reply));
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
}
/// A loopback wallet RPC for the setup path: a per-socket digest challenge,
/// then the method's own result. `create_wallet` and
/// `restore_deterministic_wallet` both answer `{}`; only the seed backup
@ -3712,7 +3873,7 @@ pub(crate) mod tests {
);
let imported = node
.wallet_restore("hunter2", "lumber tacit lemon ivory risk", None)
.wallet_restore("hunter2", "lumber tacit lemon ivory risk", None, None)
.await
.expect("restore wallet");
@ -3724,6 +3885,190 @@ pub(crate) mod tests {
);
}
/// A pasted-address send is a plain wallet `transfer`: the outgoing transfer
/// list is its record, so there is no friend, no `tip` frame and no chat
/// line to show for it.
#[tokio::test]
async fn wallet_send_transfers_without_a_tip_frame_or_a_chat_line() {
let dir = tempfile::tempdir().unwrap();
let log = Arc::new(std::sync::Mutex::new(Vec::new()));
let node = offline_node_with_wallet(
&dir.path().join("bob"),
Arc::new(DialOk),
recording_wallet_setup(Arc::clone(&log)).await,
);
let peer = Keys::generate();
{
let store = node.store.lock().unwrap();
befriend(&store, &peer.identity_pk, &peer.prekey_pk, "peer.onion");
}
let txid = node.wallet_send(&xmr_addr(), "0.5").await.expect("send");
assert_eq!(txid, "abc123");
let seen = log.lock().expect("log").clone();
assert!(
seen.iter().any(|r| r.contains(r#""method":"transfer""#)),
"a pasted-address send is the wallet's transfer: {seen:?}"
);
assert!(
!seen.iter().any(|r| r.contains(r#""method":"tip""#)),
"there is no tip frame on this path: {seen:?}"
);
assert!(
chat_lines(&node, &peer).is_empty(),
"a local send appends no chat line"
);
}
/// Every local refusal of `wallet_send` happens before a dial: the address
/// and the amount are argued with here, not by the RPC.
#[tokio::test]
async fn wallet_send_refuses_locally_without_dialing() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
let err = node.wallet_send("", "1").await.unwrap_err();
assert_eq!(err, "address required");
let err = node.wallet_send(" ", "1").await.unwrap_err();
assert_eq!(err, "address required");
let err = node.wallet_send(&xmr_addr(), "").await.unwrap_err();
assert_eq!(err, "amount required");
let err = node.wallet_send("not-an-address", "1").await.unwrap_err();
assert_eq!(err, "invalid Monero address");
let err = node
.wallet_send(&xmr_addr(), "not-a-number")
.await
.unwrap_err();
assert_eq!(err, "invalid XMR amount");
let err = node.wallet_send(&xmr_addr(), "0").await.unwrap_err();
assert_eq!(err, "amount must be > 0");
// Nothing above may reach the RPC; an unconfigured wallet is the last
// gate, and it is still local.
let err = node.wallet_send(&xmr_addr(), "1").await.unwrap_err();
assert_eq!(err, wallet::NOT_CONFIGURED_MSG);
}
/// `wallet_view_only` on an unconfigured wallet is the refusal the other
/// wallet calls give — *not* `true`, which would claim a wallet exists.
#[tokio::test]
async fn wallet_view_only_on_an_unconfigured_wallet_is_a_refusal() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
assert_eq!(
node.wallet_view_only().await.unwrap_err(),
wallet::NOT_CONFIGURED_MSG
);
}
/// The balance line carries both numbers out of one `get_balance` answer,
/// and the unlocked sentinels match the total's.
#[tokio::test]
async fn the_balance_line_shows_the_unlocked_part_from_one_answer() {
let dir = tempfile::tempdir().unwrap();
let log = Arc::new(std::sync::Mutex::new(Vec::new()));
let node = offline_node_with_wallet(
&dir.path().join("bob"),
Arc::new(NoDial),
recording_wallet_setup(Arc::clone(&log)).await,
);
assert_eq!(
node.wallet_balance_line().await,
"balance 0.9 XMR \u{b7} unlocked 0.45 XMR"
);
assert_eq!(node.wallet_unlocked_balance().await, "0.45");
let calls = log
.lock()
.expect("log")
.iter()
.filter(|r| r.contains(r#""method":"get_balance""#))
.count();
assert_eq!(
calls, 2,
"one dial per call and never two for one line: {calls}"
);
}
/// A stopped wallet still reads as `off`, not as an error or a zero.
#[tokio::test]
async fn unlocked_balance_on_an_unconfigured_wallet_is_off() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
assert_eq!(node.wallet_unlocked_balance().await, "off");
assert_eq!(node.wallet_balance_line().await, "wallet off");
}
/// The view-only import is a creation path: a catalogue row, the child
/// pointed at the new file, and the *file* passphrase sealed. The view key
/// itself is nowhere.
#[tokio::test]
async fn importing_a_view_only_wallet_records_it_and_seals_only_the_passphrase() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("bob");
let log = Arc::new(std::sync::Mutex::new(Vec::new()));
let node = offline_node_with_wallet(
&home,
Arc::new(NoDial),
recording_wallet_setup(Arc::clone(&log)).await,
);
let key = "0123456789abcdef".repeat(4);
let record = node
.wallet_import_view_only("hunter2", &xmr_addr(), &key, Some(3210000))
.await
.expect("view-only import");
assert_eq!(record.wallet_filename, "onionwire-1");
assert_eq!(
node.wallet_child_config().wallet_filename,
record.wallet_filename,
"the child has to open the file that was just written"
);
assert_eq!(sealed_passphrase(&node), "hunter2");
let seen = log.lock().expect("log").clone();
let req = seen
.iter()
.find(|r| r.contains(r#""method":"generate_from_keys""#))
.expect("generate_from_keys");
assert!(
req.contains(&key),
"the view key is what makes it watch: {req}"
);
assert!(!req.contains("spendkey"), "no spend key may be sent: {req}");
// The catalogue keeps no copy of the view key, and neither does the
// sealed child record.
assert_eq!(
node.list_wallets().expect("list wallets").len(),
1,
"a view-only import is remembered like any other wallet"
);
}
/// A view key of the wrong shape never reaches the RPC. The wallet here is
/// "configured" against a dead loopback port, so a refusal that came from a
/// dial could not read like this one.
#[tokio::test]
async fn importing_a_view_only_wallet_refuses_a_bad_key_locally() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node_with_wallet(
&dir.path().join("bob"),
Arc::new(NoDial),
Wallet::from_url("http://ow:[email protected]:1").expect("wallet url"),
);
for bad in ["", "not-hex", &"a".repeat(63)] {
let err = node
.wallet_import_view_only("pw", &xmr_addr(), bad, None)
.await
.unwrap_err();
assert_eq!(err, "view key must be 64 hex characters");
}
assert!(
node.list_wallets().expect("list wallets").is_empty(),
"a refused import must not create a catalogue row"
);
}
/// A catalogue row the child never opens is still a broken wallet: the
/// child's stored config defaults to `onionwire`, which no created wallet
/// uses any more.

File diff suppressed because it is too large Load diff

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> {

View file

@ -23,9 +23,15 @@ fn row(txid: &str, amount: &str, address: &str) -> TransferRow {
txid: txid.into(),
amount: amount.into(),
address: address.into(),
direction: "in".into(),
}
}
/// A 64-hex view key, the only shape `generate_from_keys` takes.
fn view_key() -> String {
"0123456789abcdef".repeat(4)
}
fn xmr_addr() -> String {
// Same documented mainnet standard as tests/pay.rs — F4 checksums this.
"4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge"
@ -640,6 +646,7 @@ async fn restore_wallet_sends_seed_to_restore_deterministic_wallet() {
"hunter2",
"lumber tacit lemon ivory risk",
None,
None,
)
.await
.expect("restore_wallet");
@ -680,6 +687,7 @@ async fn restore_wallet_sends_a_non_empty_seed_offset() {
"hunter2",
"lumber tacit lemon ivory risk",
Some("harbor-offset"),
None,
)
.await
.expect("restore_wallet");
@ -721,6 +729,7 @@ async fn restore_wallet_omits_a_whitespace_only_seed_offset() {
"hunter2",
"lumber tacit lemon ivory risk",
Some(" "),
None,
)
.await
.expect("blank offset restore");
@ -755,6 +764,7 @@ async fn restore_wallet_trims_the_ends_of_a_seed_offset() {
"hunter2",
"lumber tacit lemon ivory risk",
Some(" harbor offset "),
None,
)
.await
.expect("trimmed offset restore");
@ -782,6 +792,7 @@ async fn a_failed_restore_does_not_echo_the_seed_offset() {
"hunter2",
"lumber tacit lemon ivory risk",
Some("harbor-offset"),
None,
)
.await
.unwrap_err()
@ -803,7 +814,7 @@ fn restore_wallet_empty_seed_is_local_error() {
.enable_all()
.build()
.unwrap()
.block_on(w.restore_wallet("onionwire", "pw", " ", None))
.block_on(w.restore_wallet("onionwire", "pw", " ", None, None))
.unwrap_err()
.to_string();
assert!(err.to_ascii_lowercase().contains("seed"), "got {err}");
@ -2040,3 +2051,269 @@ fn wallet_name_taken_fails_closed_when_the_dir_cannot_be_read() {
std::fs::write(&file, b"x").unwrap();
assert!(wallet_child::wallet_name_taken(&file, "onionwire-1").is_err());
}
// ---------------------------------------------------------------------------
// The next wallet batch, still at the request-byte level: there is no live
// `monero-wallet-rpc` on this host. Unlocked balance, restore height, outgoing
// rows and the view-only import all have to be pinned by the bytes they send.
// ---------------------------------------------------------------------------
/// `restore_height` is `restore_deterministic_wallet`'s own optional block
/// number: a JSON number when the user typed one, and no field at all when they
/// did not (never `0`, which would hide older funds).
#[tokio::test]
async fn restore_wallet_sends_a_restore_height_as_a_number() {
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(|method| match method {
"restore_deterministic_wallet" => rpc_result(r#"{"address":"4","seed":""}"#),
_ => rpc_error(-1, "unexpected method"),
}),
));
recording_wallet(port)
.restore_wallet(
"onionwire-1",
"hunter2",
"lumber tacit lemon ivory risk",
None,
Some(3210000),
)
.await
.expect("restore_wallet");
let seen = log.lock().expect("log").clone();
let restore = seen
.iter()
.find(|r| r.contains(r#""method":"restore_deterministic_wallet""#))
.expect("restore RPC");
assert!(
restore.contains(r#""restore_height":3210000"#),
"the height must be a JSON number: {restore}"
);
assert!(
!restore.contains(r#""restore_height":"3210000""#),
"a quoted height is a string, not a block number: {restore}"
);
}
/// The default import sends no height at all. The seed offset still travels, so
/// the omission is the height's and not a lost field.
#[tokio::test]
async fn restore_wallet_omits_an_absent_restore_height() {
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(|method| match method {
"restore_deterministic_wallet" => rpc_result(r#"{"address":"4","seed":""}"#),
_ => rpc_error(-1, "unexpected method"),
}),
));
recording_wallet(port)
.restore_wallet(
"onionwire-1",
"hunter2",
"lumber tacit lemon ivory risk",
Some("harbor-offset"),
None,
)
.await
.expect("restore_wallet");
let seen = log.lock().expect("log").clone();
let restore = seen
.iter()
.find(|r| r.contains(r#""method":"restore_deterministic_wallet""#))
.expect("restore RPC");
assert!(
!restore.contains("restore_height"),
"an absent height must not become a field: {restore}"
);
assert!(
restore.contains(r#""seed_offset":"harbor-offset""#),
"the offset is beside the height and must still be there: {restore}"
);
}
/// The wallet screen shows outgoing transfers too, so the request has to ask for
/// them and each row has to say which bucket it came from.
#[tokio::test]
async fn get_transfers_asks_for_outgoing_rows_and_labels_every_bucket() {
let addr = "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
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()));
let body = format!(
r#"{{"in":[{{"txid":"aa","amount":1,"address":"{addr}"}}],"out":[{{"txid":"bb","amount":2,"address":"{addr}"}}],"pending":[{{"txid":"cc","amount":3,"address":"{addr}","type":"out"}}]}}"#
);
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = {
let body = body.clone();
Arc::new(move |method| match method {
"get_transfers" => rpc_result(&body),
_ => rpc_error(-1, "unexpected method"),
})
};
tokio::spawn(serve_recording(listener, Arc::clone(&log), reply));
let rows = recording_wallet(port)
.get_transfers()
.await
.expect("get_transfers");
let seen = log.lock().expect("log").clone();
let req = seen
.iter()
.find(|r| r.contains(r#""method":"get_transfers""#))
.expect("get_transfers RPC");
assert!(
req.contains(r#""out":true"#) || req.contains(r#""out": true"#),
"the request must ask for outgoing transfers: {req}"
);
let direction = |txid: &str| {
rows.iter()
.find(|r| r.txid == txid)
.map(|r| r.direction.clone())
};
assert_eq!(direction("aa").as_deref(), Some("in"));
assert_eq!(direction("bb").as_deref(), Some("out"));
assert_eq!(
direction("cc").as_deref(),
Some("out"),
"a pending item's own `type` is its direction"
);
}
/// Both numbers the wallet screen prints come out of one `get_balance` answer.
#[tokio::test]
async fn balances_reads_the_total_and_the_unlocked_from_one_call() {
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(|method| match method {
"get_balance" => {
rpc_result(r#"{"balance":"900000000000","unlocked_balance":"450000000000"}"#)
}
_ => rpc_error(-1, "unexpected method"),
}),
));
let (total, unlocked) = recording_wallet(port).balances().await.expect("balances");
assert_eq!(total, "900000000000");
assert_eq!(unlocked, Some(450_000_000_000));
// The recorder sees the unauthenticated request that earns the 401 too, so
// count the answered ones: exactly one `get_balance` may reach the RPC.
let calls = log
.lock()
.expect("log")
.iter()
.filter(|r| r.contains(r#""method":"get_balance""#) && r.contains("Authorization:"))
.count();
assert_eq!(calls, 1, "one response carries both fields");
}
/// The view-only import is `generate_from_keys` with a view key and **no** spend
/// key: a body that carried `spendkey` would import a spend authority.
#[tokio::test]
async fn import_view_only_sends_the_view_key_and_no_spend_key() {
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(|method| match method {
"generate_from_keys" => rpc_result(r#"{}"#),
_ => rpc_error(-1, "unexpected method"),
}),
));
let key = view_key();
recording_wallet(port)
.import_view_only("onionwire-1", "hunter2", &xmr_addr(), &key, Some(100))
.await
.expect("import_view_only");
let seen = log.lock().expect("log").clone();
let req = seen
.iter()
.find(|r| r.contains(r#""method":"generate_from_keys""#))
.expect("generate_from_keys RPC");
assert!(req.contains(&key), "view key missing: {req}");
assert!(req.contains(&xmr_addr()), "address missing: {req}");
assert!(
!req.contains("spendkey"),
"a view-only import must omit the spend key entirely: {req}"
);
assert!(
req.contains(r#""restore_height":100"#),
"the height is optional but not dropped when given: {req}"
);
}
/// A view key has exactly one shape and it is not a secret to be echoed back:
/// refusing locally also means no socket is opened.
#[tokio::test]
async fn import_view_only_refuses_a_bad_view_key_without_dialing() {
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_error(-1, "unexpected method")),
));
let w = recording_wallet(port);
for bad in ["", " ", "not-hex", &"a".repeat(63), &"a".repeat(65)] {
let err = w
.import_view_only("onionwire-1", "hunter2", &xmr_addr(), bad, None)
.await
.unwrap_err()
.to_string();
assert_eq!(
err,
"view key must be 64 hex characters",
"a {}-char view key must be refused locally",
bad.len()
);
assert!(
!err.contains(bad) || bad.trim().is_empty(),
"the typed key must never be echoed: {err}"
);
}
assert!(
log.lock().expect("log").is_empty(),
"a local refusal must not dial"
);
}
/// The address is checked before the dial, like every other wallet path.
#[tokio::test]
async fn import_view_only_refuses_a_bad_address_without_dialing() {
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_error(-1, "unexpected method")),
));
let err = recording_wallet(port)
.import_view_only(
"onionwire-1",
"hunter2",
"not-an-address",
&view_key(),
None,
)
.await
.unwrap_err()
.to_string();
assert_eq!(err, "invalid Monero address");
assert!(
log.lock().expect("log").is_empty(),
"a local refusal must not dial"
);
}