onionwire/tests/wallet.rs

1356 lines
51 KiB
Rust
Raw Permalink Normal View History

//! 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;
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard The only input path for the wallet was env. Add the same three remote-mode fields as stored config so the F7 screen can set them and headless runs read one source of truth: - `wallet_config` table in the encrypted store (one row; the login is sealed with the store data key under `onionwire/wallet-config/v1`, on top of SQLCipher). Empty URL clears it. `Store::load_wallet_config` / `save_wallet_config`. - `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which prefers stored config, falls back to env, and refuses to dial a bad stored endpoint. Node::start* now reads the store before constructing the wallet. - `WalletStatus { configured, connected, last_error, balance_line, receive_address }`: `connected` only ever comes from a probe (`Wallet::status`, get_address + get_balance); config alone leaves it false. `Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the probe that folds into it. - One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status, error }` for the Test-connection button: same loopback/digest rules, errors redacted and capped. - `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus `Node::wallet_readiness` (async, block_on-friendly): not configured → NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any dial; configured but not connected → NOT_CONNECTED_MSG; else ready. - `Node::wallet_save_config` persists, validates first, then re-reads so the live wallet and snapshot follow a Save without a restart. - `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the wallet can be re-pointed mid-session. Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not wired here. docs/WALLET.md documents the stored config, boot precedence and the exact guard copy. Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence, sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
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() {
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
let addr_hex = "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
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'));
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
let txid = w.transfer(addr_hex, 1).await.expect("transfer");
assert_eq!(txid, "abc123");
}
#[tokio::test]
async fn mock_get_transfers_matches_txid() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let canned = json_rpc_ok(
r#"{"in":[{"txid":"deadbeef","amount":5,"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}],"pending":[]}"#,
);
tokio::spawn(serve_digest_then(listener, canned));
let w = Wallet::from_url(&format!("http://ow:[email protected]:{}", addr.port())).unwrap();
let rows = w.get_transfers().await.expect("get_transfers");
assert!(wallet::transfers_match(
&rows,
"deadbeef",
"5",
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
));
assert!(!wallet::transfers_match(&rows, "nope", "1", "nope"));
}
#[test]
fn transfers_match_txid_only_wrong_amount_or_addr_is_false() {
let addr = xmr_addr();
let rows = [row("deadbeef", "5", &addr)];
assert!(!wallet::transfers_match(&rows, "deadbeef", "99", &addr));
let other = format!("8{}", "C".repeat(94));
assert!(!wallet::transfers_match(&rows, "deadbeef", "5", &other));
}
#[test]
fn transfers_match_address_and_amount_wrong_txid_is_false() {
let addr = xmr_addr();
let rows = [row("deadbeef", "5", &addr)];
assert!(!wallet::transfers_match(&rows, "cafebabe", "5", &addr));
}
#[test]
fn transfers_match_honest_triple_is_true() {
let addr = xmr_addr();
let rows = [row("deadbeef", "5", &addr)];
assert!(wallet::transfers_match(&rows, "deadbeef", "5", &addr));
}
#[test]
fn transfers_match_empty_field_is_false() {
let addr = xmr_addr();
let rows = [row("deadbeef", "5", &addr)];
assert!(!wallet::transfers_match(&rows, "", "5", &addr));
assert!(!wallet::transfers_match(&rows, "deadbeef", "", &addr));
assert!(!wallet::transfers_match(&rows, "deadbeef", "5", ""));
let empty = [row("", "", "")];
assert!(!wallet::transfers_match(&empty, "", "", ""));
}
/// ingest_receipt inserts verified=0, then mark_verified iff transfers_match.
/// A Noise-signed rcp that cites an unrelated wallet row must stay unverified.
#[test]
fn ingest_signed_receipt_mismatched_wallet_history_stays_unverified() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "onionwire-test").expect("open");
let sk = SigningKey::generate(&mut OsRng);
let pk = sk.verifying_key().to_bytes();
store.upsert_friend(&pk, "peer.onion", None).unwrap();
let addr = xmr_addr();
let rcp = pay::sign_receipt(&sk.to_bytes(), "unrelated", "5", &addr, 1).unwrap();
assert!(pay::verify_receipt(&pk, &rcp));
let id = store
.insert_payment(
&pk,
PaymentWrite {
dir: "in",
kind: "receipt",
amount_atomic: &rcp.amount_atomic,
address: &rcp.address,
memo: "",
txid: Some(&rcp.txid),
verified: false,
},
)
.unwrap();
let history = [row("unrelated", "99", &format!("8{}", "C".repeat(94)))];
if wallet::transfers_match(&history, &rcp.txid, &rcp.amount_atomic, &rcp.address) {
store.mark_verified(id).unwrap();
}
let rows = store.list_payments(&pk).unwrap();
assert!(!rows[0].verified);
}
#[tokio::test]
async fn oversized_rpc_response_is_err() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let huge = vec![b'A'; 2 * 1024 * 1024];
tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.expect("accept");
let mut buf = vec![0u8; 4096];
let _ = sock.read(&mut buf).await;
sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n")
.await
.expect("hdr");
sock.write_all(&huge).await.expect("body");
});
let w = Wallet::from_url(&format!("http://ow:[email protected]:{}", addr.port())).unwrap();
let err = w.get_address().await.unwrap_err();
let msg = err.to_string().to_ascii_lowercase();
assert!(
msg.contains("large") || msg.contains("size") || msg.contains("cap"),
"got {err}"
);
assert!(
!err.to_string().contains("secret"),
"password leaked: {err}"
);
}
/// Records every request the client sends, answers the Digest challenge and
/// then replies per RPC method. Lets a test assert on the *request log*.
async fn serve_recording(
listener: TcpListener,
log: Arc<Mutex<Vec<String>>>,
reply: Arc<dyn Fn(&str) -> String + Send + Sync>,
) {
loop {
let Ok((mut sock, _)) = listener.accept().await else {
return;
};
let mut buf = vec![0u8; 8192];
let n = sock.read(&mut buf).await.unwrap_or(0);
let req = String::from_utf8_lossy(&buf[..n]).to_string();
log.lock().expect("log").push(req.clone());
if req.contains("Authorization:") {
let body = reply(&rpc_method(&req));
let _ = sock.write_all(http_200_body(&body).as_bytes()).await;
} else {
let _ = sock.write_all(digest_401().as_bytes()).await;
}
}
}
fn rpc_method(req: &str) -> String {
let body = req.split_once("\r\n\r\n").map(|(_, b)| b).unwrap_or(req);
serde_json::from_str::<serde_json::Value>(body.trim())
.ok()
.and_then(|v| v.get("method").and_then(|m| m.as_str()).map(str::to_string))
.unwrap_or_default()
}
fn http_200_body(body: &str) -> String {
format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
}
fn rpc_error(code: i64, message: &str) -> String {
format!(r#"{{"jsonrpc":"2.0","id":"0","error":{{"code":{code},"message":"{message}"}}}}"#)
}
/// JSON-RPC body only (the server wraps it in an HTTP 200).
fn rpc_result(result: &str) -> String {
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#)
}
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// 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();
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard The only input path for the wallet was env. Add the same three remote-mode fields as stored config so the F7 screen can set them and headless runs read one source of truth: - `wallet_config` table in the encrypted store (one row; the login is sealed with the store data key under `onionwire/wallet-config/v1`, on top of SQLCipher). Empty URL clears it. `Store::load_wallet_config` / `save_wallet_config`. - `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which prefers stored config, falls back to env, and refuses to dial a bad stored endpoint. Node::start* now reads the store before constructing the wallet. - `WalletStatus { configured, connected, last_error, balance_line, receive_address }`: `connected` only ever comes from a probe (`Wallet::status`, get_address + get_balance); config alone leaves it false. `Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the probe that folds into it. - One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status, error }` for the Test-connection button: same loopback/digest rules, errors redacted and capped. - `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus `Node::wallet_readiness` (async, block_on-friendly): not configured → NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any dial; configured but not connected → NOT_CONNECTED_MSG; else ready. - `Node::wallet_save_config` persists, validates first, then re-reads so the live wallet and snapshot follow a Save without a restart. - `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the wallet can be re-pointed mid-session. Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not wired here. docs/WALLET.md documents the stored config, boot precedence and the exact guard copy. Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence, sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
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."),
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
"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"}"#),
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
"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!(
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard The only input path for the wallet was env. Add the same three remote-mode fields as stored config so the F7 screen can set them and headless runs read one source of truth: - `wallet_config` table in the encrypted store (one row; the login is sealed with the store data key under `onionwire/wallet-config/v1`, on top of SQLCipher). Empty URL clears it. `Store::load_wallet_config` / `save_wallet_config`. - `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which prefers stored config, falls back to env, and refuses to dial a bad stored endpoint. Node::start* now reads the store before constructing the wallet. - `WalletStatus { configured, connected, last_error, balance_line, receive_address }`: `connected` only ever comes from a probe (`Wallet::status`, get_address + get_balance); config alone leaves it false. `Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the probe that folds into it. - One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status, error }` for the Test-connection button: same loopback/digest rules, errors redacted and capped. - `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus `Node::wallet_readiness` (async, block_on-friendly): not configured → NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any dial; configured but not connected → NOT_CONNECTED_MSG; else ready. - `Node::wallet_save_config` persists, validates first, then re-reads so the live wallet and snapshot follow a Save without a restart. - `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the wallet can be re-pointed mid-session. Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not wired here. docs/WALLET.md documents the stored config, boot precedence and the exact guard copy. Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence, sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
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 {
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard The only input path for the wallet was env. Add the same three remote-mode fields as stored config so the F7 screen can set them and headless runs read one source of truth: - `wallet_config` table in the encrypted store (one row; the login is sealed with the store data key under `onionwire/wallet-config/v1`, on top of SQLCipher). Empty URL clears it. `Store::load_wallet_config` / `save_wallet_config`. - `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which prefers stored config, falls back to env, and refuses to dial a bad stored endpoint. Node::start* now reads the store before constructing the wallet. - `WalletStatus { configured, connected, last_error, balance_line, receive_address }`: `connected` only ever comes from a probe (`Wallet::status`, get_address + get_balance); config alone leaves it false. `Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the probe that folds into it. - One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status, error }` for the Test-connection button: same loopback/digest rules, errors redacted and capped. - `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus `Node::wallet_readiness` (async, block_on-friendly): not configured → NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any dial; configured but not connected → NOT_CONNECTED_MSG; else ready. - `Node::wallet_save_config` persists, validates first, then re-reads so the live wallet and snapshot follow a Save without a restart. - `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the wallet can be re-pointed mid-session. Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not wired here. docs/WALLET.md documents the stored config, boot precedence and the exact guard copy. Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence, sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
"restore_deterministic_wallet" => rpc_result(
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","seed":"lumber tacit lemon ivory risk"}"#,
),
_ => rpc_error(-1, "unexpected method"),
}),
));
recording_wallet(port)
.restore_wallet("onionwire", "hunter2", "lumber tacit lemon ivory risk")
.await
.expect("restore_wallet");
let seen = log.lock().expect("log").clone();
let restore = seen
.iter()
.find(|r| r.contains(r#""method":"restore_deterministic_wallet""#))
.expect("restore RPC");
assert!(
restore.contains("lumber tacit lemon ivory risk"),
"seed missing: {restore}"
);
}
#[test]
fn restore_wallet_empty_seed_is_local_error() {
let w = Wallet::from_url("http://ow:[email protected]:18083").unwrap();
let err = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(w.restore_wallet("onionwire", "pw", " "))
.unwrap_err()
.to_string();
assert!(err.to_ascii_lowercase().contains("seed"), "got {err}");
}
/// F5 must not regress: an open RPC (HTTP 200, no Digest challenge) is refused.
#[tokio::test]
async fn open_rpc_without_digest_challenge_is_still_refused() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let canned = http_200_body(
r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}}"#,
);
tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.expect("accept");
let mut buf = vec![0u8; 4096];
let _ = sock.read(&mut buf).await;
let _ = sock.write_all(canned.as_bytes()).await;
});
let err = recording_wallet(port)
.get_address()
.await
.unwrap_err()
.to_string();
assert!(err.to_ascii_lowercase().contains("digest"), "got {err}");
}
/// `ONIONWIRE_WALLET_NO_SPEND` is the operator-facing switch.
#[test]
fn from_env_reads_no_spend_flag() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
unsafe {
std::env::set_var("ONIONWIRE_WALLET_RPC", "http://ow:[email protected]:18083");
std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "1");
}
let on = Wallet::from_env();
assert!(on.no_spend(), "flag 1 must mean no-spend");
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "true") };
assert!(Wallet::from_env().no_spend(), "\"true\" must mean no-spend");
for off in ["0", "no", "off"] {
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", off) };
assert!(!Wallet::from_env().no_spend(), "{off} must be off");
}
unsafe {
std::env::remove_var("ONIONWIRE_WALLET_NO_SPEND");
std::env::remove_var("ONIONWIRE_WALLET_RPC");
}
assert!(!Wallet::from_env().no_spend(), "unset must be off");
}
fn digest_401() -> String {
"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into()
}
async fn serve_digest_then(listener: TcpListener, ok: String) {
let (mut sock, _) = listener.accept().await.expect("accept");
let mut buf = vec![0u8; 8192];
let _ = sock.read(&mut buf).await;
sock.write_all(digest_401().as_bytes()).await.expect("401");
drop(sock);
let (mut sock, _) = listener.accept().await.expect("accept2");
buf.fill(0);
let n = sock.read(&mut buf).await.unwrap_or(0);
let req = String::from_utf8_lossy(&buf[..n]);
assert!(
req.contains("Authorization: Digest"),
"missing digest auth: {req}"
);
assert!(req.contains("username=\"ow\""), "missing user: {req}");
assert!(req.contains("response=\""), "missing response: {req}");
sock.write_all(ok.as_bytes()).await.expect("200");
}
#[tokio::test]
async fn mock_digest_auth_accepted() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let canned = json_rpc_ok(
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
);
tokio::spawn(serve_digest_then(listener, canned));
let w = Wallet::from_url(&format!("http://ow:[email protected]:{}", addr.port())).unwrap();
let got = w.get_address().await.expect("get_address");
assert!(got.starts_with('4'), "got {got}");
}
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// Answers the Digest challenge, then holds the reply for `delay`. Lets a test
/// prove which call classes get which budget.
async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) {
while let Ok((mut sock, _)) = listener.accept().await {
let mut buf = vec![0u8; 8192];
let n = sock.read(&mut buf).await.unwrap_or(0);
let req = String::from_utf8_lossy(&buf[..n]).to_string();
if !req.contains("Authorization:") {
let _ = sock.write_all(digest_401().as_bytes()).await;
continue;
}
tokio::time::sleep(delay).await;
let body = match rpc_method(&req).as_str() {
"get_info" => synced_info(),
_ => rpc_result(
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
),
};
let _ = sock.write_all(http_200_body(&body).as_bytes()).await;
}
}
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard The only input path for the wallet was env. Add the same three remote-mode fields as stored config so the F7 screen can set them and headless runs read one source of truth: - `wallet_config` table in the encrypted store (one row; the login is sealed with the store data key under `onionwire/wallet-config/v1`, on top of SQLCipher). Empty URL clears it. `Store::load_wallet_config` / `save_wallet_config`. - `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which prefers stored config, falls back to env, and refuses to dial a bad stored endpoint. Node::start* now reads the store before constructing the wallet. - `WalletStatus { configured, connected, last_error, balance_line, receive_address }`: `connected` only ever comes from a probe (`Wallet::status`, get_address + get_balance); config alone leaves it false. `Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the probe that folds into it. - One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status, error }` for the Test-connection button: same loopback/digest rules, errors redacted and capped. - `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus `Node::wallet_readiness` (async, block_on-friendly): not configured → NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any dial; configured but not connected → NOT_CONNECTED_MSG; else ready. - `Node::wallet_save_config` persists, validates first, then re-reads so the live wallet and snapshot follow a Save without a restart. - `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the wallet can be re-pointed mid-session. Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not wired here. docs/WALLET.md documents the stored config, boot precedence and the exact guard copy. Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence, sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
const SPEND_ADDR: &str = "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// 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 {
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard The only input path for the wallet was env. Add the same three remote-mode fields as stored config so the F7 screen can set them and headless runs read one source of truth: - `wallet_config` table in the encrypted store (one row; the login is sealed with the store data key under `onionwire/wallet-config/v1`, on top of SQLCipher). Empty URL clears it. `Store::load_wallet_config` / `save_wallet_config`. - `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which prefers stored config, falls back to env, and refuses to dial a bad stored endpoint. Node::start* now reads the store before constructing the wallet. - `WalletStatus { configured, connected, last_error, balance_line, receive_address }`: `connected` only ever comes from a probe (`Wallet::status`, get_address + get_balance); config alone leaves it false. `Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the probe that folds into it. - One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status, error }` for the Test-connection button: same loopback/digest rules, errors redacted and capped. - `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus `Node::wallet_readiness` (async, block_on-friendly): not configured → NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any dial; configured but not connected → NOT_CONNECTED_MSG; else ready. - `Node::wallet_save_config` persists, validates first, then re-reads so the live wallet and snapshot follow a Save without a restart. - `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the wallet can be re-pointed mid-session. Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not wired here. docs/WALLET.md documents the stored config, boot precedence and the exact guard copy. Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence, sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
"get_info" => {
rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#)
}
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
}),
));
let w = recording_wallet(port);
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard The only input path for the wallet was env. Add the same three remote-mode fields as stored config so the F7 screen can set them and headless runs read one source of truth: - `wallet_config` table in the encrypted store (one row; the login is sealed with the store data key under `onionwire/wallet-config/v1`, on top of SQLCipher). Empty URL clears it. `Store::load_wallet_config` / `save_wallet_config`. - `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which prefers stored config, falls back to env, and refuses to dial a bad stored endpoint. Node::start* now reads the store before constructing the wallet. - `WalletStatus { configured, connected, last_error, balance_line, receive_address }`: `connected` only ever comes from a probe (`Wallet::status`, get_address + get_balance); config alone leaves it false. `Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the probe that folds into it. - One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status, error }` for the Test-connection button: same loopback/digest rules, errors redacted and capped. - `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus `Node::wallet_readiness` (async, block_on-friendly): not configured → NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any dial; configured but not connected → NOT_CONNECTED_MSG; else ready. - `Node::wallet_save_config` persists, validates first, then re-reads so the live wallet and snapshot follow a Save without a restart. - `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the wallet can be re-pointed mid-session. Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not wired here. docs/WALLET.md documents the stored config, boot precedence and the exact guard copy. Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence, sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
assert!(
!w.chain_ready().await.expect("get_info"),
"must not be ready"
);
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
assert!(
!w.can_verify_receipts().await,
"an unsynced wallet cannot verify receipts"
);
let err = w.transfer(SPEND_ADDR, 1).await.unwrap_err().to_string();
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard The only input path for the wallet was env. Add the same three remote-mode fields as stored config so the F7 screen can set them and headless runs read one source of truth: - `wallet_config` table in the encrypted store (one row; the login is sealed with the store data key under `onionwire/wallet-config/v1`, on top of SQLCipher). Empty URL clears it. `Store::load_wallet_config` / `save_wallet_config`. - `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which prefers stored config, falls back to env, and refuses to dial a bad stored endpoint. Node::start* now reads the store before constructing the wallet. - `WalletStatus { configured, connected, last_error, balance_line, receive_address }`: `connected` only ever comes from a probe (`Wallet::status`, get_address + get_balance); config alone leaves it false. `Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the probe that folds into it. - One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status, error }` for the Test-connection button: same loopback/digest rules, errors redacted and capped. - `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus `Node::wallet_readiness` (async, block_on-friendly): not configured → NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any dial; configured but not connected → NOT_CONNECTED_MSG; else ready. - `Node::wallet_save_config` persists, validates first, then re-reads so the live wallet and snapshot follow a Save without a restart. - `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the wallet can be re-pointed mid-session. Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not wired here. docs/WALLET.md documents the stored config, boot precedence and the exact guard copy. Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence, sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
assert!(err.to_ascii_lowercase().contains("not synced"), "got {err}");
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
let seen = log.lock().expect("log").clone();
assert!(
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard The only input path for the wallet was env. Add the same three remote-mode fields as stored config so the F7 screen can set them and headless runs read one source of truth: - `wallet_config` table in the encrypted store (one row; the login is sealed with the store data key under `onionwire/wallet-config/v1`, on top of SQLCipher). Empty URL clears it. `Store::load_wallet_config` / `save_wallet_config`. - `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which prefers stored config, falls back to env, and refuses to dial a bad stored endpoint. Node::start* now reads the store before constructing the wallet. - `WalletStatus { configured, connected, last_error, balance_line, receive_address }`: `connected` only ever comes from a probe (`Wallet::status`, get_address + get_balance); config alone leaves it false. `Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the probe that folds into it. - One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status, error }` for the Test-connection button: same loopback/digest rules, errors redacted and capped. - `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus `Node::wallet_readiness` (async, block_on-friendly): not configured → NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any dial; configured but not connected → NOT_CONNECTED_MSG; else ready. - `Node::wallet_save_config` persists, validates first, then re-reads so the live wallet and snapshot follow a Save without a restart. - `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the wallet can be re-pointed mid-session. Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not wired here. docs/WALLET.md documents the stored config, boot precedence and the exact guard copy. Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence, sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
!seen.iter().any(|r| r.contains("\"method\":\"transfer\"")),
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
"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 {
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard The only input path for the wallet was env. Add the same three remote-mode fields as stored config so the F7 screen can set them and headless runs read one source of truth: - `wallet_config` table in the encrypted store (one row; the login is sealed with the store data key under `onionwire/wallet-config/v1`, on top of SQLCipher). Empty URL clears it. `Store::load_wallet_config` / `save_wallet_config`. - `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which prefers stored config, falls back to env, and refuses to dial a bad stored endpoint. Node::start* now reads the store before constructing the wallet. - `WalletStatus { configured, connected, last_error, balance_line, receive_address }`: `connected` only ever comes from a probe (`Wallet::status`, get_address + get_balance); config alone leaves it false. `Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the probe that folds into it. - One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status, error }` for the Test-connection button: same loopback/digest rules, errors redacted and capped. - `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus `Node::wallet_readiness` (async, block_on-friendly): not configured → NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any dial; configured but not connected → NOT_CONNECTED_MSG; else ready. - `Node::wallet_save_config` persists, validates first, then re-reads so the live wallet and snapshot follow a Save without a restart. - `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the wallet can be re-pointed mid-session. Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not wired here. docs/WALLET.md documents the stored config, boot precedence and the exact guard copy. Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence, sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
"get_info" => {
rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#)
}
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
"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();
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard The only input path for the wallet was env. Add the same three remote-mode fields as stored config so the F7 screen can set them and headless runs read one source of truth: - `wallet_config` table in the encrypted store (one row; the login is sealed with the store data key under `onionwire/wallet-config/v1`, on top of SQLCipher). Empty URL clears it. `Store::load_wallet_config` / `save_wallet_config`. - `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which prefers stored config, falls back to env, and refuses to dial a bad stored endpoint. Node::start* now reads the store before constructing the wallet. - `WalletStatus { configured, connected, last_error, balance_line, receive_address }`: `connected` only ever comes from a probe (`Wallet::status`, get_address + get_balance); config alone leaves it false. `Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the probe that folds into it. - One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status, error }` for the Test-connection button: same loopback/digest rules, errors redacted and capped. - `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus `Node::wallet_readiness` (async, block_on-friendly): not configured → NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any dial; configured but not connected → NOT_CONNECTED_MSG; else ready. - `Node::wallet_save_config` persists, validates first, then re-reads so the live wallet and snapshot follow a Save without a restart. - `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the wallet can be re-pointed mid-session. Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not wired here. docs/WALLET.md documents the stored config, boot precedence and the exact guard copy. Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence, sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
tokio::spawn(serve_delayed(
listener,
std::time::Duration::from_millis(400),
));
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
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!(
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard The only input path for the wallet was env. Add the same three remote-mode fields as stored config so the F7 screen can set them and headless runs read one source of truth: - `wallet_config` table in the encrypted store (one row; the login is sealed with the store data key under `onionwire/wallet-config/v1`, on top of SQLCipher). Empty URL clears it. `Store::load_wallet_config` / `save_wallet_config`. - `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which prefers stored config, falls back to env, and refuses to dial a bad stored endpoint. Node::start* now reads the store before constructing the wallet. - `WalletStatus { configured, connected, last_error, balance_line, receive_address }`: `connected` only ever comes from a probe (`Wallet::status`, get_address + get_balance); config alone leaves it false. `Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the probe that folds into it. - One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status, error }` for the Test-connection button: same loopback/digest rules, errors redacted and capped. - `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus `Node::wallet_readiness` (async, block_on-friendly): not configured → NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any dial; configured but not connected → NOT_CONNECTED_MSG; else ready. - `Node::wallet_save_config` persists, validates first, then re-reads so the live wallet and snapshot follow a Save without a restart. - `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the wallet can be re-pointed mid-session. Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not wired here. docs/WALLET.md documents the stored config, boot precedence and the exact guard copy. Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence, sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
w.chain_ready()
.await
.expect("get_info within the chain budget"),
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
"chain calls must outlast daemon latency"
);
}
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard The only input path for the wallet was env. Add the same three remote-mode fields as stored config so the F7 screen can set them and headless runs read one source of truth: - `wallet_config` table in the encrypted store (one row; the login is sealed with the store data key under `onionwire/wallet-config/v1`, on top of SQLCipher). Empty URL clears it. `Store::load_wallet_config` / `save_wallet_config`. - `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which prefers stored config, falls back to env, and refuses to dial a bad stored endpoint. Node::start* now reads the store before constructing the wallet. - `WalletStatus { configured, connected, last_error, balance_line, receive_address }`: `connected` only ever comes from a probe (`Wallet::status`, get_address + get_balance); config alone leaves it false. `Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the probe that folds into it. - One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status, error }` for the Test-connection button: same loopback/digest rules, errors redacted and capped. - `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus `Node::wallet_readiness` (async, block_on-friendly): not configured → NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any dial; configured but not connected → NOT_CONNECTED_MSG; else ready. - `Node::wallet_save_config` persists, validates first, then re-reads so the live wallet and snapshot follow a Save without a restart. - `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the wallet can be re-pointed mid-session. Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not wired here. docs/WALLET.md documents the stored config, boot precedence and the exact guard copy. Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence, sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
// ---------------------------------------------------------------------------
// 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"),
}
.label(),
"local 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"),
};
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}");
}
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard The only input path for the wallet was env. Add the same three remote-mode fields as stored config so the F7 screen can set them and headless runs read one source of truth: - `wallet_config` table in the encrypted store (one row; the login is sealed with the store data key under `onionwire/wallet-config/v1`, on top of SQLCipher). Empty URL clears it. `Store::load_wallet_config` / `save_wallet_config`. - `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which prefers stored config, falls back to env, and refuses to dial a bad stored endpoint. Node::start* now reads the store before constructing the wallet. - `WalletStatus { configured, connected, last_error, balance_line, receive_address }`: `connected` only ever comes from a probe (`Wallet::status`, get_address + get_balance); config alone leaves it false. `Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the probe that folds into it. - One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status, error }` for the Test-connection button: same loopback/digest rules, errors redacted and capped. - `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus `Node::wallet_readiness` (async, block_on-friendly): not configured → NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any dial; configured but not connected → NOT_CONNECTED_MSG; else ready. - `Node::wallet_save_config` persists, validates first, then re-reads so the live wallet and snapshot follow a Save without a restart. - `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the wallet can be re-pointed mid-session. Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not wired here. docs/WALLET.md documents the stored config, boot precedence and the exact guard copy. Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence, sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
/// 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
}
wallet: land the in-process Cuprate chain source on main `ChainSource::InProcessCuprate { datadir }` is the fourth chain source: P2P, consensus and RandomX run inside the OnionWire process instead of as a spawned `monerod`. The wallet layer does not move — the daemon binds the same loopback unrestricted RPC (`127.0.0.1:18081`) that `WalletChild::daemon_address` already returns for a local source, so `wallet_rpc_argv`, the RPC client, the payment frames and the receipt-verification path are untouched. - Cargo.toml: `cuprated` (git, rev 4f8fcd1b) + `toml`, both optional, behind the `cuprate-daemon` feature, OFF by default. `cuprated`'s own `arti` feature is disabled (`default-features = false`): its arti-client 0.44 cannot unify with this crate's 0.46, and the in-process daemon is clearnet-only. One Tor stack in the process. `Cargo.lock` gains the graph; a default build's `cargo tree --locked -e normal -i cuprated` still says "did not match any packages", and only `arti-client v0.46.0` is in the lock. - src/cuprate.rs (new): `CuprateNode` builds the cuprated config as TOML (testnet, unrestricted RPC on loopback, restricted RPC disabled, inbound P2P off), launches it on a runtime it owns, and owns the node. `launch` is synchronous on purpose: `WalletChild::start` is sync (the TUI calls it from its blocking thread, UniFFI calls it from an async context) and a runtime cannot be started from inside a runtime, so the launch runs on a thread of its own and the node + its runtime come back over a channel. Dropping the value asks the node to shut down and `shutdown_background`s the runtime, which is the only exit that cannot panic when the value is dropped inside another runtime. The type exists in every build (feature off: `launch` fails with the feature name), so the chain-source type, its stored record and its copy do not fork on a cargo feature. - src/wallet.rs: the variant, its label (`in-process node`), and the chain-daemon client the wallet line carried (typed `WalletError`, de-chunked HTTP, `get_height` over the URI endpoint, an above-the-tip height as one typed error). Cuprate answers those three differently from monerod and the in-process source is what makes them the *local* case. - src/wallet_child.rs: launches/holds/stops the node, `chain_datadir` for the free-space/ownership question, the honest `chain_copy` line, `kind = "cuprate"` in the sealed record, and `ChildConfig::validate` for it. - src/tui.rs: the wallet screen's chain line carries the testnet caveat when the configured source is the in-process one. It computes the line at draw time, so `Screen::Wallet`'s shape (which tests construct) does not change. - docs/WALLET.md, docs/THREAT_MODEL.md, docs/cuprate-android-spike.md: the feature flag and how to enable it, where the (fjall) chain store lives, the **measured** +11.8 MiB delta, the pre-production/testnet caveat, and the in-repo aarch64-linux-android proof with exit codes. Scope deviations, stated plainly: - `src/cuprate.rs` and its one `src/lib.rs` module line are not in the card's allowed list; the card's own deliverable describes the module's behaviour. - `crates/onionwire-sdk/src/lib.rs` is forbidden, but adding a variant to a `pub enum` that the SDK matches exhaustively breaks the SDK workspace, and the root CI `sdk` job runs on every PR. One variant plus two match arms land here so the SDK keeps compiling (`cargo test --locked` + clippy clean); the SDK card owns the rest — feature passthrough, the config field's semantics, the label and its tests, and the Android check. - `tests/wallet.rs` carries the launch test. `tests/tui_frames.rs` is untouched: main has no `ChainChoice` to pin (the chain-source picker is the unmerged F7 work, and `docs/WALLET.md` says so rather than describing a picker that does not exist). Proof (all on this tree): - Default build: `cargo test --locked --target x86_64-unknown-linux-gnu` → 345 passed / 0 failed across 33 suites, exit 0; `cargo clippy --locked --all-targets --target x86_64-unknown-linux-gnu -- -D warnings` exit 0. - Feature on: `cargo test --locked --features cuprate-daemon --target x86_64-unknown-linux-gnu` → 347 passed / 0 failed, exit 0; same clippy with `--features cuprate-daemon` exit 0. The two extra tests are the real thing: `wallet_child::tests::in_process_source_launches_a_daemon_and_stop_shuts_it_down` and `tests/wallet.rs::an_in_process_cuprate_node_answers_the_typed_daemon_client` — the latter launches the node, drives `get_info` / `get_height` / `get_block` through the typed client, checks the above-the-tip 500 maps to `DaemonHeightOutOfRange`, checks the chain store is under the chain datadir, and checks the listener dies with the node. - aarch64: `cargo check --locked --release --target aarch64-linux-android --features cuprate-daemon` exit 0 (1m 50s), and the full link exit 0 (`cargo rustc ... --bin onionwire -- <NDK C++ runtime / compiler-rt link args>`) producing `ELF 64-bit LSB pie executable, ARM aarch64, for Android 26, built by NDK r28c`. - Size: stripped aarch64 release binary, 24,725,704 bytes without the feature and 37,053,472 with it — +12,327,768 bytes (≈ +11.8 MiB), the figure `docs/WALLET.md` now quotes.
2026-09-18 13:45:59 -04:00
// ---------------------------------------------------------------------------
// 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)
.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"
);
}