Merge branch 'main' into feat/store-checkpoint-wal
All checks were successful
ci / test (pull_request) Successful in 4m18s

This commit is contained in:
sirius 2026-09-12 22:09:58 +00:00
commit 111e90ce0a
23 changed files with 2283 additions and 207 deletions

View file

@ -23,9 +23,10 @@ pub struct Loc {
const PREFIX: &[u8] = b"loc ";
pub fn sign(identity_sk: &[u8], onion: &str, ts: i64) -> Result<Loc> {
let sk_bytes: [u8; 32] = identity_sk
.try_into()
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?;
// Same one-shot raw identity-secret copy as `profile::sign`; shared so
// `Zeroize` covers it here too.
let sk_bytes =
crate::profile::signing_key_bytes(identity_sk).map_err(|e| Error(e.to_string()))?;
let sk = SigningKey::from_bytes(&sk_bytes);
let sig = sk.sign(&sign_msg_v2(onion, ts)).to_bytes().to_vec();
Ok(Loc {

View file

@ -1,4 +1,5 @@
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use zeroize::Zeroizing;
pub type Result<T> = std::result::Result<T, Error>;
@ -30,6 +31,23 @@ pub fn validate(display_name: &str, bio: &str, xmr_addr: &str) -> Result<()> {
check_fields(display_name, bio, xmr_addr)
}
/// The raw 32-byte identity-secret copy that `ed25519-dalek` needs in order to
/// build a `SigningKey`.
///
/// `SigningKey` wipes its own copy on drop (its default `zeroize` feature);
/// the raw bytes are ours to wipe, so they live in a `Zeroizing` buffer rather
/// than on the stack in a bare `[u8; 32]`. Same pattern as `pay::sign_bytes`
/// and `qr::encode`; `loc::sign` shares this helper for the identical copy it
/// used to make.
pub fn signing_key_bytes(identity_sk: &[u8]) -> Result<Zeroizing<[u8; 32]>> {
if identity_sk.len() != 32 {
return Err(Error("identity secret key must be 32 bytes".into()));
}
let mut bytes = Zeroizing::new([0u8; 32]);
bytes[..].copy_from_slice(identity_sk);
Ok(bytes)
}
pub fn sign(
identity_sk: &[u8],
display_name: &str,
@ -38,9 +56,7 @@ pub fn sign(
ts: i64,
) -> Result<Profile> {
check_fields(display_name, bio, xmr_addr)?;
let sk_bytes: [u8; 32] = identity_sk
.try_into()
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?;
let sk_bytes = signing_key_bytes(identity_sk)?;
let sk = SigningKey::from_bytes(&sk_bytes);
let sig = sk
.sign(&sign_msg_v2(display_name, bio, xmr_addr, ts))

View file

@ -1,6 +1,7 @@
use std::collections::HashMap;
use std::io::{self, IsTerminal};
use std::sync::{Arc, mpsc};
use std::time::Duration;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::layout::{Constraint, Layout, Rect};
@ -8,11 +9,13 @@ use ratatui::style::{Color, Modifier, Style};
use ratatui::symbols::border;
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap};
use ratatui::{DefaultTerminal, Frame};
use zeroize::{Zeroize, Zeroizing};
use crate::node::Node;
use crate::outbox::DEFAULT_MAX_ATTEMPTS;
use crate::qr::{self, QrPayload};
use crate::sanitize;
use crate::store::{Friend, FriendProfile};
use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus};
const C_ACCENT: Color = Color::Rgb(232, 165, 75);
const C_TEXT: Color = Color::Rgb(196, 214, 176);
@ -116,6 +119,202 @@ pub fn empty_friend_chat_text() -> &'static str {
"no messages\ntype below, Enter sends"
}
// ---------------------------------------------------------------------------
// Delivery state (outbox)
//
// The outbox is the only source of per-message state: `Queued` / `Sending` /
// `Failed` rows are what `Node::outbox_pending` still holds, and a row is
// deleted the moment the send crosses the circuit — so an outbound message with
// no row is `Sent`. No parallel state model, no new wire prefix.
// ---------------------------------------------------------------------------
/// Longest short-form failure reason shown in a chat row.
pub const FAIL_REASON_BUDGET: usize = 24;
/// Marker glyph for one delivery state. ASCII chrome falls back to `ok` for the
/// wordless delivered state; `queued` / `sending` / `failed` already carry their
/// word, so their glyph is dropped rather than invented.
pub fn delivery_glyph(status: &OutboxStatus) -> &'static str {
let ascii = ascii_chrome();
match status {
OutboxStatus::Sent => {
if ascii {
"ok"
} else {
"✓"
}
}
OutboxStatus::Queued => {
if ascii {
""
} else {
"◷"
}
}
OutboxStatus::Sending => {
if ascii {
""
} else {
"»"
}
}
OutboxStatus::Failed(_) => {
if ascii {
""
} else {
"✗"
}
}
}
}
/// Next-attempt age for a queued row, from the absolute `next_attempt_at` the
/// outbox stores.
pub fn retry_in_text(next_in_secs: i64) -> String {
if next_in_secs <= 0 {
"retry now".to_string()
} else if next_in_secs < 60 {
format!("retry {next_in_secs}s")
} else {
format!("retry {}m", (next_in_secs + 59) / 60)
}
}
/// Transport failure text, short form: sanitized, tail of the `a: b: c` chain,
/// capped at `budget` cells so one peer's error cannot blow out the row.
pub fn short_send_reason(why: &str, budget: usize) -> String {
let clean = sanitize::display_text(why.as_bytes());
let tail = clean.rsplit(": ").next().unwrap_or("").trim();
let text = if tail.is_empty() { clean.trim() } else { tail };
truncate_chars(text, budget)
}
/// One row's delivery marker, straight from the outbox state.
pub fn delivery_tag(status: &OutboxStatus, attempts: u32, next_in_secs: i64) -> String {
let glyph = delivery_glyph(status);
let body = match status {
OutboxStatus::Sent => String::new(),
OutboxStatus::Queued => format!(
"queued (try {attempts}/{DEFAULT_MAX_ATTEMPTS}, {})",
retry_in_text(next_in_secs)
),
OutboxStatus::Sending => "sending".to_string(),
OutboxStatus::Failed(why) => {
format!("failed: {}", short_send_reason(why, FAIL_REASON_BUDGET))
}
};
match (glyph.is_empty(), body.is_empty()) {
(_, true) => glyph.to_string(),
(true, false) => body,
(false, false) => format!("{glyph} {body}"),
}
}
/// Footer summary derived from the outbox rows of the selected friend.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct OutboxSummary {
/// `Queued` + `Sending`: rows the worker may still deliver.
pub queued: usize,
/// Terminal failures — these never retry.
pub failed: usize,
/// First terminal failure, for the fail-closed footer copy.
pub first_error: Option<String>,
}
impl OutboxSummary {
/// Footer note, or `None` when nothing is outstanding. Any terminal failure
/// keeps a `send failed` statement so the fail-closed copy stays visible.
pub fn note(&self) -> Option<String> {
let reason = || {
short_send_reason(
self.first_error.as_deref().unwrap_or("unknown"),
FAIL_REASON_BUDGET,
)
};
match (self.queued, self.failed) {
(0, 0) => None,
(queued, 0) => Some(format!("{queued} queued")),
(0, 1) => Some(format!("send failed: {}", reason())),
(0, failed) => Some(format!("send failed: {} ({failed} failed)", reason())),
(queued, _) => Some(format!("{queued} queued, send failed: {}", reason())),
}
}
}
/// Chat transcript with per-message delivery state, plus the footer summary.
///
/// Pending rows are matched to messages by body, newest send first: an
/// outstanding retry is the most recent send of that text, and the outbox holds
/// no message id the UI could join on.
pub fn chat_with_delivery(
msgs: &[Message],
pending: &[OutboxEntry],
now: i64,
) -> (Vec<String>, OutboxSummary) {
let mut summary = OutboxSummary::default();
for entry in pending {
match &entry.status {
OutboxStatus::Failed(why) => {
summary.failed += 1;
summary.first_error.get_or_insert_with(|| why.clone());
}
_ => summary.queued += 1,
}
}
if msgs.is_empty() {
return (
empty_friend_chat_text()
.lines()
.map(str::to_string)
.collect(),
summary,
);
}
let mut by_body: HashMap<&[u8], Vec<&OutboxEntry>> = HashMap::new();
for entry in pending {
by_body
.entry(entry.body.as_slice())
.or_default()
.push(entry);
}
let mut tags: Vec<Option<String>> = vec![None; msgs.len()];
for (i, msg) in msgs.iter().enumerate().rev() {
if msg.dir != "out" {
continue;
}
if let Some(rows) = by_body.get_mut(msg.plaintext.as_slice())
&& let Some(entry) = rows.pop()
{
tags[i] = Some(delivery_tag(
&entry.status,
entry.attempts,
entry.next_attempt_at - now,
));
}
}
let lines = msgs
.iter()
.enumerate()
.map(|(i, msg)| {
let side = if msg.dir == "out" { "you" } else { "them" };
let body = sanitize::display_text(&msg.plaintext);
let tag = match tags[i].clone() {
Some(tag) => tag,
None if msg.dir == "out" => delivery_tag(&OutboxStatus::Sent, 0, 0),
None => String::new(),
};
if tag.is_empty() {
format!("{side}: {body}")
} else {
format!("{side}: {body} {tag}")
}
})
.collect();
(lines, summary)
}
/// Paste overlay copy. Error keeps the resubmit hint.
pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String {
let hint = match err {
@ -761,6 +960,78 @@ impl BackupPrompt {
}
}
/// The in-progress passphrase on the backup/restore screen: the hidden buffer
/// plus the first entry, kept across the second prompt of the backup flow.
///
/// Both are `Zeroizing<String>`, so the passphrase does not sit in a plain
/// heap `String` for the life of the screen; `close()` wipes eagerly on every
/// exit path (submit, mismatch, cancel) instead of waiting for the screen
/// value to be dropped, and the wrapper covers the paths that cannot call it
/// (Ctrl-Q, a panic).
pub struct PassphraseEntry {
first: Option<Zeroizing<String>>,
buf: Zeroizing<String>,
}
impl Default for PassphraseEntry {
fn default() -> Self {
Self {
first: None,
buf: Zeroizing::new(String::new()),
}
}
}
impl PassphraseEntry {
pub fn new() -> Self {
Self::default()
}
/// Second prompt of the backup flow: the first passphrase was already typed.
pub fn with_first(first: &str) -> Self {
Self {
first: Some(Zeroizing::new(first.to_string())),
..Self::default()
}
}
pub fn push(&mut self, c: char) {
self.buf.push(c);
}
pub fn backspace(&mut self) {
self.buf.pop();
}
/// What the screen echoes back — the passphrase itself is not drawn.
pub fn buf(&self) -> &str {
self.buf.as_str()
}
pub fn first(&self) -> Option<&str> {
self.first.as_deref().map(String::as_str)
}
/// Take the typed passphrase for submission, leaving this entry empty.
pub fn take_buf(&mut self) -> Zeroizing<String> {
std::mem::replace(&mut self.buf, Zeroizing::new(String::new()))
}
/// Take the first-passphrase copy for the confirm comparison.
pub fn take_first(&mut self) -> Option<Zeroizing<String>> {
self.first.take()
}
/// Wipe both buffers: the screen is done with them.
pub fn close(&mut self) {
self.buf.zeroize();
if let Some(first) = self.first.as_mut() {
first.zeroize();
}
self.first = None;
}
}
pub fn backup_screen_text() -> &'static str {
"Write encrypted identity backup?\n\
This file is your identity secret. Treat it like the database.\n\
@ -840,8 +1111,7 @@ enum Screen {
Passphrase {
kind: BackupKind,
path: String,
first: Option<String>,
buf: String,
entry: PassphraseEntry,
},
Quit {
prompt: QuitPrompt,
@ -929,6 +1199,7 @@ impl App {
let mut tip_cmd = None;
let mut file_cmd = None;
let mut chat_send = None;
let mut pass_submit = None;
match &mut self.screen {
Screen::Main => match key.code {
KeyCode::Tab => self.focus = self.focus.next(),
@ -1090,8 +1361,7 @@ impl App {
self.screen = Screen::Passphrase {
kind,
path: path.clone(),
first: None,
buf: String::new(),
entry: PassphraseEntry::new(),
};
}
}
@ -1101,25 +1371,17 @@ impl App {
_ => {}
}
}
Screen::Passphrase {
kind,
path,
first,
buf,
} => match key.code {
KeyCode::Esc => self.screen = Screen::Main,
KeyCode::Backspace => {
buf.pop();
Screen::Passphrase { kind, path, entry } => match key.code {
KeyCode::Esc => {
entry.close();
self.screen = Screen::Main;
}
KeyCode::Backspace => entry.backspace(),
KeyCode::Enter => {
let kind = *kind;
let path = path.clone();
let first = first.clone();
let pass = buf.clone();
self.submit_passphrase(kind, &path, first.as_deref(), &pass)?;
pass_submit = Some((*kind, path.clone(), entry.take_first(), entry.take_buf()));
}
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
buf.push(c);
entry.push(c);
}
_ => {}
},
@ -1166,6 +1428,9 @@ impl App {
if let Some(text) = chat_send {
self.send_chat(&text)?;
}
if let Some((kind, path, first, pass)) = pass_submit {
self.submit_passphrase(kind, &path, first.as_deref().map(String::as_str), &pass)?;
}
Ok(None)
}
@ -1279,8 +1544,7 @@ impl App {
self.screen = Screen::Passphrase {
kind,
path: path.to_string(),
first: Some(pass.to_string()),
buf: String::new(),
entry: PassphraseEntry::with_first(pass),
};
}
}
@ -1449,11 +1713,13 @@ impl App {
let (tx, rx) = mpsc::channel();
self.status_note = Some("sending".into());
std::mem::drop(self.rt.spawn(async move {
// send() now reports `Sent`/`Queued`; surfacing `queued` in the
// footer is a follow-up card, so this arm keeps today's wording.
// `send()` reports `Sent` when the circuit took it and `Queued` when
// the peer's onion is unreachable. The footer then reads the real
// row count from the outbox, so this note is only the first word.
let note = match node.send(&pk, &body).await {
Ok(_) => "sent".to_string(),
Err(e) => format!("send failed: {e}"),
Ok(OutboxStatus::Sent) => "sent".to_string(),
Ok(_) => "queued".to_string(),
Err(e) => format!("send failed: {}", short_send_reason(&e, FAIL_REASON_BUDGET)),
};
let _ = tx.send(note);
}));
@ -1487,9 +1753,9 @@ impl App {
Screen::Wipe { kind, prompt } => draw_wipe(f, *kind, prompt.typed()),
Screen::Profile { editor } => draw_profile(f, editor),
Screen::ConfirmKeys { kind, prompt, .. } => draw_confirm_keys(f, *kind, prompt.typed()),
Screen::Passphrase {
kind, first, buf, ..
} => draw_passphrase(f, *kind, first.is_some(), buf),
Screen::Passphrase { kind, entry, .. } => {
draw_passphrase(f, *kind, entry.first().is_some(), entry.buf())
}
Screen::Quit { prompt } => draw_quit(f, prompt.typed()),
}
if self.help_open {
@ -1563,38 +1829,22 @@ impl App {
}
f.render_stateful_widget(roster, panes[0], &mut roster_state);
let chat_lines = self.chat_lines();
let inner_h = panes[1].height.saturating_sub(2);
let nlines = chat_lines.len();
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16;
let scroll = self.chat_scroll.min(max_scroll);
let overflow = nlines > inner_h as usize && inner_h > 0;
let chat_title = {
let name = self.friends.get(self.selected).map(|friend| {
friend
.petname
.as_deref()
.unwrap_or(&friend.fingerprint)
.to_string()
});
let mut t = match name {
Some(n) => format!("chat {n}"),
None => "chat".to_string(),
};
if overflow {
let end = (scroll as usize + inner_h as usize).min(nlines);
t.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
}
let mark = if self.focus == Pane::Chat { "> " } else { " " };
format!("{mark}{t}")
};
let chat_text = chat_lines.join("\n");
let chat = Paragraph::new(chat_text)
.style(style_text())
.wrap(Wrap { trim: false })
.scroll((scroll, 0))
.block(self.pane_block(&chat_title, Pane::Chat));
f.render_widget(chat, panes[1]);
let (chat_lines, summary) = self.chat_view();
let chat_name = self.friends.get(self.selected).map(|friend| {
friend
.petname
.as_deref()
.unwrap_or(&friend.fingerprint)
.to_string()
});
draw_chat(
f,
panes[1],
&chat_lines,
chat_name.as_deref(),
self.focus == Pane::Chat,
self.chat_scroll,
);
let mark = if self.focus == Pane::Composer {
"> "
@ -1618,62 +1868,108 @@ impl App {
cols[3],
);
let footer = self.footer_line(area.width);
let footer = self.footer_line(area.width, &summary);
f.render_widget(Paragraph::new(footer).style(style_dim()), cols[4]);
}
fn footer_line(&self, width: u16) -> String {
fn footer_line(&self, width: u16, summary: &OutboxSummary) -> String {
// The outbox is the source of truth while anything is outstanding; the
// transient note still covers "sending", "sent file x", "invoice sent".
let note = summary.note().or_else(|| self.status_note.clone());
status_footer(
width,
&self.me_fp,
&self.me_onion,
self.status_note.as_deref(),
note.as_deref(),
footer_hints(&self.screen),
)
}
fn chat_lines(&self) -> Vec<String> {
fn chat_view(&self) -> (Vec<String>, OutboxSummary) {
let Some(friend) = self.friends.get(self.selected) else {
return vec![
"no friends yet".into(),
"F3 paste an invite to add one".into(),
];
return (
vec![
"no friends yet".into(),
"F3 paste an invite to add one".into(),
],
OutboxSummary::default(),
);
};
match self.node.list_messages(&friend.pubkey) {
Ok(msgs) if msgs.is_empty() => empty_friend_chat_text()
.lines()
.map(str::to_string)
.collect(),
Ok(msgs) => msgs
.iter()
.map(|m| {
let side = if m.dir == "out" { "you" } else { "them" };
format!("{side}: {}", sanitize::display_text(&m.plaintext))
})
.collect(),
Err(e) => vec![e],
Ok(msgs) => {
let pending = self.node.outbox_pending(&friend.pubkey).unwrap_or_default();
chat_with_delivery(&msgs, &pending, unix_now_secs())
}
Err(e) => (vec![e], OutboxSummary::default()),
}
}
fn pane_block<'a>(&self, title: &'a str, pane: Pane) -> Block<'a> {
let focused = self.focus == pane;
let border = if focused {
style_accent()
} else {
style_border()
};
let title_style = if focused {
style_accent().add_modifier(Modifier::BOLD)
} else {
style_dim()
};
apply_chrome_borders(Block::default())
.border_style(border)
.title(title)
.title_style(title_style)
pane_block_for(title, self.focus == pane)
}
}
/// Pane chrome without an `App`: focus is accent border + bold title, never
/// color alone (the `> ` marks come from the callers).
fn pane_block_for(title: &str, focused: bool) -> Block<'_> {
let border = if focused {
style_accent()
} else {
style_border()
};
let title_style = if focused {
style_accent().add_modifier(Modifier::BOLD)
} else {
style_dim()
};
apply_chrome_borders(Block::default())
.border_style(border)
.title(title)
.title_style(title_style)
}
fn unix_now_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
/// Real chat-pane renderer: `App::draw_main` calls this, so width, wrap and
/// delivery-marker behaviour are testable without constructing a `Node`.
pub fn draw_chat(
f: &mut Frame,
area: Rect,
lines: &[String],
name: Option<&str>,
focused: bool,
scroll: u16,
) {
let inner_h = area.height.saturating_sub(2);
let nlines = lines.len();
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16;
let scroll = scroll.min(max_scroll);
let overflow = nlines > inner_h as usize && inner_h > 0;
let mut title = match name {
Some(n) => format!("chat {n}"),
None => "chat".to_string(),
};
if overflow {
let end = (scroll as usize + inner_h as usize).min(nlines);
title.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
}
let mark = if focused { "> " } else { " " };
let title = format!("{mark}{title}");
f.render_widget(
Paragraph::new(lines.join("\n"))
.style(style_text())
.wrap(Wrap { trim: false })
.scroll((scroll, 0))
.block(pane_block_for(&title, focused)),
area,
);
}
/// Status bar: never drop a non-empty `status_note`. Always keep `TOR`, `me:`, `? help`.
pub fn status_footer(
width: u16,
@ -1689,7 +1985,7 @@ pub fn status_footer(
let mut note = status_note.unwrap_or("").trim().to_string();
if !note.is_empty()
&& color_mode() == ColorMode::None
&& (note.starts_with("send failed") || note == "fingerprint mismatch")
&& (note.contains("send failed") || note == "fingerprint mismatch")
&& !note.starts_with("! ")
{
note = format!("! {note}");
@ -2017,3 +2313,66 @@ fn to_hex(bytes: &[u8]) -> String {
fn io_err(e: io::Error) -> String {
e.to_string()
}
#[cfg(test)]
mod passphrase_buffer_tests {
use super::*;
fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
/// The typed passphrase lives in `Zeroizing` buffers, not in bare
/// `String`s that sit in the heap for the life of the screen.
#[test]
fn passphrase_buffers_are_zeroizing() {
let mut entry = PassphraseEntry::new();
entry.push('x');
let _: &Zeroizing<String> = &entry.buf;
let _: &Option<Zeroizing<String>> = &entry.first;
assert_zeroize_on_drop::<Zeroizing<String>>();
}
/// Closing the screen (submit, mismatch or cancel) must leave nothing of
/// the typed passphrase behind in its heap buffer.
#[test]
fn closing_the_passphrase_screen_wipes_the_typed_secret() {
let mut entry = PassphraseEntry::new();
for c in "hunter2-secret".chars() {
entry.push(c);
}
assert_eq!(entry.buf(), "hunter2-secret");
let ptr = entry.buf.as_ptr();
let cap = entry.buf.capacity();
assert!(cap >= 14, "expected a heap buffer, capacity {cap}");
entry.close();
assert!(entry.buf().is_empty(), "buffer not cleared");
// SAFETY: `close()` wipes through `Zeroize`, which zeroes the whole
// capacity and *keeps* the allocation (`Vec::zeroize`: zero the
// elements, clear the length, zero the spare capacity). `entry` still
// owns that buffer, so these `cap` bytes are live memory.
let bytes = unsafe { std::slice::from_raw_parts(ptr, cap) };
assert!(
bytes.iter().all(|b| *b == 0),
"typed passphrase survived close(): {bytes:?}"
);
}
/// The first entry of the two-step backup flow is a secret too, and the
/// screen holds it across the second prompt.
#[test]
fn closing_the_passphrase_screen_drops_the_first_entry_copy() {
let mut entry = PassphraseEntry::with_first("first-typed");
assert_eq!(entry.first(), Some("first-typed"));
entry.close();
assert_eq!(
entry.first(),
None,
"first passphrase copy survived close()"
);
}
}

View file

@ -42,8 +42,18 @@ impl std::fmt::Debug for Endpoint {
#[derive(Debug, Clone)]
pub struct Wallet {
endpoint: Option<Endpoint>,
no_spend: bool,
}
/// What /tip says when the wallet cannot spend. Same text for the explicit
/// `ONIONWIRE_WALLET_NO_SPEND=1` switch and for a view-only wallet detected over
/// RPC, so the operator never has to guess which one it was.
const VIEW_ONLY_MSG: &str = "wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work";
/// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in monero's
/// `src/wallet/wallet_rpc_server_error_codes.h`.
const WATCH_ONLY_CODE: i64 = -29;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransferRow {
pub txid: String,
@ -55,10 +65,17 @@ const RPC_TIMEOUT: Duration = Duration::from_secs(5);
impl Wallet {
pub fn disabled() -> Self {
Self { endpoint: None }
Self {
endpoint: None,
no_spend: false,
}
}
/// `ONIONWIRE_WALLET_NO_SPEND=1` asks for a view-only deployment: `/tip` is
/// refused locally, before any RPC dial. `/pay` and receipt verification
/// keep working.
pub fn from_env() -> Self {
let no_spend = env_flag("ONIONWIRE_WALLET_NO_SPEND");
match std::env::var("ONIONWIRE_WALLET_RPC") {
// The URL can carry `user:pass@` in its userinfo: keep it in a
// wiping buffer, not a bare `String`.
@ -71,23 +88,41 @@ impl Wallet {
match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) {
Ok(endpoint) => Self {
endpoint: Some(endpoint),
no_spend,
},
Err(e) => {
eprintln!("ONIONWIRE_WALLET_RPC: {e}");
Self::disabled()
Self {
endpoint: None,
no_spend,
}
}
}
}
_ => Self::disabled(),
_ => Self {
endpoint: None,
no_spend,
},
}
}
pub fn from_url(url: &str) -> Result<Self> {
Ok(Self {
endpoint: Some(parse_http_url(url, None)?),
no_spend: false,
})
}
/// No-spend (view-only) mode. Same switch as `ONIONWIRE_WALLET_NO_SPEND`.
pub fn with_no_spend(mut self, on: bool) -> Self {
self.no_spend = on;
self
}
pub fn no_spend(&self) -> bool {
self.no_spend
}
pub fn configured(&self) -> bool {
self.endpoint.is_some()
}
@ -107,7 +142,10 @@ impl Wallet {
}
pub async fn transfer(&self, address: &str, amount: u64) -> Result<String> {
let v = self
if self.no_spend {
return Err(Error(VIEW_ONLY_MSG.into()));
}
let sent = self
.rpc(
"transfer",
serde_json::json!({
@ -115,10 +153,36 @@ impl Wallet {
"account_index": 0
}),
)
.await?;
.await;
let v = match sent {
Ok(v) => v,
// The wallet's own refusal is opaque, so ask the documented
// pre-transfer signal before surfacing it. Fail closed: if the
// probe cannot answer, the original error stands.
Err(e) => {
if self.view_only().await {
return Err(Error(VIEW_ONLY_MSG.into()));
}
return Err(e);
}
};
json_str(&v, "tx_hash")
}
/// View-only detection over RPC: `query_key` with `key_type=spend_key` is
/// the signal monero actually exposes for a wallet with no spend key.
/// A view-only wallet answers `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (-29)
/// ("Cannot retrieve spend key"); a spend-capable wallet returns the key,
/// which this discards.
/// Source: `src/wallet/wallet_rpc_server.cpp` `on_query_key`.
async fn view_only(&self) -> bool {
matches!(
self.rpc("query_key", serde_json::json!({"key_type": "spend_key"}))
.await,
Err(e) if e.to_string() == VIEW_ONLY_MSG
)
}
pub async fn get_transfers(&self) -> Result<Vec<TransferRow>> {
let v = self
.rpc(
@ -189,6 +253,17 @@ fn credentials_required() -> Error {
Error("wallet RPC requires credentials (user:pass in URL or ONIONWIRE_WALLET_RPC_LOGIN)".into())
}
/// `1` / `true` / `yes` / `on` (case-insensitive) mean set; anything else (or
/// unset) means off.
fn env_flag(name: &str) -> bool {
matches!(
std::env::var(name)
.map(|v| v.trim().to_ascii_lowercase())
.as_deref(),
Ok("1" | "true" | "yes" | "on")
)
}
fn parse_login(login: &str) -> Result<(String, Zeroizing<String>)> {
let (user, pass) = login.split_once(':').ok_or_else(credentials_required)?;
if user.is_empty() || pass.is_empty() {
@ -455,6 +530,11 @@ fn parse_json_rpc(raw: &[u8]) -> Result<serde_json::Value> {
.get("message")
.and_then(|m| m.as_str())
.unwrap_or("rpc error");
// The one RPC-level error we translate: a view-only wallet has no
// spend key (monero `WALLET_RPC_ERROR_CODE_WATCH_ONLY`).
if err.get("code").and_then(|c| c.as_i64()) == Some(WATCH_ONLY_CODE) {
return Err(Error(VIEW_ONLY_MSG.into()));
}
return Err(Error(msg.into()));
}
json.get("result")