Merge branch 'main' into feat/store-checkpoint-wal
All checks were successful
ci / test (pull_request) Successful in 4m18s
All checks were successful
ci / test (pull_request) Successful in 4m18s
This commit is contained in:
commit
111e90ce0a
23 changed files with 2283 additions and 207 deletions
|
|
@ -1,10 +1,13 @@
|
|||
//! Spec implementation tests for docs/TUI.md (this card).
|
||||
//! Does not own `tests/tui_frames.rs` (PR #23).
|
||||
|
||||
use onionwire::Message;
|
||||
use onionwire::outbox::{OutboxEntry, OutboxStatus};
|
||||
use onionwire::qr;
|
||||
use onionwire::tui::{
|
||||
alert_line, ascii_chrome, draw_share, draw_text_overlay, empty_friend_chat_text,
|
||||
help_overlay_text, main_footer_hints, main_header_line, paste_screen_text, roster_col_width,
|
||||
OutboxSummary, alert_line, ascii_chrome, chat_with_delivery, delivery_tag, draw_chat,
|
||||
draw_share, draw_text_overlay, empty_friend_chat_text, help_overlay_text, main_footer_hints,
|
||||
main_header_line, paste_screen_text, retry_in_text, roster_col_width, short_send_reason,
|
||||
status_footer, wrap_invite,
|
||||
};
|
||||
use ratatui::Frame;
|
||||
|
|
@ -376,3 +379,376 @@ fn ascii_switch_80x24_frame_is_pure_ascii() {
|
|||
println!("===== AFTER ascii share 80x24 =====\n{screen}");
|
||||
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Outbox delivery state (card t_d9a5b065)
|
||||
//
|
||||
// States come from the outbox API (`Outbox::pending` → `Queued` / `Sending` /
|
||||
// `Failed`; delivered rows are deleted, so absence means `Sent`). No new wire
|
||||
// prefix, no parallel state model.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn out_msg(body: &str) -> Message {
|
||||
Message {
|
||||
dir: "out".into(),
|
||||
plaintext: body.as_bytes().to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
fn in_msg(body: &str) -> Message {
|
||||
Message {
|
||||
dir: "in".into(),
|
||||
plaintext: body.as_bytes().to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_row(
|
||||
body: &str,
|
||||
status: OutboxStatus,
|
||||
attempts: u32,
|
||||
next_in: i64,
|
||||
now: i64,
|
||||
) -> OutboxEntry {
|
||||
OutboxEntry {
|
||||
id: 1,
|
||||
friend_pk: vec![9u8; 32],
|
||||
message_id: 1,
|
||||
body: body.as_bytes().to_vec(),
|
||||
attempts,
|
||||
next_attempt_at: now + next_in,
|
||||
created_at: now,
|
||||
status,
|
||||
last_error: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn queued_row(body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry {
|
||||
pending_row(body, OutboxStatus::Queued, attempts, next_in, now)
|
||||
}
|
||||
|
||||
fn sending_row(body: &str, now: i64) -> OutboxEntry {
|
||||
pending_row(body, OutboxStatus::Sending, 1, 0, now)
|
||||
}
|
||||
|
||||
fn failed_row(body: &str, why: &str, now: i64) -> OutboxEntry {
|
||||
pending_row(body, OutboxStatus::Failed(why.into()), 8, 0, now)
|
||||
}
|
||||
|
||||
/// Marker is everything after the two-space separator the render helper uses.
|
||||
fn marker_of(line: &str) -> &str {
|
||||
line.rsplit(" ").next().unwrap_or("")
|
||||
}
|
||||
|
||||
/// Force the non-ASCII (unicode glyph) path. Caller holds `ASCII_ENV`.
|
||||
fn force_unicode_mode() {
|
||||
unsafe {
|
||||
std::env::remove_var("ONIONWIRE_ASCII");
|
||||
std::env::remove_var("NO_COLOR");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_and_delivered_messages_render_different_markers() {
|
||||
let guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
force_unicode_mode();
|
||||
let _guard = guard;
|
||||
let now = 1_700_000_000;
|
||||
let msgs = vec![out_msg("ping"), out_msg("pong")];
|
||||
let pending = vec![queued_row("pong", 2, 45, now)];
|
||||
|
||||
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
|
||||
|
||||
assert!(
|
||||
lines[0].contains('✓'),
|
||||
"delivered row lost its mark: {:?}",
|
||||
lines[0]
|
||||
);
|
||||
assert!(!lines[0].contains("queued"), "{:?}", lines[0]);
|
||||
assert!(
|
||||
lines[1].contains('◷'),
|
||||
"queued row lost its glyph: {:?}",
|
||||
lines[1]
|
||||
);
|
||||
assert!(lines[1].contains("queued"), "{:?}", lines[1]);
|
||||
assert!(
|
||||
lines[1].contains("try 2/8"),
|
||||
"attempt count missing: {:?}",
|
||||
lines[1]
|
||||
);
|
||||
assert!(
|
||||
lines[1].contains("retry 45s"),
|
||||
"retry age missing: {:?}",
|
||||
lines[1]
|
||||
);
|
||||
assert_ne!(
|
||||
marker_of(&lines[0]),
|
||||
marker_of(&lines[1]),
|
||||
"queued and delivered must not share a marker"
|
||||
);
|
||||
assert_eq!(summary.queued, 1);
|
||||
assert_eq!(summary.failed, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delivery_markers_have_exercised_ascii_fallbacks() {
|
||||
let _guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
unsafe {
|
||||
std::env::set_var("ONIONWIRE_ASCII", "1");
|
||||
std::env::remove_var("NO_COLOR");
|
||||
}
|
||||
let now = 500;
|
||||
let msgs = vec![
|
||||
out_msg("alpha"),
|
||||
out_msg("beta"),
|
||||
out_msg("gamma"),
|
||||
out_msg("delta"),
|
||||
in_msg("epsilon"),
|
||||
];
|
||||
let pending = vec![
|
||||
failed_row("alpha", "connect peer.onion:80: connection timed out", now),
|
||||
queued_row("beta", 1, 30, now),
|
||||
sending_row("gamma", now),
|
||||
];
|
||||
|
||||
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
|
||||
for line in &lines {
|
||||
assert!(
|
||||
line.is_ascii(),
|
||||
"ASCII fallback missing, non-ASCII in {line:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(marker_of(&lines[0]), "failed: connection timed out");
|
||||
assert_eq!(marker_of(&lines[1]), "queued (try 1/8, retry 30s)");
|
||||
assert_eq!(marker_of(&lines[2]), "sending");
|
||||
assert_eq!(marker_of(&lines[3]), "ok", "delivered fallback is `ok`");
|
||||
assert_eq!(lines[4], "them: epsilon", "inbound rows carry no state");
|
||||
assert_eq!(summary.queued, 2, "queued + sending are both outstanding");
|
||||
assert_eq!(summary.failed, 1);
|
||||
|
||||
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_age_and_failure_reason_are_short_forms() {
|
||||
assert_eq!(retry_in_text(45), "retry 45s");
|
||||
assert_eq!(retry_in_text(59), "retry 59s");
|
||||
assert_eq!(retry_in_text(60), "retry 1m");
|
||||
assert_eq!(retry_in_text(720), "retry 12m");
|
||||
assert_eq!(retry_in_text(0), "retry now");
|
||||
assert_eq!(retry_in_text(-30), "retry now");
|
||||
|
||||
assert_eq!(
|
||||
short_send_reason("connect abcdef.onion:80: connection timed out", 24),
|
||||
"connection timed out"
|
||||
);
|
||||
let long = short_send_reason("a-really-long-failure-description-here", 12);
|
||||
assert!(long.chars().count() <= 12, "{long:?}");
|
||||
assert!(
|
||||
long.contains('…') || long.contains("..."),
|
||||
"truncation marker missing: {long:?}"
|
||||
);
|
||||
assert_eq!(short_send_reason("nope", 24), "nope");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delivery_tag_reads_the_outbox_status_enum() {
|
||||
let guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
force_unicode_mode();
|
||||
let _guard = guard;
|
||||
assert_eq!(delivery_tag(&OutboxStatus::Sent, 0, 0), "✓");
|
||||
assert_eq!(
|
||||
delivery_tag(&OutboxStatus::Queued, 3, 120),
|
||||
"◷ queued (try 3/8, retry 2m)"
|
||||
);
|
||||
assert_eq!(delivery_tag(&OutboxStatus::Sending, 1, 0), "» sending");
|
||||
assert_eq!(
|
||||
delivery_tag(&OutboxStatus::Failed("connect x:80: nope".into()), 8, 0),
|
||||
"✗ failed: nope"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn footer_summary_counts_queued_and_keeps_fail_closed() {
|
||||
let none = OutboxSummary::default();
|
||||
assert_eq!(none.note(), None);
|
||||
|
||||
let queued = OutboxSummary {
|
||||
queued: 2,
|
||||
failed: 0,
|
||||
first_error: None,
|
||||
};
|
||||
assert_eq!(queued.note().as_deref(), Some("2 queued"));
|
||||
|
||||
let failed = OutboxSummary {
|
||||
queued: 0,
|
||||
failed: 1,
|
||||
first_error: Some("connect peer.onion:80: connection timed out".into()),
|
||||
};
|
||||
let note = failed.note().expect("failed rows must produce a note");
|
||||
assert!(note.starts_with("send failed:"), "{note:?}");
|
||||
assert!(note.contains("connection timed out"), "{note:?}");
|
||||
|
||||
let mixed = OutboxSummary {
|
||||
queued: 3,
|
||||
failed: 1,
|
||||
first_error: Some("connect peer.onion:80: connection timed out".into()),
|
||||
};
|
||||
let mixed_note = mixed.note().expect("mixed rows must produce a note");
|
||||
assert!(mixed_note.contains("3 queued"), "{mixed_note:?}");
|
||||
assert!(mixed_note.contains("send failed"), "{mixed_note:?}");
|
||||
|
||||
// Fail-closed copy stays visible in the real footer at the 80-col floor.
|
||||
let line = status_footer(80, FP, ONION, Some(¬e), main_footer_hints());
|
||||
assert!(
|
||||
line.chars().count() <= 80,
|
||||
"{} {line:?}",
|
||||
line.chars().count()
|
||||
);
|
||||
assert!(line.contains("send failed"), "footer dropped it: {line:?}");
|
||||
assert!(line.contains("TOR") && line.contains("? help"), "{line:?}");
|
||||
|
||||
let queued_line = status_footer(80, FP, ONION, queued.note().as_deref(), main_footer_hints());
|
||||
assert!(queued_line.contains("2 queued"), "{queued_line:?}");
|
||||
assert!(queued_line.chars().count() <= 80);
|
||||
|
||||
// `! ` ornament (colour off) still lands on the derived failing note.
|
||||
let _guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
unsafe { std::env::set_var("NO_COLOR", "1") };
|
||||
let no_color = status_footer(80, FP, ONION, Some(¬e), main_footer_hints());
|
||||
assert!(no_color.contains("! send failed"), "{no_color:?}");
|
||||
unsafe { std::env::remove_var("NO_COLOR") };
|
||||
}
|
||||
|
||||
/// The card's width criterion: draw the real helpers at the documented floor
|
||||
/// (80x24) and prove nothing in the chat/footer region exceeds the width, and
|
||||
/// that an over-long row wraps in the pane instead of being clipped.
|
||||
#[test]
|
||||
fn chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping() {
|
||||
let guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
force_unicode_mode();
|
||||
let _guard = guard;
|
||||
let now = 1_700_000_000;
|
||||
let long = "this is a very long chat line that should wrap inside the chat pane instead of running off the right edge of an 80-column terminal and colliding with the roster border";
|
||||
let msgs = vec![out_msg("ok"), in_msg("pong"), out_msg(long)];
|
||||
let pending = vec![queued_row(long, 3, 45, now)];
|
||||
|
||||
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
|
||||
for line in lines.iter().take(2) {
|
||||
assert!(
|
||||
line.chars().count() <= 80,
|
||||
"short row wider than 80: {} {line:?}",
|
||||
line.chars().count()
|
||||
);
|
||||
}
|
||||
let footer = status_footer(
|
||||
80,
|
||||
FP,
|
||||
ONION,
|
||||
summary.note().as_deref(),
|
||||
main_footer_hints(),
|
||||
);
|
||||
assert!(footer.chars().count() <= 80, "{footer:?}");
|
||||
|
||||
let backend = TestBackend::new(80, 24);
|
||||
let mut terminal = Terminal::new(backend).expect("terminal");
|
||||
terminal
|
||||
.draw(|f| {
|
||||
let area = f.area();
|
||||
let cols = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area);
|
||||
draw_chat(f, cols[0], &lines, Some("alice"), true, 0);
|
||||
f.render_widget(Paragraph::new(footer.clone()), cols[1]);
|
||||
})
|
||||
.expect("draw");
|
||||
|
||||
let buf = terminal.backend().buffer();
|
||||
let mut screen = String::new();
|
||||
for y in 0..24u16 {
|
||||
for x in 0..80u16 {
|
||||
screen.push_str(buf[(x, y)].symbol());
|
||||
}
|
||||
screen.push('\n');
|
||||
}
|
||||
for (y, row) in screen.lines().enumerate() {
|
||||
assert!(
|
||||
row.chars().count() <= 80,
|
||||
"80x24 chat/footer row {y} wider than the terminal: {} {row:?}",
|
||||
row.chars().count()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
screen.contains('◷'),
|
||||
"queued glyph missing from frame:\n{screen}"
|
||||
);
|
||||
assert!(screen.contains("queued"), "queued word missing:\n{screen}");
|
||||
assert!(screen.contains('✓'), "delivered glyph missing:\n{screen}");
|
||||
assert!(
|
||||
screen.contains("with the roster border"),
|
||||
"long row was clipped, not wrapped:\n{screen}"
|
||||
);
|
||||
assert!(
|
||||
screen.contains("1 queued"),
|
||||
"footer summary missing:\n{screen}"
|
||||
);
|
||||
println!("===== AFTER outbox 80x24 (real draw_chat + status_footer) =====\n{screen}");
|
||||
}
|
||||
|
||||
/// The renderer consumes the real outbox API, not a hand-written fixture: a
|
||||
/// genuine unreachable-onion send leaves a `Queued` row, and that row is what
|
||||
/// the chat line and the footer note are built from.
|
||||
#[tokio::test]
|
||||
async fn renders_a_queued_row_from_a_real_outbox_send() {
|
||||
use onionwire::Store;
|
||||
use onionwire::outbox::{BoxFut, Deliverer, Outbox};
|
||||
use std::sync::Arc;
|
||||
|
||||
struct Dead;
|
||||
impl Deliverer for Dead {
|
||||
fn deliver<'a>(
|
||||
&'a self,
|
||||
_onion: &'a str,
|
||||
_pinned_id: &'a [u8],
|
||||
_prekey: &'a [u8],
|
||||
_plaintext: &'a [u8],
|
||||
) -> BoxFut<'a, Result<(), String>> {
|
||||
Box::pin(async { Err("connect dead.onion:80: timed out".to_string()) })
|
||||
}
|
||||
}
|
||||
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let store = Store::open_at_with_passphrase(dir.path(), "tui-spec-pass").expect("open store");
|
||||
let pk = [1u8; 32];
|
||||
store
|
||||
.upsert_friend(&pk, "dead.onion", None)
|
||||
.expect("friend");
|
||||
store.set_friend_prekey(&pk, &[7u8; 32]).expect("prekey");
|
||||
let store = Arc::new(std::sync::Mutex::new(store));
|
||||
let outbox = Outbox::new(Arc::clone(&store), Arc::new(Dead));
|
||||
|
||||
assert_eq!(
|
||||
outbox.send(&pk, b"queued for a dead peer").await,
|
||||
Ok(OutboxStatus::Queued)
|
||||
);
|
||||
let pending = outbox.pending(&pk).expect("pending rows");
|
||||
assert_eq!(pending.len(), 1, "one queued row");
|
||||
let msgs = store
|
||||
.lock()
|
||||
.expect("store lock")
|
||||
.list_messages(&pk)
|
||||
.expect("messages");
|
||||
|
||||
let now = pending[0].next_attempt_at - 45;
|
||||
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
|
||||
assert_eq!(lines.len(), 1);
|
||||
assert!(
|
||||
lines[0].contains("queued (try 1/8, retry 45s)"),
|
||||
"real outbox row did not render: {:?}",
|
||||
lines[0]
|
||||
);
|
||||
assert_eq!(summary.note().as_deref(), Some("1 queued"));
|
||||
|
||||
// And once a send crosses the circuit the row is gone, so the same message
|
||||
// renders as delivered.
|
||||
let (delivered, summary) = chat_with_delivery(&msgs, &[], now);
|
||||
assert!(delivered[0].contains('✓'), "{:?}", delivered[0]);
|
||||
assert_eq!(summary.note(), None);
|
||||
}
|
||||
|
|
|
|||
233
tests/wallet.rs
233
tests/wallet.rs
|
|
@ -1,5 +1,7 @@
|
|||
//! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use ed25519_dalek::SigningKey;
|
||||
use onionwire::pay;
|
||||
use onionwire::wallet::{self, TransferRow, Wallet};
|
||||
|
|
@ -8,6 +10,10 @@ 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(),
|
||||
|
|
@ -241,6 +247,233 @@ async fn oversized_rpc_response_is_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}}}"#)
|
||||
}
|
||||
|
||||
fn recording_wallet(port: u16) -> Wallet {
|
||||
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("url")
|
||||
}
|
||||
|
||||
/// The wallet mock speaks the two methods `/tip` can reach, and refuses the
|
||||
/// local `transfer` before any socket is opened.
|
||||
#[tokio::test]
|
||||
async fn no_spend_mode_refuses_transfer_with_no_rpc_request() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let log = Arc::new(Mutex::new(Vec::new()));
|
||||
tokio::spawn(serve_recording(
|
||||
listener,
|
||||
Arc::clone(&log),
|
||||
Arc::new(|_| rpc_result(r#"{"tx_hash":"abc123"}"#)),
|
||||
));
|
||||
let w = recording_wallet(port).with_no_spend(true);
|
||||
assert!(w.no_spend());
|
||||
let err = w
|
||||
.transfer(
|
||||
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||||
1,
|
||||
)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(
|
||||
err.to_ascii_lowercase().contains("view-only"),
|
||||
"got {err}"
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
||||
let seen = log.lock().expect("log").clone();
|
||||
assert!(seen.is_empty(), "no RPC request may be made: {seen:?}");
|
||||
// Positive control: the recorder is live, so the emptiness above is real.
|
||||
let _ = w.get_address().await;
|
||||
assert!(!log.lock().expect("log").is_empty(), "recorder saw nothing");
|
||||
}
|
||||
|
||||
/// `/pay` (subaddress) and receipt verification (`get_transfers`) keep working
|
||||
/// with the no-spend flag on — only `transfer` is refused.
|
||||
#[tokio::test]
|
||||
async fn no_spend_mode_keeps_invoice_and_receipt_paths_working() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let log = Arc::new(Mutex::new(Vec::new()));
|
||||
tokio::spawn(serve_recording(
|
||||
listener,
|
||||
Arc::clone(&log),
|
||||
Arc::new(|method| match method {
|
||||
"create_address" => rpc_result(
|
||||
r#"{"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}"#,
|
||||
),
|
||||
"get_transfers" => rpc_result(
|
||||
r#"{"in":[{"txid":"deadbeef","amount":5,"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}],"pending":[]}"#,
|
||||
),
|
||||
_ => rpc_result(r#"{}"#),
|
||||
}),
|
||||
));
|
||||
let w = recording_wallet(port).with_no_spend(true);
|
||||
let created = w.create_address().await.expect("create_address");
|
||||
assert!(created.starts_with('8'), "got {created}");
|
||||
let rows = w.get_transfers().await.expect("get_transfers");
|
||||
assert!(wallet::transfers_match(&rows, "deadbeef", "5", &created));
|
||||
let seen = log.lock().expect("log").clone();
|
||||
assert!(
|
||||
seen.iter()
|
||||
.any(|r| r.contains("\"method\":\"create_address\"")),
|
||||
"recorder must have seen the invoice path: {seen:?}"
|
||||
);
|
||||
assert!(
|
||||
!seen.iter().any(|r| r.contains("\"method\":\"transfer\"")),
|
||||
"transfer must never be dialed in no-spend mode"
|
||||
);
|
||||
}
|
||||
|
||||
/// A view-only wallet refuses `transfer` with its own opaque error. The
|
||||
/// pre-transfer signal is `query_key` key_type=spend_key (Monero answers
|
||||
/// WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29), so /tip must say so plainly.
|
||||
#[tokio::test]
|
||||
async fn view_only_wallet_maps_transfer_failure_to_clear_message() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let log = Arc::new(Mutex::new(Vec::new()));
|
||||
tokio::spawn(serve_recording(
|
||||
listener,
|
||||
Arc::clone(&log),
|
||||
Arc::new(|method| match method {
|
||||
"query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."),
|
||||
_ => 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"}"#),
|
||||
_ => 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}");
|
||||
}
|
||||
|
||||
/// 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()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
//! Noise handshake/transport state that lives inside `snow`.
|
||||
|
||||
use onionwire::backup::BackupKeys;
|
||||
use onionwire::profile;
|
||||
use onionwire::session::Keys;
|
||||
use onionwire::wallet::Wallet;
|
||||
use onionwire::Store;
|
||||
|
|
@ -52,6 +53,20 @@ unsafe fn drop_in_place_and_peek_identity_sk(v: &mut Keys) -> [u8; 32] {
|
|||
}
|
||||
}
|
||||
|
||||
/// Drops a `Zeroizing<[u8; 32]>` in place and reads its buffer back.
|
||||
///
|
||||
/// SAFETY: only for `ManuallyDrop<Zeroizing<[u8; 32]>>` locals — same contract
|
||||
/// as `drop_in_place_and_peek_identity_sk`.
|
||||
unsafe fn drop_in_place_and_peek_zeroizing_u8x32(v: &mut Zeroizing<[u8; 32]>) -> [u8; 32] {
|
||||
let p: *const [u8; 32] = &**v;
|
||||
// SAFETY: the caller guarantees `v` is dropped exactly once and is still
|
||||
// alive at its own address when read back.
|
||||
unsafe {
|
||||
std::ptr::drop_in_place(v as *mut Zeroizing<[u8; 32]>);
|
||||
std::ptr::read_volatile(p)
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop behaviour, not a comment: after the value drops, the local secret key
|
||||
/// material that feeds the Noise IK handshake is gone from its memory.
|
||||
#[test]
|
||||
|
|
@ -116,3 +131,27 @@ fn wallet_endpoint_debug_redacts_the_rpc_password() {
|
|||
);
|
||||
assert!(dbg.contains("<redacted>"), "{dbg}");
|
||||
}
|
||||
|
||||
/// `profile::sign` needs a raw 32-byte copy of the identity secret to build the
|
||||
/// dalek `SigningKey`. That copy is a `Zeroizing` buffer, not a bare array that
|
||||
/// stays on the stack until the function returns.
|
||||
#[test]
|
||||
fn profile_signing_key_bytes_are_zeroizing_and_wipe() {
|
||||
let secret = [0x5au8; 32];
|
||||
let bytes = profile::signing_key_bytes(&secret).expect("32 bytes");
|
||||
|
||||
let _: &Zeroizing<[u8; 32]> = &bytes;
|
||||
assert_eq!(&bytes[..], &secret[..], "buffer must hold the secret");
|
||||
|
||||
let mut probe = std::mem::ManuallyDrop::new(bytes);
|
||||
let after = unsafe { drop_in_place_and_peek_zeroizing_u8x32(&mut probe) };
|
||||
|
||||
assert_eq!(after, [0u8; 32], "identity secret survived its drop");
|
||||
}
|
||||
|
||||
/// A length-mismatched secret is an error, not a truncated/padded key.
|
||||
#[test]
|
||||
fn profile_signing_key_bytes_rejects_a_short_secret() {
|
||||
assert!(profile::signing_key_bytes(&[7u8; 31]).is_err());
|
||||
assert!(profile::signing_key_bytes(&[7u8; 33]).is_err());
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue