onionwire/tests/wallet.rs
hermes-rust-dev e6b5024ad3
Some checks failed
ci / test (pull_request) Failing after 1m30s
ci / sdk (pull_request) Successful in 1m16s
wallet: typed chain-daemon client for the Cuprate parity gaps
The chain probe was a hand-rolled brace-scanner in `src/node.rs`. Cuprate
breaks three of its assumptions, all measured in Spike A
(`docs/cuprate-launch-spike.md` §Parity gaps, evidence in that spike's
`rpc-evidence/`):

1. **A height above the tip is a bare HTTP 500 with an empty body.** monerod
   answers a JSON-RPC error object instead (`TOO_BIG_HEIGHT`, code -2). The
   client now parses the HTTP status once, de-chunks `Transfer-Encoding:
   chunked` bodies (axum/hyper; the old brace-scan is not a parse once a blob
   spans more than one chunk), and maps both spellings of the height failure to
   one typed `WalletError::DaemonHeightOutOfRange`. `get_height` and `get_block`
   are height-addressed: their 5xx is the height error. `get_info` is not: its
   5xx is `WalletError::DaemonHttpStatus`.

2. **`get_info` metrics are not measurements.** Cuprate reports zero peers while
   it downloads blocks, its restricted server answers a placeholder
   `database_size` (exactly 5 GiB) and an empty `version`, and `free_space` is
   `u64::MAX` on both servers. `DaemonInfo` carries height and target only, so
   there is no field for a placeholder to reach the UI. The wallet screen's sync
   line is now built from block-height movement between two probes: "connected
   to P2P" needs the height to have moved, "no new blocks" is what a stalled
   daemon gets, and Cuprate's at-rest `synchronized = true` with
   `target_height = 0` reads as unknown instead of `1160/0`.

3. **`get_height` is a URI endpoint**: `{"method":"get_height"}` over
   `/json_rpc` is rejected with 422, so the client uses `GET /get_height`, which
   both daemons answer. The wallet-child routing rule is pinned too: it dials
   the daemon's *unrestricted* listener (monerod's `--rpc-bind-port`, and
   whatever port an in-process Cuprate binds for `[rpc.unrestricted]`), never the
   restricted one — a restricted listener answers, so a mix-up shows up as a
   wrong number rather than as an error.

Scope deviations, stated plainly:

- the card names `src/wallet.rs` + the TUI bindings. The probe itself lived in
  `src/node.rs`; it now delegates (net -100 lines there), and the routing
  constant/test live in `src/wallet_child.rs`. Tests are in `tests/wallet.rs`,
  `tests/tui_spec.rs` and `src/wallet_child.rs`'s test module.
- `daemon_get_block()` is **not called by anything yet**: it is the entry point
  the wallet's own block scan (Phase 2) needs, and the out-of-range answer it has
  to survive is item 1, so the mapping lives with the client.
- the card's item 3 gives the unrestricted port as 18089 and the restricted one
  as 28089. In monerod's numbering 18089 *is* the restricted port; the app's
  local source already dials the unrestricted 18081. The rule is what is pinned,
  not those numbers.
- `docs/cuprate-launch-spike.md` merged to `main` after this branch's base
  commit, so it is not in this tree and its Recommendation bullets are not
  updated here.
- based on `feat/wallet-create-import` (the wallet line, unmerged): the daemon
  client has no home on `main`. Retarget to `main` when that line lands.

Proof: `cargo test --locked` 306 passed / 0 failed, `cargo clippy --locked
--all-targets -- -D warnings` clean, `rustfmt --edition 2024 --check` adds no
hunk to any file (the inherited hunks in `src/node.rs`/`src/tui.rs`/
`tests/tui_spec.rs` are unchanged in count or region).
2026-09-17 00:30:31 -04:00

1362 lines
53 KiB
Rust

//! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod.
use std::sync::{Arc, Mutex};
use std::time::Duration;
use ed25519_dalek::SigningKey;
use onionwire::pay;
use onionwire::wallet::{
self, DaemonInfo, NOT_CONFIGURED_MSG, NOT_CONNECTED_MSG, Readiness, TransferRow, VIEW_ONLY_MSG,
Wallet, WalletConfig, WalletError, WalletStatus, readiness,
};
use onionwire::{PaymentWrite, Store};
use rand::rngs::OsRng;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
/// `ONIONWIRE_WALLET_NO_SPEND` is process-wide; tests that touch env serialize.
static ENV_LOCK: Mutex<()> = Mutex::new(());
fn row(txid: &str, amount: &str, address: &str) -> TransferRow {
TransferRow {
txid: txid.into(),
amount: amount.into(),
address: address.into(),
}
}
fn xmr_addr() -> String {
// Same documented mainnet standard as tests/pay.rs — F4 checksums this.
"4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge"
.to_string()
}
fn json_rpc_ok(result: &str) -> String {
let body = format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#);
format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
}
#[test]
fn disabled_create_address_is_not_configured() {
let w = Wallet::disabled();
let err = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(w.create_address())
.unwrap_err();
assert!(err.to_string().contains("not configured"), "got {err}");
}
#[test]
fn refuse_url_without_credentials() {
let err = Wallet::from_url("http://127.0.0.1:18083").unwrap_err();
let msg = err.to_string().to_ascii_lowercase();
assert!(
msg.contains("credential") || msg.contains("login") || msg.contains("user"),
"got {err}"
);
}
#[test]
fn refuse_non_loopback_non_onion_host() {
let err = Wallet::from_url("http://ow:[email protected]:18083").unwrap_err();
assert!(
err.to_string().to_ascii_lowercase().contains("host")
|| err.to_string().contains("loopback")
|| err.to_string().contains("onion"),
"got {err}"
);
}
#[test]
fn refuse_onion_rpc_url() {
let err = Wallet::from_url(
"http://ow:s3cretPASS@abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwxyz.onion:18083",
)
.unwrap_err();
let msg = err.to_string();
assert!(msg.to_ascii_lowercase().contains("onion"), "got {err}");
assert!(
!msg.contains("s3cretPASS"),
"password leaked in error: {err}"
);
}
#[test]
fn password_absent_from_url_errors() {
let err = Wallet::from_url("http://ow:[email protected]:18083").unwrap_err();
assert!(
!err.to_string().contains("s3cretPASS"),
"password leaked in error: {err}"
);
let err = Wallet::from_url("http://ow:s3cretPASS@").unwrap_err();
assert!(
!err.to_string().contains("s3cretPASS"),
"password leaked in error: {err}"
);
}
#[tokio::test]
async fn mock_get_address_parses_string() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let canned = json_rpc_ok(
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
);
tokio::spawn(serve_digest_then(listener, canned));
let w = Wallet::from_url(&format!("http://ow:[email protected]:{}", addr.port())).unwrap();
let got = w.get_address().await.expect("get_address");
assert!(got.starts_with('4'), "got {got}");
}
#[tokio::test]
async fn mock_create_address_and_transfer() {
let addr_hex = "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(serve_recording(
listener,
Arc::new(Mutex::new(Vec::new())),
Arc::new(move |method| match method {
// A spend is only attempted on a synced wallet.
"get_info" => synced_info(),
_ => rpc_result(&format!(r#"{{"address":"{addr_hex}","tx_hash":"abc123"}}"#)),
}),
));
let w = recording_wallet(port);
let created = w.create_address().await.expect("create_address");
assert!(created.starts_with('8'));
let txid = w.transfer(addr_hex, 1).await.expect("transfer");
assert_eq!(txid, "abc123");
}
#[tokio::test]
async fn mock_get_transfers_matches_txid() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let canned = json_rpc_ok(
r#"{"in":[{"txid":"deadbeef","amount":5,"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}],"pending":[]}"#,
);
tokio::spawn(serve_digest_then(listener, canned));
let w = Wallet::from_url(&format!("http://ow:[email protected]:{}", addr.port())).unwrap();
let rows = w.get_transfers().await.expect("get_transfers");
assert!(wallet::transfers_match(
&rows,
"deadbeef",
"5",
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
));
assert!(!wallet::transfers_match(&rows, "nope", "1", "nope"));
}
#[test]
fn transfers_match_txid_only_wrong_amount_or_addr_is_false() {
let addr = xmr_addr();
let rows = [row("deadbeef", "5", &addr)];
assert!(!wallet::transfers_match(&rows, "deadbeef", "99", &addr));
let other = format!("8{}", "C".repeat(94));
assert!(!wallet::transfers_match(&rows, "deadbeef", "5", &other));
}
#[test]
fn transfers_match_address_and_amount_wrong_txid_is_false() {
let addr = xmr_addr();
let rows = [row("deadbeef", "5", &addr)];
assert!(!wallet::transfers_match(&rows, "cafebabe", "5", &addr));
}
#[test]
fn transfers_match_honest_triple_is_true() {
let addr = xmr_addr();
let rows = [row("deadbeef", "5", &addr)];
assert!(wallet::transfers_match(&rows, "deadbeef", "5", &addr));
}
#[test]
fn transfers_match_empty_field_is_false() {
let addr = xmr_addr();
let rows = [row("deadbeef", "5", &addr)];
assert!(!wallet::transfers_match(&rows, "", "5", &addr));
assert!(!wallet::transfers_match(&rows, "deadbeef", "", &addr));
assert!(!wallet::transfers_match(&rows, "deadbeef", "5", ""));
let empty = [row("", "", "")];
assert!(!wallet::transfers_match(&empty, "", "", ""));
}
/// ingest_receipt inserts verified=0, then mark_verified iff transfers_match.
/// A Noise-signed rcp that cites an unrelated wallet row must stay unverified.
#[test]
fn ingest_signed_receipt_mismatched_wallet_history_stays_unverified() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "onionwire-test").expect("open");
let sk = SigningKey::generate(&mut OsRng);
let pk = sk.verifying_key().to_bytes();
store.upsert_friend(&pk, "peer.onion", None).unwrap();
let addr = xmr_addr();
let rcp = pay::sign_receipt(&sk.to_bytes(), "unrelated", "5", &addr, 1).unwrap();
assert!(pay::verify_receipt(&pk, &rcp));
let id = store
.insert_payment(
&pk,
PaymentWrite {
dir: "in",
kind: "receipt",
amount_atomic: &rcp.amount_atomic,
address: &rcp.address,
memo: "",
txid: Some(&rcp.txid),
verified: false,
},
)
.unwrap();
let history = [row("unrelated", "99", &format!("8{}", "C".repeat(94)))];
if wallet::transfers_match(&history, &rcp.txid, &rcp.amount_atomic, &rcp.address) {
store.mark_verified(id).unwrap();
}
let rows = store.list_payments(&pk).unwrap();
assert!(!rows[0].verified);
}
#[tokio::test]
async fn oversized_rpc_response_is_err() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let huge = vec![b'A'; 2 * 1024 * 1024];
tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.expect("accept");
let mut buf = vec![0u8; 4096];
let _ = sock.read(&mut buf).await;
sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n")
.await
.expect("hdr");
sock.write_all(&huge).await.expect("body");
});
let w = Wallet::from_url(&format!("http://ow:[email protected]:{}", addr.port())).unwrap();
let err = w.get_address().await.unwrap_err();
let msg = err.to_string().to_ascii_lowercase();
assert!(
msg.contains("large") || msg.contains("size") || msg.contains("cap"),
"got {err}"
);
assert!(
!err.to_string().contains("secret"),
"password leaked: {err}"
);
}
/// Records every request the client sends, answers the Digest challenge and
/// then replies per RPC method. Lets a test assert on the *request log*.
async fn serve_recording(
listener: TcpListener,
log: Arc<Mutex<Vec<String>>>,
reply: Arc<dyn Fn(&str) -> String + Send + Sync>,
) {
loop {
let Ok((mut sock, _)) = listener.accept().await else {
return;
};
let mut buf = vec![0u8; 8192];
let n = sock.read(&mut buf).await.unwrap_or(0);
let req = String::from_utf8_lossy(&buf[..n]).to_string();
log.lock().expect("log").push(req.clone());
if req.contains("Authorization:") {
let body = reply(&rpc_method(&req));
let _ = sock.write_all(http_200_body(&body).as_bytes()).await;
} else {
let _ = sock.write_all(digest_401().as_bytes()).await;
}
}
}
fn rpc_method(req: &str) -> String {
let body = req.split_once("\r\n\r\n").map(|(_, b)| b).unwrap_or(req);
serde_json::from_str::<serde_json::Value>(body.trim())
.ok()
.and_then(|v| v.get("method").and_then(|m| m.as_str()).map(str::to_string))
.unwrap_or_default()
}
fn http_200_body(body: &str) -> String {
format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
}
fn rpc_error(code: i64, message: &str) -> String {
format!(r#"{{"jsonrpc":"2.0","id":"0","error":{{"code":{code},"message":"{message}"}}}}"#)
}
/// JSON-RPC body only (the server wraps it in an HTTP 200).
fn rpc_result(result: &str) -> String {
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#)
}
/// What a fully synced wallet answers to `get_info`: the daemon has reached the
/// tip and the wallet has scanned it. This is the honest readiness signal.
fn synced_info() -> String {
rpc_result(r#"{"height":3210000,"target_height":3210000,"synchronized":true}"#)
}
fn recording_wallet(port: u16) -> Wallet {
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("url")
}
/// The wallet mock speaks the two methods `/tip` can reach, and refuses the
/// local `transfer` before any socket is opened.
#[tokio::test]
async fn no_spend_mode_refuses_transfer_with_no_rpc_request() {
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(|_| rpc_result(r#"{"tx_hash":"abc123"}"#)),
));
let w = recording_wallet(port).with_no_spend(true);
assert!(w.no_spend());
let err = w
.transfer(
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
1,
)
.await
.unwrap_err()
.to_string();
assert!(err.to_ascii_lowercase().contains("view-only"), "got {err}");
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
let seen = log.lock().expect("log").clone();
assert!(seen.is_empty(), "no RPC request may be made: {seen:?}");
// Positive control: the recorder is live, so the emptiness above is real.
let _ = w.get_address().await;
assert!(!log.lock().expect("log").is_empty(), "recorder saw nothing");
}
/// `/pay` (subaddress) and receipt verification (`get_transfers`) keep working
/// with the no-spend flag on — only `transfer` is refused.
#[tokio::test]
async fn no_spend_mode_keeps_invoice_and_receipt_paths_working() {
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 {
"create_address" => rpc_result(
r#"{"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}"#,
),
"get_transfers" => rpc_result(
r#"{"in":[{"txid":"deadbeef","amount":5,"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}],"pending":[]}"#,
),
_ => rpc_result(r#"{}"#),
}),
));
let w = recording_wallet(port).with_no_spend(true);
let created = w.create_address().await.expect("create_address");
assert!(created.starts_with('8'), "got {created}");
let rows = w.get_transfers().await.expect("get_transfers");
assert!(wallet::transfers_match(&rows, "deadbeef", "5", &created));
let seen = log.lock().expect("log").clone();
assert!(
seen.iter()
.any(|r| r.contains("\"method\":\"create_address\"")),
"recorder must have seen the invoice path: {seen:?}"
);
assert!(
!seen.iter().any(|r| r.contains("\"method\":\"transfer\"")),
"transfer must never be dialed in no-spend mode"
);
}
/// A view-only wallet refuses `transfer` with its own opaque error. The
/// pre-transfer signal is `query_key` key_type=spend_key (Monero answers
/// WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29), so /tip must say so plainly.
#[tokio::test]
async fn view_only_wallet_maps_transfer_failure_to_clear_message() {
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 {
"query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."),
"get_info" => synced_info(),
_ => rpc_error(-18, "No transaction created"),
}),
));
let w = recording_wallet(port);
assert!(!w.no_spend());
let err = w
.transfer(
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
1,
)
.await
.unwrap_err()
.to_string();
assert!(err.to_ascii_lowercase().contains("view-only"), "got {err}");
let seen = log.lock().expect("log").clone();
assert!(
seen.iter().any(|r| r.contains("\"method\":\"query_key\"")),
"must ask the RPC-side signal: {seen:?}"
);
}
/// A spend-capable wallet must keep its real error: no fabricated detection.
#[tokio::test]
async fn spend_capable_wallet_keeps_the_original_transfer_error() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(serve_recording(
listener,
Arc::new(Mutex::new(Vec::new())),
Arc::new(|method| match method {
"query_key" => rpc_result(r#"{"key":"00112233"}"#),
"get_info" => synced_info(),
_ => rpc_error(-18, "No transaction created"),
}),
));
let err = recording_wallet(port)
.transfer(
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
1,
)
.await
.unwrap_err()
.to_string();
assert!(err.contains("No transaction created"), "got {err}");
assert!(!err.to_ascii_lowercase().contains("view-only"), "got {err}");
}
/// Create generates a spend-capable wallet on the RPC; the user never pastes a key.
/// Seed is read back once via `query_key mnemonic` for the backup screen.
#[tokio::test]
async fn create_wallet_does_not_send_a_seed_and_returns_mnemonic() {
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 {
"create_wallet" => rpc_result(r#"{}"#),
"query_key" => rpc_result(r#"{"key":"lumber tacit lemon ivory risk"}"#),
_ => rpc_error(-1, "unexpected method"),
}),
));
let seed = recording_wallet(port)
.create_wallet("onionwire", "hunter2")
.await
.expect("create_wallet");
assert_eq!(seed, "lumber tacit lemon ivory risk");
let seen = log.lock().expect("log").clone();
let create = seen
.iter()
.find(|r| r.contains(r#""method":"create_wallet""#))
.expect("create_wallet RPC");
assert!(
!create.contains("lumber") && !create.contains("seed"),
"create must not take a seed: {create}"
);
assert!(
create.contains(r#""filename":"onionwire""#),
"filename missing: {create}"
);
assert!(
seen.iter()
.any(|r| r.contains(r#""method":"query_key""#) && r.contains("mnemonic")),
"must read mnemonic after create: {seen:?}"
);
}
#[test]
fn create_wallet_empty_filename_or_password_is_local_error() {
let w = Wallet::from_url("http://ow:[email protected]:18083").unwrap();
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let err = rt
.block_on(w.create_wallet("", "pw"))
.unwrap_err()
.to_string();
assert!(err.contains("filename"), "got {err}");
let err = rt
.block_on(w.create_wallet("onionwire", ""))
.unwrap_err()
.to_string();
assert!(
err.to_ascii_lowercase().contains("password")
|| err.to_ascii_lowercase().contains("passphrase"),
"got {err}"
);
}
/// Import is the only path that takes an existing secret (the 25-word seed).
#[tokio::test]
async fn restore_wallet_sends_seed_to_restore_deterministic_wallet() {
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":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","seed":"lumber tacit lemon ivory risk"}"#,
),
_ => rpc_error(-1, "unexpected method"),
}),
));
recording_wallet(port)
.restore_wallet("onionwire", "hunter2", "lumber tacit lemon ivory risk")
.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("lumber tacit lemon ivory risk"),
"seed missing: {restore}"
);
}
#[test]
fn restore_wallet_empty_seed_is_local_error() {
let w = Wallet::from_url("http://ow:[email protected]:18083").unwrap();
let err = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(w.restore_wallet("onionwire", "pw", " "))
.unwrap_err()
.to_string();
assert!(err.to_ascii_lowercase().contains("seed"), "got {err}");
}
/// F5 must not regress: an open RPC (HTTP 200, no Digest challenge) is refused.
#[tokio::test]
async fn open_rpc_without_digest_challenge_is_still_refused() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let canned = http_200_body(
r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}}"#,
);
tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.expect("accept");
let mut buf = vec![0u8; 4096];
let _ = sock.read(&mut buf).await;
let _ = sock.write_all(canned.as_bytes()).await;
});
let err = recording_wallet(port)
.get_address()
.await
.unwrap_err()
.to_string();
assert!(err.to_ascii_lowercase().contains("digest"), "got {err}");
}
/// `ONIONWIRE_WALLET_NO_SPEND` is the operator-facing switch.
#[test]
fn from_env_reads_no_spend_flag() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
unsafe {
std::env::set_var("ONIONWIRE_WALLET_RPC", "http://ow:[email protected]:18083");
std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "1");
}
let on = Wallet::from_env();
assert!(on.no_spend(), "flag 1 must mean no-spend");
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "true") };
assert!(Wallet::from_env().no_spend(), "\"true\" must mean no-spend");
for off in ["0", "no", "off"] {
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", off) };
assert!(!Wallet::from_env().no_spend(), "{off} must be off");
}
unsafe {
std::env::remove_var("ONIONWIRE_WALLET_NO_SPEND");
std::env::remove_var("ONIONWIRE_WALLET_RPC");
}
assert!(!Wallet::from_env().no_spend(), "unset must be off");
}
fn digest_401() -> String {
"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into()
}
async fn serve_digest_then(listener: TcpListener, ok: String) {
let (mut sock, _) = listener.accept().await.expect("accept");
let mut buf = vec![0u8; 8192];
let _ = sock.read(&mut buf).await;
sock.write_all(digest_401().as_bytes()).await.expect("401");
drop(sock);
let (mut sock, _) = listener.accept().await.expect("accept2");
buf.fill(0);
let n = sock.read(&mut buf).await.unwrap_or(0);
let req = String::from_utf8_lossy(&buf[..n]);
assert!(
req.contains("Authorization: Digest"),
"missing digest auth: {req}"
);
assert!(req.contains("username=\"ow\""), "missing user: {req}");
assert!(req.contains("response=\""), "missing response: {req}");
sock.write_all(ok.as_bytes()).await.expect("200");
}
#[tokio::test]
async fn mock_digest_auth_accepted() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let canned = json_rpc_ok(
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
);
tokio::spawn(serve_digest_then(listener, canned));
let w = Wallet::from_url(&format!("http://ow:[email protected]:{}", addr.port())).unwrap();
let got = w.get_address().await.expect("get_address");
assert!(got.starts_with('4'), "got {got}");
}
/// Answers the Digest challenge, then holds the reply for `delay`. Lets a test
/// prove which call classes get which budget.
async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) {
while let Ok((mut sock, _)) = listener.accept().await {
let mut buf = vec![0u8; 8192];
let n = sock.read(&mut buf).await.unwrap_or(0);
let req = String::from_utf8_lossy(&buf[..n]).to_string();
if !req.contains("Authorization:") {
let _ = sock.write_all(digest_401().as_bytes()).await;
continue;
}
tokio::time::sleep(delay).await;
let body = match rpc_method(&req).as_str() {
"get_info" => synced_info(),
_ => rpc_result(
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
),
};
let _ = sock.write_all(http_200_body(&body).as_bytes()).await;
}
}
const SPEND_ADDR: &str = "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
/// Readiness is a real predicate, not "sync made some progress": a wallet whose
/// daemon has not reached the tip is not ready, refuses to spend, and does not
/// even ask the RPC for a transfer.
#[tokio::test]
async fn unsynced_wallet_is_not_ready_and_refuses_to_spend() {
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_info" => {
rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#)
}
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
}),
));
let w = recording_wallet(port);
assert!(
!w.chain_ready().await.expect("get_info"),
"must not be ready"
);
assert!(
!w.can_verify_receipts().await,
"an unsynced wallet cannot verify receipts"
);
let err = w.transfer(SPEND_ADDR, 1).await.unwrap_err().to_string();
assert!(err.to_ascii_lowercase().contains("not synced"), "got {err}");
let seen = log.lock().expect("log").clone();
assert!(
!seen.iter().any(|r| r.contains("\"method\":\"transfer\"")),
"a not-ready wallet must not attempt a spend: {seen:?}"
);
}
/// A missing/absent `synchronized` (or a wallet behind the daemon) is not-ready,
/// never a silent pass. Fail closed.
#[tokio::test]
async fn missing_or_behind_synchronized_is_not_ready() {
for info in [
r#"{"height":10}"#,
r#"{"height":100,"target_height":200,"synchronized":true}"#,
r#"{"height":0,"target_height":0,"synchronized":true}"#,
r#"{"synchronized":"true"}"#,
] {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let canned = rpc_result(info);
tokio::spawn(serve_recording(
listener,
Arc::new(Mutex::new(Vec::new())),
Arc::new(move |_| canned.clone()),
));
let w = recording_wallet(port);
assert!(
!w.chain_ready().await.expect("get_info"),
"{info} must not read as ready"
);
}
}
#[tokio::test]
async fn synced_wallet_is_ready_and_spends() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(serve_recording(
listener,
Arc::new(Mutex::new(Vec::new())),
Arc::new(|method| match method {
"get_info" => synced_info(),
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
}),
));
let w = recording_wallet(port);
assert!(w.chain_ready().await.expect("get_info"));
assert!(w.can_verify_receipts().await);
assert_eq!(w.transfer(SPEND_ADDR, 1).await.expect("transfer"), "abc123");
}
/// `spend_ready` is the stricter signal for the spend UI: synced *and* holding
/// unlocked funds. Zero unlocked balance is not spend-ready.
#[tokio::test]
async fn spend_ready_needs_an_unlocked_balance() {
for (unlocked, ready) in [("0", false), ("5", true)] {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let balance = rpc_result(&format!(
r#"{{"balance":"{unlocked}","unlocked_balance":"{unlocked}"}}"#
));
tokio::spawn(serve_recording(
listener,
Arc::new(Mutex::new(Vec::new())),
Arc::new(move |method| match method {
"get_info" => synced_info(),
"get_balance" => balance.clone(),
_ => rpc_result(r#"{}"#),
}),
));
let w = recording_wallet(port);
assert_eq!(w.spend_ready().await.expect("spend_ready"), ready);
}
}
/// The honest not-ready state: a receipt whose history *would* match stays
/// verified=0 while the wallet is unsynced. (node.rs gates on the same
/// predicate via `can_verify_receipts`.)
#[tokio::test]
async fn unsynced_wallet_leaves_a_matching_receipt_unverified() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "onionwire-test").expect("open");
let sk = SigningKey::generate(&mut OsRng);
let pk = sk.verifying_key().to_bytes();
store.upsert_friend(&pk, "peer.onion", None).unwrap();
let addr = xmr_addr();
let rcp = pay::sign_receipt(&sk.to_bytes(), "deadbeef", "5", &addr, 1).unwrap();
let id = store
.insert_payment(
&pk,
PaymentWrite {
dir: "in",
kind: "receipt",
amount_atomic: &rcp.amount_atomic,
address: &rcp.address,
memo: "",
txid: Some(&rcp.txid),
verified: false,
},
)
.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let addr_owned = addr.clone();
tokio::spawn(serve_recording(
listener,
Arc::new(Mutex::new(Vec::new())),
Arc::new(move |method| match method {
"get_info" => {
rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#)
}
"get_transfers" => rpc_result(&format!(
r#"{{"in":[{{"txid":"deadbeef","amount":5,"address":"{addr_owned}"}}],"pending":[]}}"#
)),
_ => rpc_result(r#"{}"#),
}),
));
let w = recording_wallet(port);
// The same shape node.rs::ingest_receipt runs.
if w.can_verify_receipts().await
&& let Ok(rows) = w.get_transfers().await
&& wallet::transfers_match(&rows, &rcp.txid, &rcp.amount_atomic, &rcp.address)
{
store.mark_verified(id).unwrap();
}
assert!(
!store.list_payments(&pk).unwrap()[0].verified,
"an unsynced wallet must leave the receipt unverified"
);
}
/// Chain-dependent calls get a longer budget than local wallet-management calls,
/// and the budget is the backend's to set — not a hard-coded 5s.
#[tokio::test]
async fn chain_calls_get_a_longer_budget_than_local_calls() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(serve_delayed(
listener,
std::time::Duration::from_millis(400),
));
let w = recording_wallet(port).with_timeouts(
std::time::Duration::from_millis(150),
std::time::Duration::from_millis(2000),
);
let err = w.get_address().await.unwrap_err().to_string();
assert!(
err.to_ascii_lowercase().contains("timed out"),
"the local call must hit the short budget: {err}"
);
assert!(
w.chain_ready()
.await
.expect("get_info within the chain budget"),
"chain calls must outlast daemon latency"
);
}
// ---------------------------------------------------------------------------
// Stored wallet config (F7): read at boot, sealed at rest, never in an error.
// ---------------------------------------------------------------------------
/// The exact refusal copy the TUI asserts. Pinned here as literals so a copy
/// change is a test failure, and cross-checked against the constants the guard
/// returns.
#[test]
fn readiness_guard_refuses_each_state_with_exact_copy() {
assert_eq!(
NOT_CONFIGURED_MSG,
"wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC"
);
assert_eq!(
NOT_CONNECTED_MSG,
"wallet not connected — check endpoint, login, daemon"
);
assert_eq!(Readiness::NotConfigured.refusal(), Some(NOT_CONFIGURED_MSG));
assert_eq!(Readiness::NotConnected.refusal(), Some(NOT_CONNECTED_MSG));
assert_eq!(Readiness::NoSpend.refusal(), Some(VIEW_ONLY_MSG));
assert_eq!(Readiness::Ready.refusal(), None);
// not configured beats everything else, whatever else is true.
assert_eq!(
readiness(false, false, false, true),
Readiness::NotConfigured
);
assert_eq!(readiness(false, true, true, true), Readiness::NotConfigured);
// configured but not reachable.
assert_eq!(readiness(true, false, false, true), Readiness::NotConnected);
assert_eq!(
readiness(true, false, false, false),
Readiness::NotConnected
);
// view-only: /tip is refused on its own terms, /pay keeps working.
assert_eq!(readiness(true, true, true, true), Readiness::NoSpend);
assert_eq!(readiness(true, false, true, true), Readiness::NoSpend);
assert_eq!(readiness(true, true, true, false), Readiness::Ready);
// allowed only when configured + connected + spend-capable.
assert_eq!(readiness(true, true, false, true), Readiness::Ready);
assert!(!readiness(true, false, false, true).is_ready());
}
#[test]
fn wallet_config_debug_never_prints_the_login() {
let cfg = WalletConfig::new("http://127.0.0.1:18083", "ow:hunter2XYZ", true);
let dbg = format!("{cfg:?}");
assert!(!dbg.contains("hunter2XYZ"), "debug leaked the login: {dbg}");
assert!(dbg.contains("127.0.0.1:18083"), "{dbg}");
}
/// Stored config is what boot reads; env is the migration/fallback path.
#[test]
fn boot_reads_stored_config_over_env_and_falls_back_to_env() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
unsafe {
std::env::set_var("ONIONWIRE_WALLET_RPC", "http://ow:[email protected]:18083");
std::env::remove_var("ONIONWIRE_WALLET_RPC_LOGIN");
std::env::remove_var("ONIONWIRE_WALLET_NO_SPEND");
}
let stored = WalletConfig::new("http://127.0.0.1:18084", "ow:storedpass", true);
let w = Wallet::for_boot(Some(&stored));
assert!(w.configured(), "stored config must configure the wallet");
assert!(w.no_spend(), "stored no_spend must win over env");
let in_use = w.config().expect("configured wallet has a config");
assert_eq!(in_use.rpc_url, "http://127.0.0.1:18084/json_rpc");
assert_eq!(in_use.rpc_login.as_str(), "ow:storedpass");
assert!(!in_use.rpc_url.contains("storedpass"), "{}", in_use.rpc_url);
// No stored config: the env vars still boot headless / pre-F7 installs.
let w = Wallet::for_boot(None);
assert!(w.configured());
let in_use = w.config().expect("env wallet has a config");
assert_eq!(in_use.rpc_url, "http://127.0.0.1:18083/json_rpc");
assert_eq!(in_use.rpc_login.as_str(), "ow:envpass");
assert!(!w.no_spend());
// A stored config that cannot be used falls through to env, not to a dial.
let broken = WalletConfig::new("http://example.com:18083", "ow:x", false);
assert!(Wallet::for_boot(Some(&broken)).configured());
// Neither: disabled, and the refusal says so.
unsafe {
std::env::remove_var("ONIONWIRE_WALLET_RPC");
}
let w = Wallet::for_boot(None);
assert!(!w.configured());
assert!(w.config().is_none());
}
#[test]
fn malformed_config_errors_never_carry_the_password() {
let cfg = WalletConfig::new("http://example.com:18083", "ow:hunter2XYZ", false);
let err = Wallet::from_config(&cfg).unwrap_err().to_string();
assert!(!err.contains("hunter2XYZ"), "password leaked: {err}");
let cfg = WalletConfig::new("http://127.0.0.1:18083", "", false);
let err = Wallet::from_config(&cfg).unwrap_err().to_string();
assert!(!err.is_empty());
let cfg = WalletConfig::new("", "ow:hunter2XYZ", false);
assert!(
Wallet::from_config(&cfg).is_err(),
"empty url is not a config"
);
}
/// One row, sealed with the store data key on top of SQLCipher, and nothing in
/// the clear on disk.
#[test]
fn stored_wallet_config_round_trips_and_the_login_is_sealed_on_disk() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open_at_with_passphrase(dir.path(), "cfg-pass").unwrap();
assert!(
store.load_wallet_config().unwrap().is_none(),
"a fresh store has no wallet config"
);
let cfg = WalletConfig::new("http://127.0.0.1:18083", "ow:cfg-secret-xyz", false);
store.save_wallet_config(&cfg).unwrap();
let got = store.load_wallet_config().unwrap().expect("stored config");
assert_eq!(got.rpc_url, "http://127.0.0.1:18083");
assert_eq!(got.rpc_login.as_str(), "ow:cfg-secret-xyz");
assert!(!got.no_spend);
// Saving again replaces the single row.
let cfg2 = WalletConfig::new("http://127.0.0.1:18085", "ow:second-secret-abc", true);
store.save_wallet_config(&cfg2).unwrap();
let got = store.load_wallet_config().unwrap().expect("stored config");
assert_eq!(got.rpc_url, "http://127.0.0.1:18085");
assert_eq!(got.rpc_login.as_str(), "ow:second-secret-abc");
assert!(got.no_spend);
// An empty URL clears the stored config instead of storing a half-config.
store
.save_wallet_config(&WalletConfig::new("", "", false))
.unwrap();
assert!(store.load_wallet_config().unwrap().is_none());
store.save_wallet_config(&cfg).unwrap();
store.checkpoint_wal().unwrap();
drop(store);
for name in ["onionwire.db", "onionwire.db-wal", "onionwire.db-shm"] {
let Ok(bytes) = std::fs::read(dir.path().join(name)) else {
continue;
};
assert!(
!contains_bytes(&bytes, b"cfg-secret-xyz"),
"{name} holds the RPC login in the clear"
);
}
// The readers come back to a config that still decrypts.
let store = Store::open_at_with_passphrase(dir.path(), "cfg-pass").unwrap();
let got = store
.load_wallet_config()
.unwrap()
.expect("reopened config");
assert_eq!(got.rpc_login.as_str(), "ow:cfg-secret-xyz");
}
fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
haystack.windows(needle.len()).any(|w| w == needle)
}
/// The one-shot probe the config screen's Test button fires. It is against the
/// *typed* endpoint, so it must not touch the live wallet.
#[tokio::test]
async fn ping_reports_success_and_sanitizes_failures() {
// A reachable endpoint: digest challenge, then get_address.
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let canned = json_rpc_ok(
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
);
tokio::spawn(serve_digest_then(listener, canned));
let ok = wallet::Wallet::ping(&format!("http://127.0.0.1:{port}"), "ow:ping-secret-xyz").await;
assert!(ok.ok, "{ok:?}");
assert_eq!(ok.status, "connected");
assert_eq!(ok.error, None);
assert!(!format!("{ok:?}").contains("ping-secret-xyz"));
// Nothing listening: refused, and the reason carries no password.
let dead = freed_loopback_port();
let bad = wallet::Wallet::ping(&format!("http://127.0.0.1:{dead}"), "ow:ping-secret-xyz").await;
assert!(!bad.ok, "{bad:?}");
assert!(bad.error.is_some(), "{bad:?}");
assert!(
!bad.error.as_deref().unwrap().contains("ping-secret-xyz"),
"{bad:?}"
);
// A non-loopback host is refused locally, before any dial.
let off = wallet::Wallet::ping("http://node.example.com:18083", "ow:ping-secret-xyz").await;
assert!(!off.ok);
assert!(
!off.error
.as_deref()
.unwrap_or_default()
.contains("ping-secret-xyz"),
"{off:?}"
);
// An open RPC (no digest challenge) is refused with no password in it.
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let open = http_200_body(r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4AA"}}"#);
tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.expect("accept");
let mut buf = vec![0u8; 4096];
let _ = sock.read(&mut buf).await;
let _ = sock.write_all(open.as_bytes()).await;
});
let open =
wallet::Wallet::ping(&format!("http://127.0.0.1:{port}"), "ow:ping-secret-xyz").await;
assert!(!open.ok, "{open:?}");
assert!(
open.error.as_deref().unwrap_or_default().contains("digest"),
"{open:?}"
);
}
/// `WalletStatus.connected` comes from a probe, never from config-existence —
/// and a lower layer that echoes the password into an RPC error cannot leak it
/// into the status line.
#[tokio::test]
async fn status_is_connected_only_after_a_successful_probe() {
// Configured but never probed: connected is false, config is not reachability.
let idle = WalletStatus::idle(true);
assert!(idle.configured());
assert!(!idle.connected, "config exists is not reachability");
assert_eq!(idle.balance_line, "—");
assert_eq!(idle.receive_address, "—");
// A successful probe: connected, address + balance filled in.
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(serve_recording(
listener,
Arc::new(Mutex::new(Vec::new())),
Arc::new(|method: &str| match method {
"get_address" => rpc_result(
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
),
"get_balance" => rpc_result(r#"{"balance":"123456"}"#),
_ => rpc_result("{}"),
}),
));
let w = recording_wallet(port);
let ok = w.status().await;
assert!(ok.configured() && ok.connected, "{ok:?}");
assert_eq!(ok.last_error, None);
assert_eq!(ok.balance_line, "123456 piconero");
assert!(ok.receive_address.starts_with('4'), "{ok:?}");
// A probe that fails keeps configured=true and turns connected off.
let dead = freed_loopback_port();
let down = Wallet::from_url(&format!("http://ow:[email protected]:{dead}")).unwrap();
let bad = down.status().await;
assert!(bad.configured(), "{bad:?}");
assert!(!bad.connected, "{bad:?}");
assert!(bad.last_error.is_some(), "{bad:?}");
assert_eq!(bad.balance_line, "—");
assert_eq!(bad.receive_address, "—");
// An RPC error message that repeats the password is redacted before display.
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let leaky = http_200_body(&rpc_error(-1, "auth failed for ow:leak-secret-xyz"));
tokio::spawn(serve_digest_then(listener, leaky));
let w = Wallet::from_url(&format!("http://ow:[email protected]:{port}")).unwrap();
let leak = w.status().await;
assert!(!leak.connected, "{leak:?}");
let err = leak.last_error.expect("failure reason");
assert!(!err.contains("leak-secret-xyz"), "password leaked: {err}");
assert!(err.contains("<redacted>"), "{err}");
assert!(
err.chars().count() <= 121,
"status copy must stay short: {err}"
);
// Nothing configured at all.
let none = Wallet::disabled().status().await;
assert!(!none.configured() && !none.connected, "{none:?}");
}
/// A port nothing is listening on: bind it, read it, drop the listener.
fn freed_loopback_port() -> u16 {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
drop(listener);
port
}
// ---------------------------------------------------------------------------
// Chain daemon client: the Cuprate parity workarounds.
//
// Every payload below is copied from the Spike A evidence
// (`rpc-evidence/` next to `docs/cuprate-launch-spike.md`), not invented:
// Cuprate answers an out-of-range `get_block` with a bare HTTP 500 and a
// zero-byte body, reports `outgoing_connections_count = 0` while it downloads
// blocks, answers `database_size = 5368709120` (exactly 5 GiB) and
// `version = ""` on its restricted server, and `free_space` is `u64::MAX` on
// both servers.
// ---------------------------------------------------------------------------
/// Serve exactly one HTTP response, then drop the listener. Returns the port.
async fn serve_raw(response: String) -> u16 {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.expect("accept");
let mut buf = vec![0u8; 8192];
let _ = sock.read(&mut buf).await;
let _ = sock.write_all(response.as_bytes()).await;
});
port
}
/// Same, but records the request line so a test can assert which endpoint and
/// method the client used.
async fn serve_raw_logged(response: String, log: Arc<Mutex<Vec<String>>>) -> u16 {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.expect("accept");
let mut buf = vec![0u8; 8192];
let n = sock.read(&mut buf).await.unwrap_or(0);
log.lock()
.expect("log")
.push(String::from_utf8_lossy(&buf[..n]).to_string());
let _ = sock.write_all(response.as_bytes()).await;
});
port
}
/// `HTTP/1.1 500 Internal Server Error` with an empty body — what Cuprate
/// answers for a height above its tip.
const CUPRATE_OUT_OF_RANGE: &str =
"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
/// monerod's answer to the same request: HTTP 200 with an epee/JSON-RPC error
/// object, `CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT` = -2
/// (`src/rpc/core_rpc_server_error_codes.h`).
fn monerod_too_big_height() -> String {
http_200_body(&rpc_error(
-2,
"Requested block height: 3300000 greater than current top block height: 23758",
))
}
fn daemon_addr(port: u16) -> String {
format!("127.0.0.1:{port}")
}
#[tokio::test]
async fn out_of_range_get_block_is_a_typed_height_error() {
let port = serve_raw(CUPRATE_OUT_OF_RANGE.to_string()).await;
let err = wallet::daemon_get_block(&daemon_addr(port), 3_300_000, Duration::from_secs(5))
.await
.expect_err("an out-of-range height must not decode");
assert_eq!(
err,
WalletError::DaemonHeightOutOfRange,
"a bare 500 on a height-addressed call is the Cuprate spelling of TOO_BIG_HEIGHT"
);
}
#[tokio::test]
async fn out_of_range_get_height_is_the_same_typed_error() {
let port = serve_raw(CUPRATE_OUT_OF_RANGE.to_string()).await;
let err = wallet::daemon_get_height(&daemon_addr(port), Duration::from_secs(5))
.await
.expect_err("a 500 must not decode");
assert_eq!(err, WalletError::DaemonHeightOutOfRange);
}
#[tokio::test]
async fn monerod_too_big_height_object_is_the_same_typed_error() {
let port = serve_raw(monerod_too_big_height()).await;
let err = wallet::daemon_get_block(&daemon_addr(port), 3_300_000, Duration::from_secs(5))
.await
.expect_err("code -2 must map to the height error");
assert_eq!(
err,
WalletError::DaemonHeightOutOfRange,
"parity: monerod's -2 and Cuprate's bare 500 are the same failure"
);
}
#[tokio::test]
async fn a_5xx_that_is_not_height_addressed_is_a_status_error() {
let port = serve_raw(
"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
.to_string(),
)
.await;
let err = wallet::daemon_get_info(&daemon_addr(port), Duration::from_secs(5))
.await
.expect_err("503 is not a chain answer");
assert_eq!(err, WalletError::DaemonHttpStatus(503));
}
#[tokio::test]
async fn get_height_uses_the_uri_endpoint_and_cuprates_top_level_shape() {
// Evidence `GET__get_height.json`: no jsonrpc envelope, no `result`.
let body = r#"{"status":"OK","untrusted":false,"hash":"7458280ccc2befbbb074f50b37195ed13039178a05fd8816fc8f8a64fb4df417","height":23758}"#;
let log = Arc::new(Mutex::new(Vec::new()));
let port = serve_raw_logged(http_200_body(body), Arc::clone(&log)).await;
let height = wallet::daemon_get_height(&daemon_addr(port), Duration::from_secs(5))
.await
.expect("the URI endpoint answers");
assert_eq!(height, 23_758);
let req = log
.lock()
.expect("log")
.first()
.cloned()
.unwrap_or_default();
assert!(
req.starts_with("GET /get_height "),
"Cuprate rejects get_height over /json_rpc (422); the URI endpoint is the one that works: {req}"
);
}
#[tokio::test]
async fn get_info_reads_height_and_target_only() {
// Evidence `get_info.endpoint.post_sync.json`, mid-sync: height below
// target, zero peers, `free_space` u64::MAX.
let body = r#"{"jsonrpc":"2.0","id":"0","result":{"status":"OK","height":23758,"target_height":3090939,"synchronized":false,"database_size":54852877,"free_space":18446744073709551615,"incoming_connections_count":0,"outgoing_connections_count":0,"version":"0.1.0-preview-release"}}"#;
let port = serve_raw(http_200_body(body)).await;
let info = wallet::daemon_get_info(&daemon_addr(port), Duration::from_secs(5))
.await
.expect("a syncing daemon answers");
assert_eq!(
info,
DaemonInfo {
height: 23_758,
target_height: 3_090_939
}
);
}
#[tokio::test]
async fn cuprate_placeholder_metrics_never_change_what_the_client_reports() {
// The same height from both servers: the restricted payload carries a 5 GiB
// `database_size`, an empty `version`, zero peers and u64::MAX `free_space`.
// None of it may reach the client, because none of it is a measurement.
let unrestricted = r#"{"jsonrpc":"2.0","id":"0","result":{"height":1160,"target_height":0,"synchronized":true,"database_size":1770926,"free_space":18446744073709551615,"outgoing_connections_count":0,"version":"0.1.0-preview-release"}}"#;
let restricted = r#"{"jsonrpc":"2.0","id":"0","result":{"height":1160,"height_without_bootstrap":0,"target_height":0,"synchronized":true,"restricted":true,"database_size":5368709120,"free_space":18446744073709551615,"outgoing_connections_count":0,"incoming_connections_count":0,"version":""}}"#;
let a = serve_raw(http_200_body(unrestricted)).await;
let b = serve_raw(http_200_body(restricted)).await;
let one = wallet::daemon_get_info(&daemon_addr(a), Duration::from_secs(5))
.await
.unwrap();
let two = wallet::daemon_get_info(&daemon_addr(b), Duration::from_secs(5))
.await
.unwrap();
assert_eq!(
one, two,
"placeholder metrics must not influence the report"
);
assert_eq!(
one,
DaemonInfo {
height: 1160,
target_height: 0
}
);
}
#[tokio::test]
async fn chunked_daemon_answers_are_dechunked() {
// axum/hyper (Cuprate) answers with `Transfer-Encoding: chunked`; the body
// arrives framing-wrapped, so brace-scanning alone is not a parse.
let json = r#"{"jsonrpc":"2.0","id":"0","result":{"height":1160,"target_height":0}}"#;
let (head, tail) = json.split_at(json.len() / 2);
let chunked = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n{:x}\r\n{head}\r\n{:x}\r\n{tail}\r\n0\r\n\r\n",
head.len(),
tail.len()
);
let port = serve_raw(chunked).await;
let info = wallet::daemon_get_info(&daemon_addr(port), Duration::from_secs(5))
.await
.expect("a chunked answer must parse");
assert_eq!(info.height, 1160);
}
#[tokio::test]
async fn a_dead_daemon_is_a_transport_error_that_names_the_address() {
let port = freed_loopback_port();
let err = wallet::daemon_get_info(&daemon_addr(port), Duration::from_secs(2))
.await
.expect_err("a closed port must not answer");
assert!(
err.to_string().contains(&daemon_addr(port)),
"the reason must name the address: {err}"
);
}
#[tokio::test]
async fn a_transport_failure_is_not_a_height_error() {
let port = freed_loopback_port();
let err = wallet::daemon_get_block(&daemon_addr(port), 1, Duration::from_secs(2))
.await
.expect_err("a closed port must not answer");
assert!(!err.is_height_out_of_range(), "{err}");
}
#[test]
fn only_the_height_error_reports_itself_as_one() {
assert!(WalletError::DaemonHeightOutOfRange.is_height_out_of_range());
assert!(!WalletError::DaemonHttpStatus(500).is_height_out_of_range());
assert!(
!WalletError::DaemonRpc {
code: -1,
message: "Invalid parameter".into()
}
.is_height_out_of_range()
);
}