2225 lines
84 KiB
Rust
2225 lines
84 KiB
Rust
|
|
//! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod.
|
||
|
|
|
||
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||
|
|
use std::sync::{Arc, Mutex};
|
||
|
|
|
||
|
|
use ed25519_dalek::SigningKey;
|
||
|
|
use onionwire::pay;
|
||
|
|
use onionwire::wallet::{
|
||
|
|
self, NOT_CONFIGURED_MSG, NOT_CONNECTED_MSG, Readiness, TransferRow, VIEW_ONLY_MSG, Wallet,
|
||
|
|
WalletConfig, WalletStatus, readiness,
|
||
|
|
};
|
||
|
|
use onionwire::wallet_child;
|
||
|
|
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}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A 401 on the authenticated retry means the login is wrong. That copy is
|
||
|
|
/// rendered in the TUI/Android status line, so it must not echo either half of
|
||
|
|
/// the credential — not the password, not `user:pass`, not a URL with userinfo.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn ping_401_error_carries_no_credential() {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let addr = listener.local_addr().unwrap();
|
||
|
|
// Answer the authenticated retry with another 401: the digest was built
|
||
|
|
// from this connection's own challenge, so this is a wrong login.
|
||
|
|
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> =
|
||
|
|
Arc::new(|_| digest_401("refused-again"));
|
||
|
|
tokio::spawn(serve_rpc_conns_with(listener, reply, None, None, true));
|
||
|
|
|
||
|
|
let pass = "s3cretPASS";
|
||
|
|
let login = format!("ow:{pass}");
|
||
|
|
let res = Wallet::ping(&format!("http://127.0.0.1:{}", addr.port()), login.as_str()).await;
|
||
|
|
assert!(!res.ok, "a refused digest must not report connected");
|
||
|
|
let err = res.error.expect("failure carries a reason");
|
||
|
|
println!("401 ping error: {err}");
|
||
|
|
assert!(!err.contains(pass), "password leaked in error: {err}");
|
||
|
|
assert!(!err.contains(&login), "login leaked in error: {err}");
|
||
|
|
assert!(
|
||
|
|
!err.contains(&format!("://{login}@")),
|
||
|
|
"URL userinfo 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: the wallet's own
|
||
|
|
// scanned height plus the daemon tip.
|
||
|
|
"get_height" => wallet_height(3210000),
|
||
|
|
_ => rpc_result(&format!(r#"{{"address":"{addr_hex}","tx_hash":"abc123"}}"#)),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||
|
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||
|
|
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}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The Digest challenge is bound to the **connection** that answered 401, the
|
||
|
|
/// way epee does it: `http_custom_handler` owns the `http_server_auth`, whose
|
||
|
|
/// nonce starts empty, so a nonce is only ever valid on the socket that received
|
||
|
|
/// it. A client that retries on a fresh socket presents a nonce that socket
|
||
|
|
/// never issued and is refused again — the real `monero-wallet-rpc` 401 this
|
||
|
|
/// suite reproduces. One socket serves requests until it closes; the mock closes
|
||
|
|
/// after an authenticated reply, because the client asks for `Connection: close`
|
||
|
|
/// there and epee honours it.
|
||
|
|
async fn serve_one_conn(
|
||
|
|
mut sock: tokio::net::TcpStream,
|
||
|
|
reply: Arc<dyn Fn(&str) -> String + Send + Sync>,
|
||
|
|
log: Option<Arc<Mutex<Vec<String>>>>,
|
||
|
|
delay: Option<std::time::Duration>,
|
||
|
|
raw_reply: bool,
|
||
|
|
) {
|
||
|
|
let mut nonce: Option<String> = None;
|
||
|
|
while let Some(req) = read_http_request(&mut sock).await {
|
||
|
|
if let Some(log) = &log {
|
||
|
|
log.lock().expect("log").push(req.clone());
|
||
|
|
}
|
||
|
|
let sent = authorization_nonce(&req);
|
||
|
|
if sent.is_some() && sent == nonce {
|
||
|
|
assert!(req.contains("Authorization: Digest"), "missing digest auth: {req}");
|
||
|
|
assert!(req.contains("username=\"ow\""), "missing user: {req}");
|
||
|
|
assert!(req.contains("response=\""), "missing response: {req}");
|
||
|
|
if let Some(d) = delay {
|
||
|
|
tokio::time::sleep(d).await;
|
||
|
|
}
|
||
|
|
let answer = reply(&rpc_method(&req));
|
||
|
|
// `raw_reply` servers hand back a whole HTTP response (some tests
|
||
|
|
// bake their own status line); the default is a JSON-RPC body.
|
||
|
|
let wire = if raw_reply {
|
||
|
|
answer
|
||
|
|
} else {
|
||
|
|
http_200_body(&answer)
|
||
|
|
};
|
||
|
|
let _ = sock.write_all(wire.as_bytes()).await;
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
let fresh = next_nonce();
|
||
|
|
let _ = sock.write_all(digest_401(&fresh).as_bytes()).await;
|
||
|
|
nonce = Some(fresh);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Accept loop for [`serve_one_conn`].
|
||
|
|
async fn serve_rpc_conns(
|
||
|
|
listener: TcpListener,
|
||
|
|
reply: Arc<dyn Fn(&str) -> String + Send + Sync>,
|
||
|
|
log: Option<Arc<Mutex<Vec<String>>>>,
|
||
|
|
delay: Option<std::time::Duration>,
|
||
|
|
) {
|
||
|
|
serve_rpc_conns_with(listener, reply, log, delay, false).await
|
||
|
|
}
|
||
|
|
|
||
|
|
/// [`serve_rpc_conns`] with the reply contract spelled out: `raw_reply` means the
|
||
|
|
/// closure returns a complete HTTP response, otherwise a JSON-RPC body.
|
||
|
|
async fn serve_rpc_conns_with(
|
||
|
|
listener: TcpListener,
|
||
|
|
reply: Arc<dyn Fn(&str) -> String + Send + Sync>,
|
||
|
|
log: Option<Arc<Mutex<Vec<String>>>>,
|
||
|
|
delay: Option<std::time::Duration>,
|
||
|
|
raw_reply: bool,
|
||
|
|
) {
|
||
|
|
while let Ok((sock, _)) = listener.accept().await {
|
||
|
|
tokio::spawn(serve_one_conn(
|
||
|
|
sock,
|
||
|
|
Arc::clone(&reply),
|
||
|
|
log.clone(),
|
||
|
|
delay,
|
||
|
|
raw_reply,
|
||
|
|
));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// 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>,
|
||
|
|
) {
|
||
|
|
serve_rpc_conns(listener, reply, Some(log), None).await
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Read one whole request: its head, then `Content-Length` body bytes. `None`
|
||
|
|
/// when the peer closed.
|
||
|
|
async fn read_http_request(sock: &mut tokio::net::TcpStream) -> Option<String> {
|
||
|
|
let mut buf = Vec::new();
|
||
|
|
let mut tmp = [0u8; 4096];
|
||
|
|
let head_end = loop {
|
||
|
|
if let Some(i) = find_head_end(&buf) {
|
||
|
|
break i;
|
||
|
|
}
|
||
|
|
match sock.read(&mut tmp).await {
|
||
|
|
Ok(0) | Err(_) => return None,
|
||
|
|
Ok(n) => buf.extend_from_slice(&tmp[..n]),
|
||
|
|
}
|
||
|
|
};
|
||
|
|
let head = String::from_utf8_lossy(&buf[..head_end]).to_string();
|
||
|
|
let want = content_length(&head).unwrap_or(0);
|
||
|
|
while buf.len() < head_end + 4 + want {
|
||
|
|
match sock.read(&mut tmp).await {
|
||
|
|
Ok(0) | Err(_) => break,
|
||
|
|
Ok(n) => buf.extend_from_slice(&tmp[..n]),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Some(String::from_utf8_lossy(&buf).to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
fn find_head_end(buf: &[u8]) -> Option<usize> {
|
||
|
|
buf.windows(4).position(|w| w == b"\r\n\r\n")
|
||
|
|
}
|
||
|
|
|
||
|
|
fn content_length(head: &str) -> Option<usize> {
|
||
|
|
head.lines().skip(1).find_map(|line| {
|
||
|
|
let (k, v) = line.split_once(':')?;
|
||
|
|
k.eq_ignore_ascii_case("content-length")
|
||
|
|
.then(|| v.trim().parse().ok())
|
||
|
|
.flatten()
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The `nonce` a request's `Authorization` field answers.
|
||
|
|
fn authorization_nonce(req: &str) -> Option<String> {
|
||
|
|
let head = req.split("\r\n\r\n").next().unwrap_or(req);
|
||
|
|
let line = head
|
||
|
|
.lines()
|
||
|
|
.find(|l| l.to_ascii_lowercase().starts_with("authorization:"))?;
|
||
|
|
let rest = line.split_once("nonce=")?.1;
|
||
|
|
Some(rest.trim_start_matches('"').split('"').next()?.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A fresh server nonce per 401, so a stale one never passes by luck.
|
||
|
|
fn next_nonce() -> String {
|
||
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||
|
|
static NEXT: AtomicUsize = AtomicUsize::new(1);
|
||
|
|
format!("nonce{:016x}", NEXT.fetch_add(1, Ordering::Relaxed))
|
||
|
|
}
|
||
|
|
|
||
|
|
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 the wallet RPC answers to `get_height`: the wallet's own scanned height.
|
||
|
|
/// This is the honest wallet-side signal — `get_info` does not exist there.
|
||
|
|
fn wallet_height(height: u64) -> String {
|
||
|
|
rpc_result(&format!(r#"{{"height":{height}}}"#))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A chain-daemon stub. `GET /get_height` answers the tip; `/json_rpc get_info`
|
||
|
|
/// answers height and target. A daemon is unauthenticated, so no Digest flow.
|
||
|
|
async fn serve_daemon(
|
||
|
|
listener: TcpListener,
|
||
|
|
height: u64,
|
||
|
|
target: u64,
|
||
|
|
log: Option<Arc<Mutex<Vec<String>>>>,
|
||
|
|
) {
|
||
|
|
while let Ok((mut sock, _)) = listener.accept().await {
|
||
|
|
let mut buf = vec![0u8; 8192];
|
||
|
|
let Ok(n) = sock.read(&mut buf).await else {
|
||
|
|
return;
|
||
|
|
};
|
||
|
|
if n == 0 {
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
let req = String::from_utf8_lossy(&buf[..n]).to_string();
|
||
|
|
if let Some(log) = &log {
|
||
|
|
log.lock().expect("daemon log").push(req.clone());
|
||
|
|
}
|
||
|
|
let body = if req.starts_with("GET /get_height") {
|
||
|
|
format!(r#"{{"height":{height}}}"#)
|
||
|
|
} else if req.contains("get_info") {
|
||
|
|
format!(
|
||
|
|
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target}}}}}"#
|
||
|
|
)
|
||
|
|
} else {
|
||
|
|
"{}".to_string()
|
||
|
|
};
|
||
|
|
let _ = sock
|
||
|
|
.write_all(
|
||
|
|
format!(
|
||
|
|
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||
|
|
body.len()
|
||
|
|
)
|
||
|
|
.as_bytes(),
|
||
|
|
)
|
||
|
|
.await;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Start a daemon stub on an ephemeral loopback port; returns `host:port`.
|
||
|
|
async fn mock_daemon(height: u64, target: u64) -> String {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let addr = listener.local_addr().unwrap().to_string();
|
||
|
|
tokio::spawn(serve_daemon(listener, height, target, None));
|
||
|
|
addr
|
||
|
|
}
|
||
|
|
|
||
|
|
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_height" => wallet_height(3210000),
|
||
|
|
_ => rpc_error(-18, "No transaction created"),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||
|
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||
|
|
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_height" => wallet_height(3210000),
|
||
|
|
_ => rpc_error(-18, "No transaction created"),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||
|
|
let err = recording_wallet(port)
|
||
|
|
.with_daemon_probe(Some(daemon))
|
||
|
|
.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).
|
||
|
|
/// An absent seed offset is not a field: the request must not carry one.
|
||
|
|
#[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",
|
||
|
|
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("lumber tacit lemon ivory risk"),
|
||
|
|
"seed missing: {restore}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
!restore.contains("seed_offset"),
|
||
|
|
"an absent offset must not become a field: {restore}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The seed offset is a second spend secret, sent beside the seed when present.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn restore_wallet_sends_a_non_empty_seed_offset() {
|
||
|
|
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",
|
||
|
|
Some("harbor-offset"),
|
||
|
|
)
|
||
|
|
.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#""seed_offset":"harbor-offset""#),
|
||
|
|
"offset missing: {restore}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
restore.contains("lumber tacit lemon ivory risk"),
|
||
|
|
"seed missing: {restore}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Blank or whitespace-only is the same as none: no `seed_offset` field at all,
|
||
|
|
/// never `"seed_offset":""`.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn restore_wallet_omits_a_whitespace_only_seed_offset() {
|
||
|
|
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",
|
||
|
|
Some(" "),
|
||
|
|
)
|
||
|
|
.await
|
||
|
|
.expect("blank offset restore");
|
||
|
|
let seen = log.lock().expect("log").clone();
|
||
|
|
assert!(
|
||
|
|
seen.iter()
|
||
|
|
.filter(|r| r.contains(r#""method":"restore_deterministic_wallet""#))
|
||
|
|
.all(|r| !r.contains("seed_offset")),
|
||
|
|
"a blank offset must not become a field: {seen:?}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Only the ends trim: an offset with interior spaces is sent as typed.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn restore_wallet_trims_the_ends_of_a_seed_offset() {
|
||
|
|
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",
|
||
|
|
Some(" harbor offset "),
|
||
|
|
)
|
||
|
|
.await
|
||
|
|
.expect("trimmed offset restore");
|
||
|
|
let seen = log.lock().expect("log").clone();
|
||
|
|
assert!(
|
||
|
|
seen.iter()
|
||
|
|
.any(|r| r.contains(r#""seed_offset":"harbor offset""#)),
|
||
|
|
"ends trim, interior spaces stay: {seen:?}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The offset is a spend secret: an RPC refusal must not echo it back.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn a_failed_restore_does_not_echo_the_seed_offset() {
|
||
|
|
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| rpc_error(-1, "restore refused")),
|
||
|
|
));
|
||
|
|
let err = recording_wallet(port)
|
||
|
|
.restore_wallet(
|
||
|
|
"onionwire",
|
||
|
|
"hunter2",
|
||
|
|
"lumber tacit lemon ivory risk",
|
||
|
|
Some("harbor-offset"),
|
||
|
|
)
|
||
|
|
.await
|
||
|
|
.unwrap_err()
|
||
|
|
.to_string();
|
||
|
|
assert!(
|
||
|
|
!err.contains("harbor-offset"),
|
||
|
|
"offset leaked in the error string: {err}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
!err.contains("lumber tacit lemon ivory risk"),
|
||
|
|
"seed leaked in the error string: {err}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[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", " ", None))
|
||
|
|
.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(nonce: &str) -> String {
|
||
|
|
format!(
|
||
|
|
"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"{nonce}\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\n\r\n"
|
||
|
|
)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Answers the Digest challenge on one connection with `ok` — a complete HTTP
|
||
|
|
/// response — to every method.
|
||
|
|
async fn serve_digest_then(listener: TcpListener, ok: String) {
|
||
|
|
serve_rpc_conns_with(listener, Arc::new(move |_| ok.clone()), None, None, true).await
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The digest retry must ride the socket that issued the challenge. epee binds
|
||
|
|
/// the nonce to the connection, so the pre-fix shape — challenge on one socket,
|
||
|
|
/// authenticated retry on another — is refused with 401 forever. That is the
|
||
|
|
/// `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed while
|
||
|
|
/// this suite stayed green against a mock that replayed the challenge on any
|
||
|
|
/// socket.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn digest_retry_rides_the_connection_that_issued_the_challenge() {
|
||
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||
|
|
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
let conns = Arc::new(AtomicUsize::new(0));
|
||
|
|
let counted = Arc::clone(&conns);
|
||
|
|
tokio::spawn(async move {
|
||
|
|
while let Ok((sock, _)) = listener.accept().await {
|
||
|
|
counted.fetch_add(1, Ordering::SeqCst);
|
||
|
|
tokio::spawn(serve_one_conn(
|
||
|
|
sock,
|
||
|
|
Arc::new(|_: &str| {
|
||
|
|
rpc_result(
|
||
|
|
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
|
||
|
|
)
|
||
|
|
}),
|
||
|
|
None,
|
||
|
|
None,
|
||
|
|
false,
|
||
|
|
));
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
let got = recording_wallet(port)
|
||
|
|
.get_address()
|
||
|
|
.await
|
||
|
|
.expect("a same-socket digest retry must be accepted");
|
||
|
|
assert!(got.starts_with('4'), "got {got}");
|
||
|
|
assert_eq!(
|
||
|
|
conns.load(Ordering::SeqCst),
|
||
|
|
1,
|
||
|
|
"one RPC call must use one connection: challenge and retry share it"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The flip side, pinned at the socket level: the nonce belongs to the
|
||
|
|
/// connection that minted it, so the same digest on a second connection is
|
||
|
|
/// refused. Without this the mock could silently go back to accepting the
|
||
|
|
/// cross-connection retry and stop catching the bug.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn the_mock_refuses_a_digest_presented_on_another_connection() {
|
||
|
|
use tokio::net::TcpStream;
|
||
|
|
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
tokio::spawn(serve_rpc_conns(
|
||
|
|
listener,
|
||
|
|
Arc::new(|_: &str| rpc_result("{}")),
|
||
|
|
None,
|
||
|
|
None,
|
||
|
|
));
|
||
|
|
|
||
|
|
let body = r#"{"jsonrpc":"2.0","id":"0","method":"get_version","params":{}}"#;
|
||
|
|
let plain = format!(
|
||
|
|
"POST /json_rpc HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
|
||
|
|
body.len()
|
||
|
|
);
|
||
|
|
|
||
|
|
let mut first = TcpStream::connect(("127.0.0.1", port)).await.unwrap();
|
||
|
|
first.write_all(plain.as_bytes()).await.unwrap();
|
||
|
|
let raw = read_http_request(&mut first).await.expect("the 401");
|
||
|
|
assert!(raw.starts_with("HTTP/1.1 401"), "got {raw}");
|
||
|
|
let nonce = raw
|
||
|
|
.split_once("nonce=\"")
|
||
|
|
.and_then(|(_, rest)| rest.split('"').next())
|
||
|
|
.expect("a challenge nonce")
|
||
|
|
.to_string();
|
||
|
|
drop(first);
|
||
|
|
|
||
|
|
let answered = format!(
|
||
|
|
"POST /json_rpc HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAuthorization: Digest username=\"ow\", realm=\"monero-rpc\", nonce=\"{nonce}\", uri=\"/json_rpc\", algorithm=MD5, response=\"deadbeef\"\r\n\r\n{body}",
|
||
|
|
body.len()
|
||
|
|
);
|
||
|
|
let mut second = TcpStream::connect(("127.0.0.1", port)).await.unwrap();
|
||
|
|
second.write_all(answered.as_bytes()).await.unwrap();
|
||
|
|
let raw = read_http_request(&mut second).await.expect("the second 401");
|
||
|
|
assert!(
|
||
|
|
raw.starts_with("HTTP/1.1 401"),
|
||
|
|
"a nonce from another connection must not be accepted: {raw}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[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}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The seed is a spend key: `mnemonic` must be one `query_key mnemonic` call
|
||
|
|
/// and nothing else, so the caller sees exactly what the open wallet answers.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn mnemonic_returns_the_words_the_rpc_answers() {
|
||
|
|
const WORDS: &str = "one two three four five six seven eight nine ten eleven twelve \
|
||
|
|
thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty twentyone \
|
||
|
|
twentytwo twentythree twentyfour twentyfive";
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
tokio::spawn(serve_rpc_conns(
|
||
|
|
listener,
|
||
|
|
Arc::new(|method: &str| match method {
|
||
|
|
"query_key" => rpc_result(&format!(r#"{{"key":"{WORDS}"}}"#)),
|
||
|
|
other => panic!("mnemonic must make one query_key call, saw {other}"),
|
||
|
|
}),
|
||
|
|
None,
|
||
|
|
None,
|
||
|
|
));
|
||
|
|
let got = recording_wallet(port).mnemonic().await.expect("mnemonic");
|
||
|
|
assert_eq!(got, WORDS);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A wallet with no open file answers a JSON-RPC error. It must surface as the
|
||
|
|
/// wallet's error, and the RPC login from the URL must not ride along with it.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn mnemonic_surfaces_an_rpc_error_without_leaking_the_login() {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
tokio::spawn(serve_rpc_conns(
|
||
|
|
listener,
|
||
|
|
Arc::new(|_: &str| rpc_error(-1, "wallet file is not open")),
|
||
|
|
None,
|
||
|
|
None,
|
||
|
|
));
|
||
|
|
let err = recording_wallet(port).mnemonic().await.unwrap_err();
|
||
|
|
let msg = err.to_string();
|
||
|
|
assert!(msg.contains("wallet file is not open"), "got {err}");
|
||
|
|
assert!(!msg.contains("secret"), "password leaked: {err}");
|
||
|
|
assert!(!msg.contains("http://"), "endpoint leaked: {err}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The refused-digest refusal names the login in prose ("the login does not
|
||
|
|
/// match"), which is exactly the copy that must not carry the credential.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn mnemonic_refuses_a_rejected_digest_without_leaking_the_login() {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
tokio::spawn(serve_rpc_conns_with(
|
||
|
|
listener,
|
||
|
|
Arc::new(|_: &str| "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n".to_string()),
|
||
|
|
None,
|
||
|
|
None,
|
||
|
|
true,
|
||
|
|
));
|
||
|
|
let err = recording_wallet(port).mnemonic().await.unwrap_err();
|
||
|
|
let msg = err.to_string();
|
||
|
|
assert!(msg.contains("digest rejected"), "got {err}");
|
||
|
|
assert!(!msg.contains("secret"), "password leaked: {err}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// No endpoint, no dial: the refusal is the configured-guard copy the rest of
|
||
|
|
/// the wallet uses, not a connection error.
|
||
|
|
#[test]
|
||
|
|
fn mnemonic_on_an_unconfigured_wallet_is_a_refusal_not_a_dial() {
|
||
|
|
let w = Wallet::disabled();
|
||
|
|
let err = tokio::runtime::Builder::new_current_thread()
|
||
|
|
.enable_all()
|
||
|
|
.build()
|
||
|
|
.unwrap()
|
||
|
|
.block_on(w.mnemonic())
|
||
|
|
.unwrap_err();
|
||
|
|
assert_eq!(err.to_string(), NOT_CONFIGURED_MSG);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The two private keys come from the open wallet file, in two `query_key`
|
||
|
|
/// calls: `view_key` first (always available), `spend_key` second (absent on a
|
||
|
|
/// view-only wallet). A wallet that can spend answers both.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn keys_returns_the_view_and_spend_keys_of_the_open_wallet() {
|
||
|
|
const VIEW: &str = "0f0e0d0c0b0a09080706050403020100";
|
||
|
|
const SPEND: &str = "0102030405060708090a0b0c0d0e0f10";
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
let calls = Arc::new(AtomicUsize::new(0));
|
||
|
|
let seen = Arc::clone(&calls);
|
||
|
|
tokio::spawn(serve_rpc_conns(
|
||
|
|
listener,
|
||
|
|
Arc::new(move |method: &str| match method {
|
||
|
|
"query_key" => match seen.fetch_add(1, Ordering::SeqCst) {
|
||
|
|
0 => rpc_result(&format!(r#"{{"key":"{VIEW}"}}"#)),
|
||
|
|
_ => rpc_result(&format!(r#"{{"key":"{SPEND}"}}"#)),
|
||
|
|
},
|
||
|
|
other => panic!("keys must only ask query_key, saw {other}"),
|
||
|
|
}),
|
||
|
|
None,
|
||
|
|
None,
|
||
|
|
));
|
||
|
|
let keys = recording_wallet(port).keys().await.expect("keys");
|
||
|
|
assert_eq!(keys.view_key, VIEW);
|
||
|
|
assert_eq!(keys.spend_key.as_deref(), Some(SPEND));
|
||
|
|
assert_eq!(calls.load(Ordering::SeqCst), 2, "one call per key");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A view-only wallet has no spend key: the RPC answers `-29`
|
||
|
|
/// (`WALLET_RPC_ERROR_CODE_WATCH_ONLY`). That is the wallet's answer, so it must
|
||
|
|
/// come back as `spend_key: None` — not as an error, which would leave the
|
||
|
|
/// backup screen unable to show the view key.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn keys_of_a_view_only_wallet_have_no_spend_key_and_no_error() {
|
||
|
|
const VIEW: &str = "aabbccddeeff00112233445566778899";
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
let calls = Arc::new(AtomicUsize::new(0));
|
||
|
|
let seen = Arc::clone(&calls);
|
||
|
|
tokio::spawn(serve_rpc_conns(
|
||
|
|
listener,
|
||
|
|
Arc::new(move |method: &str| match method {
|
||
|
|
"query_key" => match seen.fetch_add(1, Ordering::SeqCst) {
|
||
|
|
0 => rpc_result(&format!(r#"{{"key":"{VIEW}"}}"#)),
|
||
|
|
_ => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."),
|
||
|
|
},
|
||
|
|
other => panic!("keys must only ask query_key, saw {other}"),
|
||
|
|
}),
|
||
|
|
None,
|
||
|
|
None,
|
||
|
|
));
|
||
|
|
let keys = recording_wallet(port)
|
||
|
|
.keys()
|
||
|
|
.await
|
||
|
|
.expect("a view-only wallet");
|
||
|
|
assert_eq!(keys.view_key, VIEW);
|
||
|
|
assert_eq!(
|
||
|
|
keys.spend_key, None,
|
||
|
|
"view-only means no spend key to hand out"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Any *other* RPC failure is a real failure: a view-only `-29` is the only
|
||
|
|
/// error `keys` turns into `None`.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn keys_surfaces_an_rpc_error_that_is_not_the_view_only_answer() {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
let calls = Arc::new(AtomicUsize::new(0));
|
||
|
|
let seen = Arc::clone(&calls);
|
||
|
|
tokio::spawn(serve_rpc_conns(
|
||
|
|
listener,
|
||
|
|
Arc::new(move |_: &str| {
|
||
|
|
if seen.fetch_add(1, Ordering::SeqCst) == 0 {
|
||
|
|
rpc_result(r#"{"key":"aabbccdd"}"#)
|
||
|
|
} else {
|
||
|
|
rpc_error(-1, "wallet file is not open")
|
||
|
|
}
|
||
|
|
}),
|
||
|
|
None,
|
||
|
|
None,
|
||
|
|
));
|
||
|
|
let err = recording_wallet(port)
|
||
|
|
.keys()
|
||
|
|
.await
|
||
|
|
.expect_err("a spend-key error that is not -29 must not read as view-only");
|
||
|
|
let msg = err.to_string();
|
||
|
|
assert!(msg.contains("wallet file is not open"), "got {err}");
|
||
|
|
assert!(!msg.contains("secret"), "password leaked: {err}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// No endpoint, no dial: the refusal is the configured-guard copy the rest of
|
||
|
|
/// the wallet uses, not a connection error.
|
||
|
|
#[test]
|
||
|
|
fn keys_on_an_unconfigured_wallet_is_a_refusal_not_a_dial() {
|
||
|
|
let w = Wallet::disabled();
|
||
|
|
let err = tokio::runtime::Builder::new_current_thread()
|
||
|
|
.enable_all()
|
||
|
|
.build()
|
||
|
|
.unwrap()
|
||
|
|
.block_on(w.keys())
|
||
|
|
.unwrap_err();
|
||
|
|
assert_eq!(err.to_string(), NOT_CONFIGURED_MSG);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The keys are spend secrets. `WalletKeys` is the value the whole path carries,
|
||
|
|
/// so its `Debug` must not print either key — a stray `{:?}` in a log is how a
|
||
|
|
/// key leaks.
|
||
|
|
#[test]
|
||
|
|
fn wallet_keys_debug_never_prints_a_private_key() {
|
||
|
|
let keys = wallet::WalletKeys {
|
||
|
|
view_key: "VIEWKEYMATERIAL".to_string(),
|
||
|
|
spend_key: Some("SPENDKEYMATERIAL".to_string()),
|
||
|
|
};
|
||
|
|
let printed = format!("{keys:?}");
|
||
|
|
assert!(
|
||
|
|
!printed.contains("VIEWKEYMATERIAL"),
|
||
|
|
"view key leaked: {printed}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
!printed.contains("SPENDKEYMATERIAL"),
|
||
|
|
"spend key leaked: {printed}"
|
||
|
|
);
|
||
|
|
assert!(printed.contains("redacted"), "got {printed}");
|
||
|
|
|
||
|
|
let only_view = wallet::WalletKeys {
|
||
|
|
view_key: "VIEWKEYMATERIAL".to_string(),
|
||
|
|
spend_key: None,
|
||
|
|
};
|
||
|
|
let printed = format!("{only_view:?}");
|
||
|
|
assert!(
|
||
|
|
!printed.contains("VIEWKEYMATERIAL"),
|
||
|
|
"view key leaked: {printed}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
printed.contains("None"),
|
||
|
|
"a view-only wallet must read as None: {printed}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// 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) {
|
||
|
|
serve_rpc_conns(
|
||
|
|
listener,
|
||
|
|
Arc::new(|method: &str| match method {
|
||
|
|
"get_height" => wallet_height(3210000),
|
||
|
|
"get_transfers" => rpc_result(r#"{"in":[],"pending":[]}"#),
|
||
|
|
_ => rpc_result(
|
||
|
|
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
|
||
|
|
),
|
||
|
|
}),
|
||
|
|
None,
|
||
|
|
Some(delay),
|
||
|
|
)
|
||
|
|
.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_height" => wallet_height(1200000),
|
||
|
|
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||
|
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||
|
|
assert!(
|
||
|
|
!w.chain_ready().await.expect("get_height"),
|
||
|
|
"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:?}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// `monero-wallet-rpc` has no `get_info` (it answers `-32601 Method not found`).
|
||
|
|
/// Readiness must never depend on that call: the wallet's own `get_height` is
|
||
|
|
/// compared with the daemon's tip.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn readiness_never_asks_the_wallet_rpc_for_get_info() {
|
||
|
|
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_height" => wallet_height(3210000),
|
||
|
|
"get_info" => rpc_error(-32601, "Method not found"),
|
||
|
|
_ => rpc_result("{}"),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||
|
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||
|
|
assert!(
|
||
|
|
w.chain_ready().await.expect("get_height"),
|
||
|
|
"a wallet at the daemon tip is ready without get_info"
|
||
|
|
);
|
||
|
|
let seen = log.lock().expect("log").clone();
|
||
|
|
assert!(
|
||
|
|
seen.iter().any(|r| r.contains("\"method\":\"get_height\"")),
|
||
|
|
"the wallet's own scanned height must be asked: {seen:?}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
!seen.iter().any(|r| r.contains("\"method\":\"get_info\"")),
|
||
|
|
"get_info is not a wallet-RPC method and must not be probed: {seen:?}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Readiness against a daemon tip: equal is ready, the tip moves every ~2 min so
|
||
|
|
/// a two-block gap is ready, a real lag is not.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn a_wallet_within_the_slack_of_the_daemon_tip_is_ready() {
|
||
|
|
for (wallet, tip, ready) in [
|
||
|
|
(3210000u64, 3210000u64, true),
|
||
|
|
(3209998, 3210000, true),
|
||
|
|
(3209997, 3210000, false),
|
||
|
|
] {
|
||
|
|
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 |_| wallet_height(wallet)),
|
||
|
|
));
|
||
|
|
let daemon = mock_daemon(tip, tip).await;
|
||
|
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||
|
|
assert_eq!(
|
||
|
|
w.chain_ready().await.expect("get_height"),
|
||
|
|
ready,
|
||
|
|
"wallet {wallet} / tip {tip}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A daemon that does not answer leaves the tip unknown. Unknown is *not*
|
||
|
|
/// caught up — fail closed, never a silent pass.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn an_unreachable_daemon_is_not_ready() {
|
||
|
|
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(|_| wallet_height(3210000)),
|
||
|
|
));
|
||
|
|
// Bind, read the port, drop: nothing is listening there.
|
||
|
|
let dead = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let dead_addr = dead.local_addr().unwrap().to_string();
|
||
|
|
drop(dead);
|
||
|
|
let w = recording_wallet(port).with_daemon_probe(Some(dead_addr));
|
||
|
|
assert!(
|
||
|
|
!w.chain_ready().await.expect("get_height"),
|
||
|
|
"an unanswered daemon must not read as ready"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A wallet RPC with no wallet file open answers `-13 No wallet file` to
|
||
|
|
/// `get_height`. That is a state, not an error banner: not ready, no Err.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn an_rpc_with_no_wallet_open_is_not_ready_and_not_an_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(|_| rpc_error(-13, "No wallet file")),
|
||
|
|
));
|
||
|
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||
|
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||
|
|
assert!(
|
||
|
|
!w.chain_ready()
|
||
|
|
.await
|
||
|
|
.expect("no wallet file is a state, not an error"),
|
||
|
|
"a wallet with no file open is not ready"
|
||
|
|
);
|
||
|
|
assert!(!w.can_verify_receipts().await);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// An answered `get_height` with no height (or height 0) is unknown, and a
|
||
|
|
/// daemon tip of 0 is a daemon that has not indexed anything: not ready.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn a_missing_or_zero_wallet_height_is_not_ready() {
|
||
|
|
for info in [r#"{}"#, r#"{"height":0}"#, r#"{"height":"10"}"#] {
|
||
|
|
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 daemon = mock_daemon(0, 0).await;
|
||
|
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||
|
|
assert!(
|
||
|
|
!w.chain_ready().await.expect("get_height"),
|
||
|
|
"{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_height" => wallet_height(3210000),
|
||
|
|
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||
|
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||
|
|
assert!(w.chain_ready().await.expect("get_height"));
|
||
|
|
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_height" => wallet_height(3210000),
|
||
|
|
"get_balance" => balance.clone(),
|
||
|
|
_ => rpc_result("{}"),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||
|
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||
|
|
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_height" => wallet_height(1200000),
|
||
|
|
"get_transfers" => rpc_result(&format!(
|
||
|
|
r#"{{"in":[{{"txid":"deadbeef","amount":5,"address":"{addr_owned}"}}],"pending":[]}}"#
|
||
|
|
)),
|
||
|
|
_ => rpc_result("{}"),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||
|
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||
|
|
|
||
|
|
// 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_transfers`, `transfer`) get a longer budget than
|
||
|
|
/// local wallet-management calls, and the budget is the backend's to set — not a
|
||
|
|
/// hard-coded 5s. Readiness is no longer a chain wait: it is one local
|
||
|
|
/// `get_height` plus one bounded daemon probe.
|
||
|
|
#[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}"
|
||
|
|
);
|
||
|
|
let rows = w
|
||
|
|
.get_transfers()
|
||
|
|
.await
|
||
|
|
.expect("get_transfers within the chain budget");
|
||
|
|
assert!(rows.is_empty(), "{rows:?}");
|
||
|
|
}
|
||
|
|
|
||
|
|
// ---------------------------------------------------------------------------
|
||
|
|
// 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:?}");
|
||
|
|
}
|
||
|
|
|
||
|
|
// Chain-source labels and the persisted wallet-child settings. The child itself
|
||
|
|
// spawns processes (see `src/node.rs`'s tests and `src/wallet_child.rs`), so
|
||
|
|
// these cover the public shapes a config screen and the SDK build on.
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn chain_source_labels_name_what_the_child_dials() {
|
||
|
|
use std::path::PathBuf;
|
||
|
|
|
||
|
|
use onionwire::wallet::ChainSource;
|
||
|
|
|
||
|
|
assert_eq!(ChainSource::None.label(), "receive-only");
|
||
|
|
assert_eq!(
|
||
|
|
ChainSource::Local {
|
||
|
|
monerod_bin: PathBuf::from("/usr/bin/monerod"),
|
||
|
|
datadir: PathBuf::from("/var/lib/onionwire"),
|
||
|
|
prune: false,
|
||
|
|
}
|
||
|
|
.label(),
|
||
|
|
"local full node"
|
||
|
|
);
|
||
|
|
assert_eq!(
|
||
|
|
ChainSource::Remote {
|
||
|
|
host: "daemon.onion".into(),
|
||
|
|
port: 18089
|
||
|
|
}
|
||
|
|
.label(),
|
||
|
|
"remote onion daemon"
|
||
|
|
);
|
||
|
|
assert_eq!(
|
||
|
|
ChainSource::Remote {
|
||
|
|
host: "127.0.0.1".into(),
|
||
|
|
port: 18089
|
||
|
|
}
|
||
|
|
.label(),
|
||
|
|
"remote daemon"
|
||
|
|
);
|
||
|
|
// Onion detection needs the suffix, and is case-insensitive.
|
||
|
|
assert!(
|
||
|
|
ChainSource::Remote {
|
||
|
|
host: "ABCDEF.ONION".into(),
|
||
|
|
port: 1
|
||
|
|
}
|
||
|
|
.is_onion()
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
!ChainSource::Remote {
|
||
|
|
host: "notonion.example".into(),
|
||
|
|
port: 1
|
||
|
|
}
|
||
|
|
.is_onion()
|
||
|
|
);
|
||
|
|
assert!(!ChainSource::None.is_onion());
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn child_settings_round_trip_sealed_and_keep_the_creds() {
|
||
|
|
use std::path::PathBuf;
|
||
|
|
|
||
|
|
use onionwire::wallet::ChainSource;
|
||
|
|
use onionwire::wallet_child::{ChildConfig, merge_record};
|
||
|
|
|
||
|
|
let cfg = ChildConfig {
|
||
|
|
source: ChainSource::Remote {
|
||
|
|
host: "daemon.onion".into(),
|
||
|
|
port: 18089,
|
||
|
|
},
|
||
|
|
wallet_rpc_bin: PathBuf::from("/data/app/lib/libmonero-wallet-rpc.so"),
|
||
|
|
arti_bin: PathBuf::from("/data/app/lib/libarti.so"),
|
||
|
|
wallet_filename: "onionwire".into(),
|
||
|
|
};
|
||
|
|
let record = merge_record(None, cfg.record_fields());
|
||
|
|
// The creds a first start seals live in the same record and must survive a
|
||
|
|
// later settings save.
|
||
|
|
let with_creds = merge_record(
|
||
|
|
Some(&record),
|
||
|
|
serde_json::json!({"user": "owuser", "pass": "ow-secret"}),
|
||
|
|
);
|
||
|
|
|
||
|
|
let dir = std::env::temp_dir().join(format!("ow-child-cfg-{}", std::process::id()));
|
||
|
|
let _ = std::fs::remove_dir_all(&dir);
|
||
|
|
let store = Store::open_at_with_passphrase(&dir, "child-cfg-pass").unwrap();
|
||
|
|
store.save_wallet_child(&with_creds).unwrap();
|
||
|
|
let raw = store.load_wallet_child().unwrap().expect("record");
|
||
|
|
assert_eq!(
|
||
|
|
ChildConfig::from_record(&raw).unwrap().expect("settings"),
|
||
|
|
cfg,
|
||
|
|
"the settings survive the sealed round trip"
|
||
|
|
);
|
||
|
|
drop(store);
|
||
|
|
let _ = std::fs::remove_dir_all(&dir);
|
||
|
|
|
||
|
|
// A record written before the settings existed is `None`, not a lie.
|
||
|
|
assert_eq!(
|
||
|
|
ChildConfig::from_record(r#"{"user":"u","pass":"p"}"#).unwrap(),
|
||
|
|
None
|
||
|
|
);
|
||
|
|
|
||
|
|
// Receive-only spawns nothing, so empty binaries are not an error there;
|
||
|
|
// they are for the kinds that spawn.
|
||
|
|
assert!(ChildConfig::receive_only().validate().is_ok());
|
||
|
|
let mut local = ChildConfig::receive_only();
|
||
|
|
local.source = ChainSource::Local {
|
||
|
|
monerod_bin: PathBuf::new(),
|
||
|
|
datadir: PathBuf::from("/var/lib/onionwire"),
|
||
|
|
prune: false,
|
||
|
|
};
|
||
|
|
let err = local.validate().expect_err("a local node needs monerod");
|
||
|
|
assert!(err.to_string().contains("monerod path required"), "{err}");
|
||
|
|
let mut remote = ChildConfig::receive_only();
|
||
|
|
remote.source = ChainSource::Remote {
|
||
|
|
host: "daemon.onion".into(),
|
||
|
|
port: 0,
|
||
|
|
};
|
||
|
|
let err = remote.validate().expect_err("a remote daemon needs a port");
|
||
|
|
assert!(err.to_string().contains("daemon port required"), "{err}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// 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
|
||
|
|
}
|
||
|
|
|
||
|
|
// ---------------------------------------------------------------------------
|
||
|
|
// The in-process chain daemon (feature `cuprate-daemon`).
|
||
|
|
//
|
||
|
|
// The one test in the suite that runs a real chain daemon: it launches the
|
||
|
|
// `cuprated` node OnionWire embeds, asks it through the *same* typed daemon
|
||
|
|
// client a remote `monerod` is asked through, and then proves the listener dies
|
||
|
|
// with the node. A testnet node with no peers answers RPC and stays at genesis,
|
||
|
|
// so this needs no network.
|
||
|
|
// ---------------------------------------------------------------------------
|
||
|
|
|
||
|
|
#[cfg(feature = "cuprate-daemon")]
|
||
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||
|
|
async fn an_in_process_cuprate_node_answers_the_typed_daemon_client() {
|
||
|
|
let dir = tempfile::tempdir().expect("tempdir");
|
||
|
|
let datadir = dir.path().join("chain");
|
||
|
|
let port = freed_loopback_port();
|
||
|
|
let addr = format!("127.0.0.1:{port}");
|
||
|
|
let budget = std::time::Duration::from_secs(5);
|
||
|
|
|
||
|
|
let mut node = onionwire::cuprate::CuprateNode::launch(&datadir, port, "Testnet", false)
|
||
|
|
.expect("launch the in-process testnet daemon");
|
||
|
|
|
||
|
|
// `launch` returns with the services started; the RPC listener can still be
|
||
|
|
// a moment behind, so poll with a deadline instead of racing it.
|
||
|
|
let mut info = None;
|
||
|
|
for _ in 0..40 {
|
||
|
|
if let Ok(got) = wallet::daemon_get_info(&addr, budget).await {
|
||
|
|
info = Some(got);
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
|
||
|
|
}
|
||
|
|
let info = info.expect("the in-process daemon never answered get_info on /json_rpc");
|
||
|
|
|
||
|
|
// A fresh testnet chain: genesis is height 1 and there is nothing to sync
|
||
|
|
// towards. The daemon's own consensus context is the reference, and the RPC
|
||
|
|
// answer may trail it by a block or two while it is running.
|
||
|
|
assert!(info.height >= 1, "genesis is height 1: {info:?}");
|
||
|
|
let context_height = node.chain_height();
|
||
|
|
assert!(context_height >= 1, "in-process height: {context_height}");
|
||
|
|
assert!(
|
||
|
|
info.height.abs_diff(context_height) <= 2,
|
||
|
|
"get_info ({}) and the node's own context ({context_height}) disagree",
|
||
|
|
info.height
|
||
|
|
);
|
||
|
|
assert_eq!(
|
||
|
|
info.target_height, 0,
|
||
|
|
"a testnet node with no peers reports no target, not a caught-up chain"
|
||
|
|
);
|
||
|
|
|
||
|
|
// `get_height` is the URI endpoint (Cuprate rejects it over /json_rpc), and
|
||
|
|
// it has to agree with `get_info`.
|
||
|
|
let height = wallet::daemon_get_height(&addr, budget)
|
||
|
|
.await
|
||
|
|
.expect("get_height on the URI endpoint");
|
||
|
|
assert!(height >= 1, "{height}");
|
||
|
|
assert!(
|
||
|
|
height.abs_diff(info.height) <= 2,
|
||
|
|
"get_height ({height}) and get_info ({}) disagree",
|
||
|
|
info.height
|
||
|
|
);
|
||
|
|
|
||
|
|
// Genesis is always retrievable, and a height above the tip is the bare-500
|
||
|
|
// answer the typed client normalizes.
|
||
|
|
let genesis = wallet::daemon_get_block(&addr, 0, std::time::Duration::from_secs(30))
|
||
|
|
.await
|
||
|
|
.expect("get_block at genesis");
|
||
|
|
assert!(
|
||
|
|
genesis.len() > 70,
|
||
|
|
"a genesis block with a header and one tx is longer than this: {}",
|
||
|
|
genesis.len()
|
||
|
|
);
|
||
|
|
let far = wallet::daemon_get_block(
|
||
|
|
&addr,
|
||
|
|
info.height + 1_000_000,
|
||
|
|
std::time::Duration::from_secs(30),
|
||
|
|
)
|
||
|
|
.await;
|
||
|
|
assert!(
|
||
|
|
matches!(far, Err(wallet::WalletError::DaemonHeightOutOfRange)),
|
||
|
|
"an above-the-tip height must map to the typed height error: {far:?}"
|
||
|
|
);
|
||
|
|
|
||
|
|
// The chain database is Cuprate's own embedded store, under the datadir it
|
||
|
|
// was given — never beside OnionWire's SQLCipher file.
|
||
|
|
let fjall = datadir.join("testnet").join("fjall");
|
||
|
|
assert!(
|
||
|
|
fjall.is_dir(),
|
||
|
|
"the chain store must live under the chain datadir: {}",
|
||
|
|
fjall.display()
|
||
|
|
);
|
||
|
|
|
||
|
|
// Dropping the node *is* the shutdown. The listener has to go with it, or
|
||
|
|
// the app would leave a chain daemon behind after quitting.
|
||
|
|
drop(node);
|
||
|
|
let mut closed = false;
|
||
|
|
for _ in 0..40 {
|
||
|
|
if tokio::net::TcpStream::connect(&addr).await.is_err() {
|
||
|
|
closed = true;
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
|
||
|
|
}
|
||
|
|
assert!(
|
||
|
|
closed,
|
||
|
|
"the unrestricted RPC was still accepting after shutdown"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The call the whole restart story hangs on. Assert the bytes the client
|
||
|
|
/// **sent**: a mock that answers whatever it is asked stays green for a client
|
||
|
|
/// that never issued `open_wallet` at all — which is exactly how a wallet came
|
||
|
|
/// back from a restart answering `-13 No wallet file` while the suite passed.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn open_wallet_issues_the_rpc_method_with_the_file_and_passphrase() {
|
||
|
|
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_result("{}")),
|
||
|
|
));
|
||
|
|
|
||
|
|
recording_wallet(port)
|
||
|
|
.open_wallet("onionwire-1", "walletfile-pass")
|
||
|
|
.await
|
||
|
|
.expect("open_wallet");
|
||
|
|
|
||
|
|
let sent = log.lock().unwrap().join("\n");
|
||
|
|
assert!(
|
||
|
|
sent.contains(r#""method":"open_wallet""#),
|
||
|
|
"the client never asked to open the file: {sent}"
|
||
|
|
);
|
||
|
|
assert!(sent.contains(r#""filename":"onionwire-1""#), "{sent}");
|
||
|
|
assert!(sent.contains(r#""password":"walletfile-pass""#), "{sent}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Same refusals as `create_wallet`: an empty file name or an empty passphrase
|
||
|
|
/// is a local error, before any socket is opened.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn open_wallet_refuses_a_blank_filename_or_passphrase_locally() {
|
||
|
|
let w = Wallet::disabled();
|
||
|
|
let err = w.open_wallet(" ", "pw").await.expect_err("no filename");
|
||
|
|
assert!(err.to_string().contains("filename"), "{err}");
|
||
|
|
let err = w
|
||
|
|
.open_wallet("onionwire-1", "")
|
||
|
|
.await
|
||
|
|
.expect_err("no passphrase");
|
||
|
|
assert!(err.to_string().contains("passphrase"), "{err}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A refused passphrase is the RPC's own message, not a rewritten generic one:
|
||
|
|
/// the caller has to be able to tell it apart from a daemon that never answered.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn open_wallet_surfaces_the_rpcs_own_refusal() {
|
||
|
|
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(|_: &str| {
|
||
|
|
r#"{"jsonrpc":"2.0","id":"0","error":{"code":-1,"message":"Failed to open wallet"}}"#
|
||
|
|
.to_string()
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
|
||
|
|
let err = recording_wallet(port)
|
||
|
|
.open_wallet("onionwire-1", "wrong-pass")
|
||
|
|
.await
|
||
|
|
.expect_err("the RPC refused");
|
||
|
|
assert!(
|
||
|
|
err.to_string().contains("Failed to open wallet"),
|
||
|
|
"the RPC's own reason is what a caller needs: {err}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
!err.to_string().contains("wrong-pass"),
|
||
|
|
"the passphrase must never be echoed back in an error: {err}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
// ---------------------------------------------------------------------------
|
||
|
|
// `next_wallet_filename`'s disk half: monero writes two files per wallet and
|
||
|
|
// the daemon refuses a create that would collide with either, so the picker
|
||
|
|
// has to look at the directory, not only at the catalogue.
|
||
|
|
// ---------------------------------------------------------------------------
|
||
|
|
|
||
|
|
/// `<name>` and `<name>.keys` both mean taken; nothing else does.
|
||
|
|
#[test]
|
||
|
|
fn wallet_name_taken_sees_the_file_and_its_keys_sibling() {
|
||
|
|
let dir = tempfile::tempdir().expect("tempdir");
|
||
|
|
let wallet_dir = dir.path();
|
||
|
|
std::fs::write(wallet_dir.join("onionwire-1.keys"), b"keys").unwrap();
|
||
|
|
std::fs::write(wallet_dir.join("onionwire-2"), b"wallet").unwrap();
|
||
|
|
|
||
|
|
assert!(
|
||
|
|
wallet_child::wallet_name_taken(wallet_dir, "onionwire-1").unwrap(),
|
||
|
|
"the `.keys` sibling is enough to make the name taken"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
wallet_child::wallet_name_taken(wallet_dir, "onionwire-2").unwrap(),
|
||
|
|
"the wallet file itself is enough"
|
||
|
|
);
|
||
|
|
assert!(!wallet_child::wallet_name_taken(wallet_dir, "onionwire-3").unwrap());
|
||
|
|
assert!(
|
||
|
|
!wallet_child::wallet_name_taken(wallet_dir, "onionwire").unwrap(),
|
||
|
|
"a prefix is not a collision"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
!wallet_child::wallet_name_taken(wallet_dir, "onionwire-20").unwrap(),
|
||
|
|
"neither is a longer name that starts with a taken one"
|
||
|
|
);
|
||
|
|
|
||
|
|
// The files may be the only copy of a funded wallet: naming the collision
|
||
|
|
// must not remove it.
|
||
|
|
assert!(wallet_dir.join("onionwire-1.keys").is_file());
|
||
|
|
assert!(wallet_dir.join("onionwire-2").is_file());
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Fail closed: a directory that cannot be listed is an error, not "every name
|
||
|
|
/// is free". Guessing here is how the collision comes back.
|
||
|
|
#[test]
|
||
|
|
fn wallet_name_taken_fails_closed_when_the_dir_cannot_be_read() {
|
||
|
|
let dir = tempfile::tempdir().expect("tempdir");
|
||
|
|
let missing = dir.path().join("no-such-wallet-dir");
|
||
|
|
let err = wallet_child::wallet_name_taken(&missing, "onionwire-1")
|
||
|
|
.expect_err("a missing wallet dir must refuse, not answer 'free'")
|
||
|
|
.to_string();
|
||
|
|
assert!(
|
||
|
|
err.contains("wallet dir"),
|
||
|
|
"the error must name what could not be listed: {err}"
|
||
|
|
);
|
||
|
|
|
||
|
|
// A path that is a file, not a directory, is unreadable too.
|
||
|
|
let file = dir.path().join("not-a-dir");
|
||
|
|
std::fs::write(&file, b"x").unwrap();
|
||
|
|
assert!(wallet_child::wallet_name_taken(&file, "onionwire-1").is_err());
|
||
|
|
}
|