1547 lines
58 KiB
Rust
1547 lines
58 KiB
Rust
|
|
//! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod.
|
||
|
|
|
||
|
|
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::{PaymentWrite, Store};
|
||
|
|
use rand::rngs::OsRng;
|
||
|
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||
|
|
use tokio::net::TcpListener;
|
||
|
|
|
||
|
|
/// `ONIONWIRE_WALLET_NO_SPEND` is process-wide; tests that touch env serialize.
|
||
|
|
static ENV_LOCK: Mutex<()> = Mutex::new(());
|
||
|
|
|
||
|
|
fn row(txid: &str, amount: &str, address: &str) -> TransferRow {
|
||
|
|
TransferRow {
|
||
|
|
txid: txid.into(),
|
||
|
|
amount: amount.into(),
|
||
|
|
address: address.into(),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
fn xmr_addr() -> String {
|
||
|
|
// Same documented mainnet standard as tests/pay.rs — F4 checksums this.
|
||
|
|
"4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge"
|
||
|
|
.to_string()
|
||
|
|
}
|
||
|
|
|
||
|
|
fn json_rpc_ok(result: &str) -> String {
|
||
|
|
let body = format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#);
|
||
|
|
format!(
|
||
|
|
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||
|
|
body.len()
|
||
|
|
)
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn disabled_create_address_is_not_configured() {
|
||
|
|
let w = Wallet::disabled();
|
||
|
|
let err = tokio::runtime::Builder::new_current_thread()
|
||
|
|
.enable_all()
|
||
|
|
.build()
|
||
|
|
.unwrap()
|
||
|
|
.block_on(w.create_address())
|
||
|
|
.unwrap_err();
|
||
|
|
assert!(err.to_string().contains("not configured"), "got {err}");
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn refuse_url_without_credentials() {
|
||
|
|
let err = Wallet::from_url("http://127.0.0.1:18083").unwrap_err();
|
||
|
|
let msg = err.to_string().to_ascii_lowercase();
|
||
|
|
assert!(
|
||
|
|
msg.contains("credential") || msg.contains("login") || msg.contains("user"),
|
||
|
|
"got {err}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn refuse_non_loopback_non_onion_host() {
|
||
|
|
let err = Wallet::from_url("http://ow:[email protected]:18083").unwrap_err();
|
||
|
|
assert!(
|
||
|
|
err.to_string().to_ascii_lowercase().contains("host")
|
||
|
|
|| err.to_string().contains("loopback")
|
||
|
|
|| err.to_string().contains("onion"),
|
||
|
|
"got {err}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn refuse_onion_rpc_url() {
|
||
|
|
let err = Wallet::from_url(
|
||
|
|
"http://ow:s3cretPASS@abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwxyz.onion:18083",
|
||
|
|
)
|
||
|
|
.unwrap_err();
|
||
|
|
let msg = err.to_string();
|
||
|
|
assert!(msg.to_ascii_lowercase().contains("onion"), "got {err}");
|
||
|
|
assert!(
|
||
|
|
!msg.contains("s3cretPASS"),
|
||
|
|
"password leaked in error: {err}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn password_absent_from_url_errors() {
|
||
|
|
let err = Wallet::from_url("http://ow:[email protected]:18083").unwrap_err();
|
||
|
|
assert!(
|
||
|
|
!err.to_string().contains("s3cretPASS"),
|
||
|
|
"password leaked in error: {err}"
|
||
|
|
);
|
||
|
|
let err = Wallet::from_url("http://ow:s3cretPASS@").unwrap_err();
|
||
|
|
assert!(
|
||
|
|
!err.to_string().contains("s3cretPASS"),
|
||
|
|
"password leaked in error: {err}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[tokio::test]
|
||
|
|
async fn mock_get_address_parses_string() {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let addr = listener.local_addr().unwrap();
|
||
|
|
let canned = json_rpc_ok(
|
||
|
|
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
|
||
|
|
);
|
||
|
|
tokio::spawn(serve_digest_then(listener, canned));
|
||
|
|
let w = Wallet::from_url(&format!("http://ow:[email protected]:{}", addr.port())).unwrap();
|
||
|
|
let got = w.get_address().await.expect("get_address");
|
||
|
|
assert!(got.starts_with('4'), "got {got}");
|
||
|
|
}
|
||
|
|
|
||
|
|
#[tokio::test]
|
||
|
|
async fn mock_create_address_and_transfer() {
|
||
|
|
let addr_hex = "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
tokio::spawn(serve_recording(
|
||
|
|
listener,
|
||
|
|
Arc::new(Mutex::new(Vec::new())),
|
||
|
|
Arc::new(move |method| match method {
|
||
|
|
// A spend is only attempted on a synced wallet.
|
||
|
|
"get_info" => synced_info(),
|
||
|
|
_ => rpc_result(&format!(r#"{{"address":"{addr_hex}","tx_hash":"abc123"}}"#)),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let w = recording_wallet(port);
|
||
|
|
let created = w.create_address().await.expect("create_address");
|
||
|
|
assert!(created.starts_with('8'));
|
||
|
|
|
||
|
|
let txid = w.transfer(addr_hex, 1).await.expect("transfer");
|
||
|
|
assert_eq!(txid, "abc123");
|
||
|
|
}
|
||
|
|
|
||
|
|
#[tokio::test]
|
||
|
|
async fn mock_get_transfers_matches_txid() {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let addr = listener.local_addr().unwrap();
|
||
|
|
let canned = json_rpc_ok(
|
||
|
|
r#"{"in":[{"txid":"deadbeef","amount":5,"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}],"pending":[]}"#,
|
||
|
|
);
|
||
|
|
tokio::spawn(serve_digest_then(listener, canned));
|
||
|
|
let w = Wallet::from_url(&format!("http://ow:[email protected]:{}", addr.port())).unwrap();
|
||
|
|
let rows = w.get_transfers().await.expect("get_transfers");
|
||
|
|
assert!(wallet::transfers_match(
|
||
|
|
&rows,
|
||
|
|
"deadbeef",
|
||
|
|
"5",
|
||
|
|
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
|
||
|
|
));
|
||
|
|
assert!(!wallet::transfers_match(&rows, "nope", "1", "nope"));
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn transfers_match_txid_only_wrong_amount_or_addr_is_false() {
|
||
|
|
let addr = xmr_addr();
|
||
|
|
let rows = [row("deadbeef", "5", &addr)];
|
||
|
|
assert!(!wallet::transfers_match(&rows, "deadbeef", "99", &addr));
|
||
|
|
let other = format!("8{}", "C".repeat(94));
|
||
|
|
assert!(!wallet::transfers_match(&rows, "deadbeef", "5", &other));
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn transfers_match_address_and_amount_wrong_txid_is_false() {
|
||
|
|
let addr = xmr_addr();
|
||
|
|
let rows = [row("deadbeef", "5", &addr)];
|
||
|
|
assert!(!wallet::transfers_match(&rows, "cafebabe", "5", &addr));
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn transfers_match_honest_triple_is_true() {
|
||
|
|
let addr = xmr_addr();
|
||
|
|
let rows = [row("deadbeef", "5", &addr)];
|
||
|
|
assert!(wallet::transfers_match(&rows, "deadbeef", "5", &addr));
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn transfers_match_empty_field_is_false() {
|
||
|
|
let addr = xmr_addr();
|
||
|
|
let rows = [row("deadbeef", "5", &addr)];
|
||
|
|
assert!(!wallet::transfers_match(&rows, "", "5", &addr));
|
||
|
|
assert!(!wallet::transfers_match(&rows, "deadbeef", "", &addr));
|
||
|
|
assert!(!wallet::transfers_match(&rows, "deadbeef", "5", ""));
|
||
|
|
let empty = [row("", "", "")];
|
||
|
|
assert!(!wallet::transfers_match(&empty, "", "", ""));
|
||
|
|
}
|
||
|
|
|
||
|
|
/// ingest_receipt inserts verified=0, then mark_verified iff transfers_match.
|
||
|
|
/// A Noise-signed rcp that cites an unrelated wallet row must stay unverified.
|
||
|
|
#[test]
|
||
|
|
fn ingest_signed_receipt_mismatched_wallet_history_stays_unverified() {
|
||
|
|
let dir = tempfile::tempdir().expect("tempdir");
|
||
|
|
let store = Store::open_at_with_passphrase(dir.path(), "onionwire-test").expect("open");
|
||
|
|
let sk = SigningKey::generate(&mut OsRng);
|
||
|
|
let pk = sk.verifying_key().to_bytes();
|
||
|
|
store.upsert_friend(&pk, "peer.onion", None).unwrap();
|
||
|
|
let addr = xmr_addr();
|
||
|
|
let rcp = pay::sign_receipt(&sk.to_bytes(), "unrelated", "5", &addr, 1).unwrap();
|
||
|
|
assert!(pay::verify_receipt(&pk, &rcp));
|
||
|
|
let id = store
|
||
|
|
.insert_payment(
|
||
|
|
&pk,
|
||
|
|
PaymentWrite {
|
||
|
|
dir: "in",
|
||
|
|
kind: "receipt",
|
||
|
|
amount_atomic: &rcp.amount_atomic,
|
||
|
|
address: &rcp.address,
|
||
|
|
memo: "",
|
||
|
|
txid: Some(&rcp.txid),
|
||
|
|
verified: false,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
.unwrap();
|
||
|
|
let history = [row("unrelated", "99", &format!("8{}", "C".repeat(94)))];
|
||
|
|
if wallet::transfers_match(&history, &rcp.txid, &rcp.amount_atomic, &rcp.address) {
|
||
|
|
store.mark_verified(id).unwrap();
|
||
|
|
}
|
||
|
|
let rows = store.list_payments(&pk).unwrap();
|
||
|
|
assert!(!rows[0].verified);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[tokio::test]
|
||
|
|
async fn oversized_rpc_response_is_err() {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let addr = listener.local_addr().unwrap();
|
||
|
|
let huge = vec![b'A'; 2 * 1024 * 1024];
|
||
|
|
tokio::spawn(async move {
|
||
|
|
let (mut sock, _) = listener.accept().await.expect("accept");
|
||
|
|
let mut buf = vec![0u8; 4096];
|
||
|
|
let _ = sock.read(&mut buf).await;
|
||
|
|
sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n")
|
||
|
|
.await
|
||
|
|
.expect("hdr");
|
||
|
|
sock.write_all(&huge).await.expect("body");
|
||
|
|
});
|
||
|
|
let w = Wallet::from_url(&format!("http://ow:[email protected]:{}", addr.port())).unwrap();
|
||
|
|
let err = w.get_address().await.unwrap_err();
|
||
|
|
let msg = err.to_string().to_ascii_lowercase();
|
||
|
|
assert!(
|
||
|
|
msg.contains("large") || msg.contains("size") || msg.contains("cap"),
|
||
|
|
"got {err}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
!err.to_string().contains("secret"),
|
||
|
|
"password leaked: {err}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// 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 a fully synced wallet answers to `get_info`: the daemon has reached the
|
||
|
|
/// tip and the wallet has scanned it. This is the honest readiness signal.
|
||
|
|
fn synced_info() -> String {
|
||
|
|
rpc_result(r#"{"height":3210000,"target_height":3210000,"synchronized":true}"#)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn recording_wallet(port: u16) -> Wallet {
|
||
|
|
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("url")
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The wallet mock speaks the two methods `/tip` can reach, and refuses the
|
||
|
|
/// local `transfer` before any socket is opened.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn no_spend_mode_refuses_transfer_with_no_rpc_request() {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
let log = Arc::new(Mutex::new(Vec::new()));
|
||
|
|
tokio::spawn(serve_recording(
|
||
|
|
listener,
|
||
|
|
Arc::clone(&log),
|
||
|
|
Arc::new(|_| rpc_result(r#"{"tx_hash":"abc123"}"#)),
|
||
|
|
));
|
||
|
|
let w = recording_wallet(port).with_no_spend(true);
|
||
|
|
assert!(w.no_spend());
|
||
|
|
let err = w
|
||
|
|
.transfer(
|
||
|
|
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||
|
|
1,
|
||
|
|
)
|
||
|
|
.await
|
||
|
|
.unwrap_err()
|
||
|
|
.to_string();
|
||
|
|
assert!(err.to_ascii_lowercase().contains("view-only"), "got {err}");
|
||
|
|
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
||
|
|
let seen = log.lock().expect("log").clone();
|
||
|
|
assert!(seen.is_empty(), "no RPC request may be made: {seen:?}");
|
||
|
|
// Positive control: the recorder is live, so the emptiness above is real.
|
||
|
|
let _ = w.get_address().await;
|
||
|
|
assert!(!log.lock().expect("log").is_empty(), "recorder saw nothing");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// `/pay` (subaddress) and receipt verification (`get_transfers`) keep working
|
||
|
|
/// with the no-spend flag on — only `transfer` is refused.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn no_spend_mode_keeps_invoice_and_receipt_paths_working() {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
let log = Arc::new(Mutex::new(Vec::new()));
|
||
|
|
tokio::spawn(serve_recording(
|
||
|
|
listener,
|
||
|
|
Arc::clone(&log),
|
||
|
|
Arc::new(|method| match method {
|
||
|
|
"create_address" => rpc_result(
|
||
|
|
r#"{"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}"#,
|
||
|
|
),
|
||
|
|
"get_transfers" => rpc_result(
|
||
|
|
r#"{"in":[{"txid":"deadbeef","amount":5,"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}],"pending":[]}"#,
|
||
|
|
),
|
||
|
|
_ => rpc_result(r#"{}"#),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let w = recording_wallet(port).with_no_spend(true);
|
||
|
|
let created = w.create_address().await.expect("create_address");
|
||
|
|
assert!(created.starts_with('8'), "got {created}");
|
||
|
|
let rows = w.get_transfers().await.expect("get_transfers");
|
||
|
|
assert!(wallet::transfers_match(&rows, "deadbeef", "5", &created));
|
||
|
|
let seen = log.lock().expect("log").clone();
|
||
|
|
assert!(
|
||
|
|
seen.iter()
|
||
|
|
.any(|r| r.contains("\"method\":\"create_address\"")),
|
||
|
|
"recorder must have seen the invoice path: {seen:?}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
!seen.iter().any(|r| r.contains("\"method\":\"transfer\"")),
|
||
|
|
"transfer must never be dialed in no-spend mode"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A view-only wallet refuses `transfer` with its own opaque error. The
|
||
|
|
/// pre-transfer signal is `query_key` key_type=spend_key (Monero answers
|
||
|
|
/// WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29), so /tip must say so plainly.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn view_only_wallet_maps_transfer_failure_to_clear_message() {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
let log = Arc::new(Mutex::new(Vec::new()));
|
||
|
|
tokio::spawn(serve_recording(
|
||
|
|
listener,
|
||
|
|
Arc::clone(&log),
|
||
|
|
Arc::new(|method| match method {
|
||
|
|
"query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."),
|
||
|
|
"get_info" => synced_info(),
|
||
|
|
_ => rpc_error(-18, "No transaction created"),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let w = recording_wallet(port);
|
||
|
|
assert!(!w.no_spend());
|
||
|
|
let err = w
|
||
|
|
.transfer(
|
||
|
|
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||
|
|
1,
|
||
|
|
)
|
||
|
|
.await
|
||
|
|
.unwrap_err()
|
||
|
|
.to_string();
|
||
|
|
assert!(err.to_ascii_lowercase().contains("view-only"), "got {err}");
|
||
|
|
let seen = log.lock().expect("log").clone();
|
||
|
|
assert!(
|
||
|
|
seen.iter().any(|r| r.contains("\"method\":\"query_key\"")),
|
||
|
|
"must ask the RPC-side signal: {seen:?}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A spend-capable wallet must keep its real error: no fabricated detection.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn spend_capable_wallet_keeps_the_original_transfer_error() {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
tokio::spawn(serve_recording(
|
||
|
|
listener,
|
||
|
|
Arc::new(Mutex::new(Vec::new())),
|
||
|
|
Arc::new(|method| match method {
|
||
|
|
"query_key" => rpc_result(r#"{"key":"00112233"}"#),
|
||
|
|
"get_info" => synced_info(),
|
||
|
|
_ => rpc_error(-18, "No transaction created"),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let err = recording_wallet(port)
|
||
|
|
.transfer(
|
||
|
|
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||
|
|
1,
|
||
|
|
)
|
||
|
|
.await
|
||
|
|
.unwrap_err()
|
||
|
|
.to_string();
|
||
|
|
assert!(err.contains("No transaction created"), "got {err}");
|
||
|
|
assert!(!err.to_ascii_lowercase().contains("view-only"), "got {err}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Create generates a spend-capable wallet on the RPC; the user never pastes a key.
|
||
|
|
/// Seed is read back once via `query_key mnemonic` for the backup screen.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn create_wallet_does_not_send_a_seed_and_returns_mnemonic() {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
let log = Arc::new(Mutex::new(Vec::new()));
|
||
|
|
tokio::spawn(serve_recording(
|
||
|
|
listener,
|
||
|
|
Arc::clone(&log),
|
||
|
|
Arc::new(|method| match method {
|
||
|
|
"create_wallet" => rpc_result(r#"{}"#),
|
||
|
|
"query_key" => rpc_result(r#"{"key":"lumber tacit lemon ivory risk"}"#),
|
||
|
|
_ => rpc_error(-1, "unexpected method"),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let seed = recording_wallet(port)
|
||
|
|
.create_wallet("onionwire", "hunter2")
|
||
|
|
.await
|
||
|
|
.expect("create_wallet");
|
||
|
|
assert_eq!(seed, "lumber tacit lemon ivory risk");
|
||
|
|
let seen = log.lock().expect("log").clone();
|
||
|
|
let create = seen
|
||
|
|
.iter()
|
||
|
|
.find(|r| r.contains(r#""method":"create_wallet""#))
|
||
|
|
.expect("create_wallet RPC");
|
||
|
|
assert!(
|
||
|
|
!create.contains("lumber") && !create.contains("seed"),
|
||
|
|
"create must not take a seed: {create}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
create.contains(r#""filename":"onionwire""#),
|
||
|
|
"filename missing: {create}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
seen.iter()
|
||
|
|
.any(|r| r.contains(r#""method":"query_key""#) && r.contains("mnemonic")),
|
||
|
|
"must read mnemonic after create: {seen:?}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn create_wallet_empty_filename_or_password_is_local_error() {
|
||
|
|
let w = Wallet::from_url("http://ow:[email protected]:18083").unwrap();
|
||
|
|
let rt = tokio::runtime::Builder::new_current_thread()
|
||
|
|
.enable_all()
|
||
|
|
.build()
|
||
|
|
.unwrap();
|
||
|
|
let err = rt
|
||
|
|
.block_on(w.create_wallet("", "pw"))
|
||
|
|
.unwrap_err()
|
||
|
|
.to_string();
|
||
|
|
assert!(err.contains("filename"), "got {err}");
|
||
|
|
let err = rt
|
||
|
|
.block_on(w.create_wallet("onionwire", ""))
|
||
|
|
.unwrap_err()
|
||
|
|
.to_string();
|
||
|
|
assert!(
|
||
|
|
err.to_ascii_lowercase().contains("password")
|
||
|
|
|| err.to_ascii_lowercase().contains("passphrase"),
|
||
|
|
"got {err}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Import is the only path that takes an existing secret (the 25-word seed).
|
||
|
|
#[tokio::test]
|
||
|
|
async fn restore_wallet_sends_seed_to_restore_deterministic_wallet() {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
let log = Arc::new(Mutex::new(Vec::new()));
|
||
|
|
tokio::spawn(serve_recording(
|
||
|
|
listener,
|
||
|
|
Arc::clone(&log),
|
||
|
|
Arc::new(|method| match method {
|
||
|
|
"restore_deterministic_wallet" => rpc_result(
|
||
|
|
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","seed":"lumber tacit lemon ivory risk"}"#,
|
||
|
|
),
|
||
|
|
_ => rpc_error(-1, "unexpected method"),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
recording_wallet(port)
|
||
|
|
.restore_wallet("onionwire", "hunter2", "lumber tacit lemon ivory risk")
|
||
|
|
.await
|
||
|
|
.expect("restore_wallet");
|
||
|
|
let seen = log.lock().expect("log").clone();
|
||
|
|
let restore = seen
|
||
|
|
.iter()
|
||
|
|
.find(|r| r.contains(r#""method":"restore_deterministic_wallet""#))
|
||
|
|
.expect("restore RPC");
|
||
|
|
assert!(
|
||
|
|
restore.contains("lumber tacit lemon ivory risk"),
|
||
|
|
"seed missing: {restore}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn restore_wallet_empty_seed_is_local_error() {
|
||
|
|
let w = Wallet::from_url("http://ow:[email protected]:18083").unwrap();
|
||
|
|
let err = tokio::runtime::Builder::new_current_thread()
|
||
|
|
.enable_all()
|
||
|
|
.build()
|
||
|
|
.unwrap()
|
||
|
|
.block_on(w.restore_wallet("onionwire", "pw", " "))
|
||
|
|
.unwrap_err()
|
||
|
|
.to_string();
|
||
|
|
assert!(err.to_ascii_lowercase().contains("seed"), "got {err}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// F5 must not regress: an open RPC (HTTP 200, no Digest challenge) is refused.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn open_rpc_without_digest_challenge_is_still_refused() {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
let canned = http_200_body(
|
||
|
|
r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}}"#,
|
||
|
|
);
|
||
|
|
tokio::spawn(async move {
|
||
|
|
let (mut sock, _) = listener.accept().await.expect("accept");
|
||
|
|
let mut buf = vec![0u8; 4096];
|
||
|
|
let _ = sock.read(&mut buf).await;
|
||
|
|
let _ = sock.write_all(canned.as_bytes()).await;
|
||
|
|
});
|
||
|
|
let err = recording_wallet(port)
|
||
|
|
.get_address()
|
||
|
|
.await
|
||
|
|
.unwrap_err()
|
||
|
|
.to_string();
|
||
|
|
assert!(err.to_ascii_lowercase().contains("digest"), "got {err}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// `ONIONWIRE_WALLET_NO_SPEND` is the operator-facing switch.
|
||
|
|
#[test]
|
||
|
|
fn from_env_reads_no_spend_flag() {
|
||
|
|
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||
|
|
unsafe {
|
||
|
|
std::env::set_var("ONIONWIRE_WALLET_RPC", "http://ow:[email protected]:18083");
|
||
|
|
std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "1");
|
||
|
|
}
|
||
|
|
let on = Wallet::from_env();
|
||
|
|
assert!(on.no_spend(), "flag 1 must mean no-spend");
|
||
|
|
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "true") };
|
||
|
|
assert!(Wallet::from_env().no_spend(), "\"true\" must mean no-spend");
|
||
|
|
for off in ["0", "no", "off"] {
|
||
|
|
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", off) };
|
||
|
|
assert!(!Wallet::from_env().no_spend(), "{off} must be off");
|
||
|
|
}
|
||
|
|
unsafe {
|
||
|
|
std::env::remove_var("ONIONWIRE_WALLET_NO_SPEND");
|
||
|
|
std::env::remove_var("ONIONWIRE_WALLET_RPC");
|
||
|
|
}
|
||
|
|
assert!(!Wallet::from_env().no_spend(), "unset must be off");
|
||
|
|
}
|
||
|
|
|
||
|
|
fn digest_401(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}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// 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_info" => synced_info(),
|
||
|
|
_ => 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_info" => {
|
||
|
|
rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#)
|
||
|
|
}
|
||
|
|
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let w = recording_wallet(port);
|
||
|
|
assert!(
|
||
|
|
!w.chain_ready().await.expect("get_info"),
|
||
|
|
"must not be ready"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
!w.can_verify_receipts().await,
|
||
|
|
"an unsynced wallet cannot verify receipts"
|
||
|
|
);
|
||
|
|
|
||
|
|
let err = w.transfer(SPEND_ADDR, 1).await.unwrap_err().to_string();
|
||
|
|
assert!(err.to_ascii_lowercase().contains("not synced"), "got {err}");
|
||
|
|
let seen = log.lock().expect("log").clone();
|
||
|
|
assert!(
|
||
|
|
!seen.iter().any(|r| r.contains("\"method\":\"transfer\"")),
|
||
|
|
"a not-ready wallet must not attempt a spend: {seen:?}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A missing/absent `synchronized` (or a wallet behind the daemon) is not-ready,
|
||
|
|
/// never a silent pass. Fail closed.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn missing_or_behind_synchronized_is_not_ready() {
|
||
|
|
for info in [
|
||
|
|
r#"{"height":10}"#,
|
||
|
|
r#"{"height":100,"target_height":200,"synchronized":true}"#,
|
||
|
|
r#"{"height":0,"target_height":0,"synchronized":true}"#,
|
||
|
|
r#"{"synchronized":"true"}"#,
|
||
|
|
] {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
let canned = rpc_result(info);
|
||
|
|
tokio::spawn(serve_recording(
|
||
|
|
listener,
|
||
|
|
Arc::new(Mutex::new(Vec::new())),
|
||
|
|
Arc::new(move |_| canned.clone()),
|
||
|
|
));
|
||
|
|
let w = recording_wallet(port);
|
||
|
|
assert!(
|
||
|
|
!w.chain_ready().await.expect("get_info"),
|
||
|
|
"{info} must not read as ready"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
#[tokio::test]
|
||
|
|
async fn synced_wallet_is_ready_and_spends() {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
tokio::spawn(serve_recording(
|
||
|
|
listener,
|
||
|
|
Arc::new(Mutex::new(Vec::new())),
|
||
|
|
Arc::new(|method| match method {
|
||
|
|
"get_info" => synced_info(),
|
||
|
|
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let w = recording_wallet(port);
|
||
|
|
assert!(w.chain_ready().await.expect("get_info"));
|
||
|
|
assert!(w.can_verify_receipts().await);
|
||
|
|
assert_eq!(w.transfer(SPEND_ADDR, 1).await.expect("transfer"), "abc123");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// `spend_ready` is the stricter signal for the spend UI: synced *and* holding
|
||
|
|
/// unlocked funds. Zero unlocked balance is not spend-ready.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn spend_ready_needs_an_unlocked_balance() {
|
||
|
|
for (unlocked, ready) in [("0", false), ("5", true)] {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
let balance = rpc_result(&format!(
|
||
|
|
r#"{{"balance":"{unlocked}","unlocked_balance":"{unlocked}"}}"#
|
||
|
|
));
|
||
|
|
tokio::spawn(serve_recording(
|
||
|
|
listener,
|
||
|
|
Arc::new(Mutex::new(Vec::new())),
|
||
|
|
Arc::new(move |method| match method {
|
||
|
|
"get_info" => synced_info(),
|
||
|
|
"get_balance" => balance.clone(),
|
||
|
|
_ => rpc_result(r#"{}"#),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let w = recording_wallet(port);
|
||
|
|
assert_eq!(w.spend_ready().await.expect("spend_ready"), ready);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The honest not-ready state: a receipt whose history *would* match stays
|
||
|
|
/// verified=0 while the wallet is unsynced. (node.rs gates on the same
|
||
|
|
/// predicate via `can_verify_receipts`.)
|
||
|
|
#[tokio::test]
|
||
|
|
async fn unsynced_wallet_leaves_a_matching_receipt_unverified() {
|
||
|
|
let dir = tempfile::tempdir().expect("tempdir");
|
||
|
|
let store = Store::open_at_with_passphrase(dir.path(), "onionwire-test").expect("open");
|
||
|
|
let sk = SigningKey::generate(&mut OsRng);
|
||
|
|
let pk = sk.verifying_key().to_bytes();
|
||
|
|
store.upsert_friend(&pk, "peer.onion", None).unwrap();
|
||
|
|
let addr = xmr_addr();
|
||
|
|
let rcp = pay::sign_receipt(&sk.to_bytes(), "deadbeef", "5", &addr, 1).unwrap();
|
||
|
|
let id = store
|
||
|
|
.insert_payment(
|
||
|
|
&pk,
|
||
|
|
PaymentWrite {
|
||
|
|
dir: "in",
|
||
|
|
kind: "receipt",
|
||
|
|
amount_atomic: &rcp.amount_atomic,
|
||
|
|
address: &rcp.address,
|
||
|
|
memo: "",
|
||
|
|
txid: Some(&rcp.txid),
|
||
|
|
verified: false,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
.unwrap();
|
||
|
|
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
let addr_owned = addr.clone();
|
||
|
|
tokio::spawn(serve_recording(
|
||
|
|
listener,
|
||
|
|
Arc::new(Mutex::new(Vec::new())),
|
||
|
|
Arc::new(move |method| match method {
|
||
|
|
"get_info" => {
|
||
|
|
rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#)
|
||
|
|
}
|
||
|
|
"get_transfers" => rpc_result(&format!(
|
||
|
|
r#"{{"in":[{{"txid":"deadbeef","amount":5,"address":"{addr_owned}"}}],"pending":[]}}"#
|
||
|
|
)),
|
||
|
|
_ => rpc_result(r#"{}"#),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let w = recording_wallet(port);
|
||
|
|
|
||
|
|
// The same shape node.rs::ingest_receipt runs.
|
||
|
|
if w.can_verify_receipts().await
|
||
|
|
&& let Ok(rows) = w.get_transfers().await
|
||
|
|
&& wallet::transfers_match(&rows, &rcp.txid, &rcp.amount_atomic, &rcp.address)
|
||
|
|
{
|
||
|
|
store.mark_verified(id).unwrap();
|
||
|
|
}
|
||
|
|
assert!(
|
||
|
|
!store.list_payments(&pk).unwrap()[0].verified,
|
||
|
|
"an unsynced wallet must leave the receipt unverified"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Chain-dependent calls get a longer budget than local wallet-management calls,
|
||
|
|
/// and the budget is the backend's to set — not a hard-coded 5s.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn chain_calls_get_a_longer_budget_than_local_calls() {
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
tokio::spawn(serve_delayed(
|
||
|
|
listener,
|
||
|
|
std::time::Duration::from_millis(400),
|
||
|
|
));
|
||
|
|
let w = recording_wallet(port).with_timeouts(
|
||
|
|
std::time::Duration::from_millis(150),
|
||
|
|
std::time::Duration::from_millis(2000),
|
||
|
|
);
|
||
|
|
let err = w.get_address().await.unwrap_err().to_string();
|
||
|
|
assert!(
|
||
|
|
err.to_ascii_lowercase().contains("timed out"),
|
||
|
|
"the local call must hit the short budget: {err}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
w.chain_ready()
|
||
|
|
.await
|
||
|
|
.expect("get_info within the chain budget"),
|
||
|
|
"chain calls must outlast daemon latency"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
// ---------------------------------------------------------------------------
|
||
|
|
// Stored wallet config (F7): read at boot, sealed at rest, never in an error.
|
||
|
|
// ---------------------------------------------------------------------------
|
||
|
|
|
||
|
|
/// The exact refusal copy the TUI asserts. Pinned here as literals so a copy
|
||
|
|
/// change is a test failure, and cross-checked against the constants the guard
|
||
|
|
/// returns.
|
||
|
|
#[test]
|
||
|
|
fn readiness_guard_refuses_each_state_with_exact_copy() {
|
||
|
|
assert_eq!(
|
||
|
|
NOT_CONFIGURED_MSG,
|
||
|
|
"wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC"
|
||
|
|
);
|
||
|
|
assert_eq!(
|
||
|
|
NOT_CONNECTED_MSG,
|
||
|
|
"wallet not connected — check endpoint, login, daemon"
|
||
|
|
);
|
||
|
|
assert_eq!(Readiness::NotConfigured.refusal(), Some(NOT_CONFIGURED_MSG));
|
||
|
|
assert_eq!(Readiness::NotConnected.refusal(), Some(NOT_CONNECTED_MSG));
|
||
|
|
assert_eq!(Readiness::NoSpend.refusal(), Some(VIEW_ONLY_MSG));
|
||
|
|
assert_eq!(Readiness::Ready.refusal(), None);
|
||
|
|
|
||
|
|
// not configured beats everything else, whatever else is true.
|
||
|
|
assert_eq!(
|
||
|
|
readiness(false, false, false, true),
|
||
|
|
Readiness::NotConfigured
|
||
|
|
);
|
||
|
|
assert_eq!(readiness(false, true, true, true), Readiness::NotConfigured);
|
||
|
|
// configured but not reachable.
|
||
|
|
assert_eq!(readiness(true, false, false, true), Readiness::NotConnected);
|
||
|
|
assert_eq!(
|
||
|
|
readiness(true, false, false, false),
|
||
|
|
Readiness::NotConnected
|
||
|
|
);
|
||
|
|
// view-only: /tip is refused on its own terms, /pay keeps working.
|
||
|
|
assert_eq!(readiness(true, true, true, true), Readiness::NoSpend);
|
||
|
|
assert_eq!(readiness(true, false, true, true), Readiness::NoSpend);
|
||
|
|
assert_eq!(readiness(true, true, true, false), Readiness::Ready);
|
||
|
|
// allowed only when configured + connected + spend-capable.
|
||
|
|
assert_eq!(readiness(true, true, false, true), Readiness::Ready);
|
||
|
|
assert!(!readiness(true, false, false, true).is_ready());
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn wallet_config_debug_never_prints_the_login() {
|
||
|
|
let cfg = WalletConfig::new("http://127.0.0.1:18083", "ow:hunter2XYZ", true);
|
||
|
|
let dbg = format!("{cfg:?}");
|
||
|
|
assert!(!dbg.contains("hunter2XYZ"), "debug leaked the login: {dbg}");
|
||
|
|
assert!(dbg.contains("127.0.0.1:18083"), "{dbg}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Stored config is what boot reads; env is the migration/fallback path.
|
||
|
|
#[test]
|
||
|
|
fn boot_reads_stored_config_over_env_and_falls_back_to_env() {
|
||
|
|
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||
|
|
unsafe {
|
||
|
|
std::env::set_var("ONIONWIRE_WALLET_RPC", "http://ow:[email protected]:18083");
|
||
|
|
std::env::remove_var("ONIONWIRE_WALLET_RPC_LOGIN");
|
||
|
|
std::env::remove_var("ONIONWIRE_WALLET_NO_SPEND");
|
||
|
|
}
|
||
|
|
|
||
|
|
let stored = WalletConfig::new("http://127.0.0.1:18084", "ow:storedpass", true);
|
||
|
|
let w = Wallet::for_boot(Some(&stored));
|
||
|
|
assert!(w.configured(), "stored config must configure the wallet");
|
||
|
|
assert!(w.no_spend(), "stored no_spend must win over env");
|
||
|
|
let in_use = w.config().expect("configured wallet has a config");
|
||
|
|
assert_eq!(in_use.rpc_url, "http://127.0.0.1:18084/json_rpc");
|
||
|
|
assert_eq!(in_use.rpc_login.as_str(), "ow:storedpass");
|
||
|
|
assert!(!in_use.rpc_url.contains("storedpass"), "{}", in_use.rpc_url);
|
||
|
|
|
||
|
|
// No stored config: the env vars still boot headless / pre-F7 installs.
|
||
|
|
let w = Wallet::for_boot(None);
|
||
|
|
assert!(w.configured());
|
||
|
|
let in_use = w.config().expect("env wallet has a config");
|
||
|
|
assert_eq!(in_use.rpc_url, "http://127.0.0.1:18083/json_rpc");
|
||
|
|
assert_eq!(in_use.rpc_login.as_str(), "ow:envpass");
|
||
|
|
assert!(!w.no_spend());
|
||
|
|
|
||
|
|
// A stored config that cannot be used falls through to env, not to a dial.
|
||
|
|
let broken = WalletConfig::new("http://example.com:18083", "ow:x", false);
|
||
|
|
assert!(Wallet::for_boot(Some(&broken)).configured());
|
||
|
|
|
||
|
|
// Neither: disabled, and the refusal says so.
|
||
|
|
unsafe {
|
||
|
|
std::env::remove_var("ONIONWIRE_WALLET_RPC");
|
||
|
|
}
|
||
|
|
let w = Wallet::for_boot(None);
|
||
|
|
assert!(!w.configured());
|
||
|
|
assert!(w.config().is_none());
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn malformed_config_errors_never_carry_the_password() {
|
||
|
|
let cfg = WalletConfig::new("http://example.com:18083", "ow:hunter2XYZ", false);
|
||
|
|
let err = Wallet::from_config(&cfg).unwrap_err().to_string();
|
||
|
|
assert!(!err.contains("hunter2XYZ"), "password leaked: {err}");
|
||
|
|
let cfg = WalletConfig::new("http://127.0.0.1:18083", "", false);
|
||
|
|
let err = Wallet::from_config(&cfg).unwrap_err().to_string();
|
||
|
|
assert!(!err.is_empty());
|
||
|
|
let cfg = WalletConfig::new("", "ow:hunter2XYZ", false);
|
||
|
|
assert!(
|
||
|
|
Wallet::from_config(&cfg).is_err(),
|
||
|
|
"empty url is not a config"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// One row, sealed with the store data key on top of SQLCipher, and nothing in
|
||
|
|
/// the clear on disk.
|
||
|
|
#[test]
|
||
|
|
fn stored_wallet_config_round_trips_and_the_login_is_sealed_on_disk() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let store = Store::open_at_with_passphrase(dir.path(), "cfg-pass").unwrap();
|
||
|
|
assert!(
|
||
|
|
store.load_wallet_config().unwrap().is_none(),
|
||
|
|
"a fresh store has no wallet config"
|
||
|
|
);
|
||
|
|
|
||
|
|
let cfg = WalletConfig::new("http://127.0.0.1:18083", "ow:cfg-secret-xyz", false);
|
||
|
|
store.save_wallet_config(&cfg).unwrap();
|
||
|
|
let got = store.load_wallet_config().unwrap().expect("stored config");
|
||
|
|
assert_eq!(got.rpc_url, "http://127.0.0.1:18083");
|
||
|
|
assert_eq!(got.rpc_login.as_str(), "ow:cfg-secret-xyz");
|
||
|
|
assert!(!got.no_spend);
|
||
|
|
|
||
|
|
// Saving again replaces the single row.
|
||
|
|
let cfg2 = WalletConfig::new("http://127.0.0.1:18085", "ow:second-secret-abc", true);
|
||
|
|
store.save_wallet_config(&cfg2).unwrap();
|
||
|
|
let got = store.load_wallet_config().unwrap().expect("stored config");
|
||
|
|
assert_eq!(got.rpc_url, "http://127.0.0.1:18085");
|
||
|
|
assert_eq!(got.rpc_login.as_str(), "ow:second-secret-abc");
|
||
|
|
assert!(got.no_spend);
|
||
|
|
|
||
|
|
// An empty URL clears the stored config instead of storing a half-config.
|
||
|
|
store
|
||
|
|
.save_wallet_config(&WalletConfig::new("", "", false))
|
||
|
|
.unwrap();
|
||
|
|
assert!(store.load_wallet_config().unwrap().is_none());
|
||
|
|
|
||
|
|
store.save_wallet_config(&cfg).unwrap();
|
||
|
|
store.checkpoint_wal().unwrap();
|
||
|
|
drop(store);
|
||
|
|
for name in ["onionwire.db", "onionwire.db-wal", "onionwire.db-shm"] {
|
||
|
|
let Ok(bytes) = std::fs::read(dir.path().join(name)) else {
|
||
|
|
continue;
|
||
|
|
};
|
||
|
|
assert!(
|
||
|
|
!contains_bytes(&bytes, b"cfg-secret-xyz"),
|
||
|
|
"{name} holds the RPC login in the clear"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
// The readers come back to a config that still decrypts.
|
||
|
|
let store = Store::open_at_with_passphrase(dir.path(), "cfg-pass").unwrap();
|
||
|
|
let got = store
|
||
|
|
.load_wallet_config()
|
||
|
|
.unwrap()
|
||
|
|
.expect("reopened config");
|
||
|
|
assert_eq!(got.rpc_login.as_str(), "ow:cfg-secret-xyz");
|
||
|
|
}
|
||
|
|
|
||
|
|
fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
|
||
|
|
haystack.windows(needle.len()).any(|w| w == needle)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The one-shot probe the config screen's Test button fires. It is against the
|
||
|
|
/// *typed* endpoint, so it must not touch the live wallet.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn ping_reports_success_and_sanitizes_failures() {
|
||
|
|
// A reachable endpoint: digest challenge, then get_address.
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
let canned = json_rpc_ok(
|
||
|
|
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
|
||
|
|
);
|
||
|
|
tokio::spawn(serve_digest_then(listener, canned));
|
||
|
|
let ok = wallet::Wallet::ping(&format!("http://127.0.0.1:{port}"), "ow:ping-secret-xyz").await;
|
||
|
|
assert!(ok.ok, "{ok:?}");
|
||
|
|
assert_eq!(ok.status, "connected");
|
||
|
|
assert_eq!(ok.error, None);
|
||
|
|
assert!(!format!("{ok:?}").contains("ping-secret-xyz"));
|
||
|
|
|
||
|
|
// Nothing listening: refused, and the reason carries no password.
|
||
|
|
let dead = freed_loopback_port();
|
||
|
|
let bad = wallet::Wallet::ping(&format!("http://127.0.0.1:{dead}"), "ow:ping-secret-xyz").await;
|
||
|
|
assert!(!bad.ok, "{bad:?}");
|
||
|
|
assert!(bad.error.is_some(), "{bad:?}");
|
||
|
|
assert!(
|
||
|
|
!bad.error.as_deref().unwrap().contains("ping-secret-xyz"),
|
||
|
|
"{bad:?}"
|
||
|
|
);
|
||
|
|
|
||
|
|
// A non-loopback host is refused locally, before any dial.
|
||
|
|
let off = wallet::Wallet::ping("http://node.example.com:18083", "ow:ping-secret-xyz").await;
|
||
|
|
assert!(!off.ok);
|
||
|
|
assert!(
|
||
|
|
!off.error
|
||
|
|
.as_deref()
|
||
|
|
.unwrap_or_default()
|
||
|
|
.contains("ping-secret-xyz"),
|
||
|
|
"{off:?}"
|
||
|
|
);
|
||
|
|
|
||
|
|
// An open RPC (no digest challenge) is refused with no password in it.
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
let open = http_200_body(r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4AA"}}"#);
|
||
|
|
tokio::spawn(async move {
|
||
|
|
let (mut sock, _) = listener.accept().await.expect("accept");
|
||
|
|
let mut buf = vec![0u8; 4096];
|
||
|
|
let _ = sock.read(&mut buf).await;
|
||
|
|
let _ = sock.write_all(open.as_bytes()).await;
|
||
|
|
});
|
||
|
|
let open =
|
||
|
|
wallet::Wallet::ping(&format!("http://127.0.0.1:{port}"), "ow:ping-secret-xyz").await;
|
||
|
|
assert!(!open.ok, "{open:?}");
|
||
|
|
assert!(
|
||
|
|
open.error.as_deref().unwrap_or_default().contains("digest"),
|
||
|
|
"{open:?}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// `WalletStatus.connected` comes from a probe, never from config-existence —
|
||
|
|
/// and a lower layer that echoes the password into an RPC error cannot leak it
|
||
|
|
/// into the status line.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn status_is_connected_only_after_a_successful_probe() {
|
||
|
|
// Configured but never probed: connected is false, config is not reachability.
|
||
|
|
let idle = WalletStatus::idle(true);
|
||
|
|
assert!(idle.configured());
|
||
|
|
assert!(!idle.connected, "config exists is not reachability");
|
||
|
|
assert_eq!(idle.balance_line, "—");
|
||
|
|
assert_eq!(idle.receive_address, "—");
|
||
|
|
|
||
|
|
// A successful probe: connected, address + balance filled in.
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
tokio::spawn(serve_recording(
|
||
|
|
listener,
|
||
|
|
Arc::new(Mutex::new(Vec::new())),
|
||
|
|
Arc::new(|method: &str| match method {
|
||
|
|
"get_address" => rpc_result(
|
||
|
|
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
|
||
|
|
),
|
||
|
|
"get_balance" => rpc_result(r#"{"balance":"123456"}"#),
|
||
|
|
_ => rpc_result("{}"),
|
||
|
|
}),
|
||
|
|
));
|
||
|
|
let w = recording_wallet(port);
|
||
|
|
let ok = w.status().await;
|
||
|
|
assert!(ok.configured() && ok.connected, "{ok:?}");
|
||
|
|
assert_eq!(ok.last_error, None);
|
||
|
|
assert_eq!(ok.balance_line, "123456 piconero");
|
||
|
|
assert!(ok.receive_address.starts_with('4'), "{ok:?}");
|
||
|
|
|
||
|
|
// A probe that fails keeps configured=true and turns connected off.
|
||
|
|
let dead = freed_loopback_port();
|
||
|
|
let down = Wallet::from_url(&format!("http://ow:[email protected]:{dead}")).unwrap();
|
||
|
|
let bad = down.status().await;
|
||
|
|
assert!(bad.configured(), "{bad:?}");
|
||
|
|
assert!(!bad.connected, "{bad:?}");
|
||
|
|
assert!(bad.last_error.is_some(), "{bad:?}");
|
||
|
|
assert_eq!(bad.balance_line, "—");
|
||
|
|
assert_eq!(bad.receive_address, "—");
|
||
|
|
|
||
|
|
// An RPC error message that repeats the password is redacted before display.
|
||
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
let leaky = http_200_body(&rpc_error(-1, "auth failed for ow:leak-secret-xyz"));
|
||
|
|
tokio::spawn(serve_digest_then(listener, leaky));
|
||
|
|
let w = Wallet::from_url(&format!("http://ow:[email protected]:{port}")).unwrap();
|
||
|
|
let leak = w.status().await;
|
||
|
|
assert!(!leak.connected, "{leak:?}");
|
||
|
|
let err = leak.last_error.expect("failure reason");
|
||
|
|
assert!(!err.contains("leak-secret-xyz"), "password leaked: {err}");
|
||
|
|
assert!(err.contains("<redacted>"), "{err}");
|
||
|
|
assert!(
|
||
|
|
err.chars().count() <= 121,
|
||
|
|
"status copy must stay short: {err}"
|
||
|
|
);
|
||
|
|
|
||
|
|
// Nothing configured at all.
|
||
|
|
let none = Wallet::disabled().status().await;
|
||
|
|
assert!(!none.configured() && !none.connected, "{none:?}");
|
||
|
|
}
|
||
|
|
|
||
|
|
// 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"
|
||
|
|
);
|
||
|
|
}
|