5041 lines
204 KiB
Rust
5041 lines
204 KiB
Rust
|
|
//! Two-node onion session: host HS, Noise IK, persist plaintext locally.
|
||
|
|
|
||
|
|
use std::path::{Path, PathBuf};
|
||
|
|
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||
|
|
use std::sync::{Arc, Mutex};
|
||
|
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||
|
|
|
||
|
|
use futures::StreamExt;
|
||
|
|
use futures::io::{AsyncRead, AsyncWrite};
|
||
|
|
use hkdf::Hkdf;
|
||
|
|
use rand::rngs::OsRng;
|
||
|
|
use sha2::Sha256;
|
||
|
|
use tor_cell::relaycell::msg::Connected;
|
||
|
|
use tor_hsservice::{RunningOnionService, handle_rend_requests};
|
||
|
|
use x25519_dalek::{PublicKey as X25519Public, StaticSecret};
|
||
|
|
use zeroize::Zeroizing;
|
||
|
|
|
||
|
|
use crate::dispatch::{self, Kind};
|
||
|
|
use crate::file;
|
||
|
|
use crate::frame;
|
||
|
|
use crate::hs::{self, Client, HS_PORT, TorState};
|
||
|
|
use crate::loc;
|
||
|
|
use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus};
|
||
|
|
use crate::pay;
|
||
|
|
use crate::profile;
|
||
|
|
use crate::qr;
|
||
|
|
use crate::ratchet::{RatchetKeyPair, RatchetState};
|
||
|
|
use crate::ratelimit::TokenBucket;
|
||
|
|
use crate::sanitize;
|
||
|
|
use crate::session::{self, Keys};
|
||
|
|
use crate::store::{
|
||
|
|
Friend, FriendProfile, Message, NewWallet, Payment, PaymentWrite, Store, WalletRecord,
|
||
|
|
};
|
||
|
|
use crate::wallet::{self, ChainNetwork, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus};
|
||
|
|
use crate::wallet_child::{
|
||
|
|
ChildConfig, ChildWalletState, WalletChild, WalletChildState, WalletChildStatus,
|
||
|
|
wallet_name_taken,
|
||
|
|
};
|
||
|
|
|
||
|
|
pub struct RotateResult {
|
||
|
|
pub notified: usize,
|
||
|
|
pub friends: usize,
|
||
|
|
}
|
||
|
|
|
||
|
|
/// What a `flush` actually managed to do, for UI surfacing.
|
||
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
|
|
pub struct FlushOutcome {
|
||
|
|
/// Outbox rows we tried to deliver in this pass.
|
||
|
|
pub attempted: usize,
|
||
|
|
/// Rows delivered now — their outbox rows are gone.
|
||
|
|
pub delivered: usize,
|
||
|
|
/// Rows still queued or terminally failed after the pass.
|
||
|
|
pub remaining: usize,
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A foreground/unlock flush is bounded: the caller is a UI thread and a dead
|
||
|
|
/// peer's onion can hold a dial open for 20s. Whatever is left stays queued and
|
||
|
|
/// the retry worker picks it up on its normal schedule.
|
||
|
|
pub const FLUSH_TIMEOUT: Duration = Duration::from_secs(30);
|
||
|
|
/// The drain inside `shutdown` gets a shorter budget: teardown must not hang
|
||
|
|
/// the caller behind a Tor dial. Undelivered rows survive in sqlite.
|
||
|
|
pub const SHUTDOWN_FLUSH_TIMEOUT: Duration = Duration::from_secs(10);
|
||
|
|
/// Budget for the direct loopback `get_info` a child refresh makes when the
|
||
|
|
/// wallet RPC is not answering. Local TCP only — a refused daemon returns
|
||
|
|
/// immediately, and a live one answers in milliseconds.
|
||
|
|
const DAEMON_PROBE_BUDGET: Duration = Duration::from_secs(3);
|
||
|
|
|
||
|
|
struct HsHandle {
|
||
|
|
svc: Arc<RunningOnionService>,
|
||
|
|
rend: tokio::task::JoinHandle<()>,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl Drop for HsHandle {
|
||
|
|
fn drop(&mut self) {
|
||
|
|
self.rend.abort();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Abort the outbox worker when the node goes away.
|
||
|
|
struct WorkerHandle(tokio::task::JoinHandle<()>);
|
||
|
|
|
||
|
|
impl Drop for WorkerHandle {
|
||
|
|
fn drop(&mut self) {
|
||
|
|
self.0.abort();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A wallet just created on the wallet RPC and recorded in the store's
|
||
|
|
/// catalogue: the row is what makes it survive a restart, and the seed is the
|
||
|
|
/// one-time backup the UI shows before the wallet is used. The caller owns
|
||
|
|
/// wiping `seed` (the TUI moves it straight into a `Zeroizing`).
|
||
|
|
pub struct CreatedWallet {
|
||
|
|
/// The stored catalogue row, with the id and `created_at` the store
|
||
|
|
/// assigned. `wallet_filename` is the file this wallet lives in.
|
||
|
|
pub record: WalletRecord,
|
||
|
|
/// The 25-word seed, returned once by the create path.
|
||
|
|
pub seed: String,
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Hand-written so a stray `{:?}` cannot print the seed: the record is the
|
||
|
|
/// wallet, the mnemonic is the money.
|
||
|
|
impl std::fmt::Debug for CreatedWallet {
|
||
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||
|
|
f.debug_struct("CreatedWallet")
|
||
|
|
.field("record", &self.record)
|
||
|
|
.field("seed", &"<redacted>")
|
||
|
|
.finish()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
pub struct Node {
|
||
|
|
home: PathBuf,
|
||
|
|
store: Arc<Mutex<Store>>,
|
||
|
|
client: Client,
|
||
|
|
hs: Mutex<Option<HsHandle>>,
|
||
|
|
onion: Mutex<String>,
|
||
|
|
keys: Mutex<Keys>,
|
||
|
|
/// Behind a lock because the F7 screen can re-point it at a saved config
|
||
|
|
/// without a restart. Clone it out (`wallet_snapshot`) before awaiting: a
|
||
|
|
/// `std::sync::Mutex` guard must not live across an `.await`.
|
||
|
|
wallet: Mutex<Wallet>,
|
||
|
|
/// Last probe result, for the draw path. Cheap to read, never dials.
|
||
|
|
wallet_status: Mutex<WalletStatus>,
|
||
|
|
/// The app-owned wallet child, once one has been started. `None` until
|
||
|
|
/// `start_wallet_child`, and `None` again after `stop_wallet_child` — the
|
||
|
|
/// child is never started implicitly.
|
||
|
|
wallet_child: Mutex<Option<Arc<WalletChild>>>,
|
||
|
|
/// Did the running child's wallet report a synced chain at the last probe?
|
||
|
|
/// Only `wallet_child_refresh` writes it; the draw path only reads it.
|
||
|
|
child_synced: AtomicBool,
|
||
|
|
/// Blocks the chain daemon had at the last probe. `0` means unknown: never
|
||
|
|
/// probed, the child is off/exited, or the probe failed. Only
|
||
|
|
/// `wallet_child_refresh` writes it; the draw path only reads it.
|
||
|
|
child_height: AtomicU64,
|
||
|
|
/// Blocks the daemon was syncing towards at the last probe. `0` means the
|
||
|
|
/// daemon reported none — not the same as caught up.
|
||
|
|
child_target: AtomicU64,
|
||
|
|
/// The last child failure, display-ready. Cleared on a successful start.
|
||
|
|
child_error: Mutex<Option<String>>,
|
||
|
|
/// Whether the running child's wallet **file** is open. Not derivable from
|
||
|
|
/// the process: `monero-wallet-rpc` starts with no wallet open, so a live
|
||
|
|
/// child that answers every call with `-13 No wallet file` is a child
|
||
|
|
/// waiting for a passphrase, not a healthy one. Only the start path, an
|
||
|
|
/// explicit open, and a successful probe write it.
|
||
|
|
child_wallet: Mutex<ChildWalletState>,
|
||
|
|
incoming_limit: Mutex<TokenBucket>,
|
||
|
|
inbox: Mutex<file::Inbox>,
|
||
|
|
outbox: Arc<Outbox>,
|
||
|
|
worker: Mutex<Option<WorkerHandle>>,
|
||
|
|
/// Set by `shutdown`. Checked before any operation that would touch Tor or
|
||
|
|
/// the store, so a stopped node fails cleanly instead of dialing.
|
||
|
|
stopped: AtomicBool,
|
||
|
|
/// Has this node's onion service ever crossed the reachability bar (status
|
||
|
|
/// `Running`/`DegradedReachable`, or a successful probe of our own onion)?
|
||
|
|
/// Arti's combined status can stay `Bootstrapping` for minutes *after* the
|
||
|
|
/// descriptor is downloadable, so without this the UI would keep saying
|
||
|
|
/// "starting" long past the point where friends can reach us. Cleared when
|
||
|
|
/// `rotate` hard-cuts the service.
|
||
|
|
onion_reachable: AtomicBool,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl Node {
|
||
|
|
pub async fn start(home: PathBuf) -> Result<Arc<Self>, String> {
|
||
|
|
let pass = Zeroizing::new(
|
||
|
|
std::env::var("ONIONWIRE_STORE_PASSPHRASE")
|
||
|
|
.map_err(|_| "ONIONWIRE_STORE_PASSPHRASE required".to_string())?,
|
||
|
|
);
|
||
|
|
if pass.is_empty() {
|
||
|
|
return Err("empty passphrase".into());
|
||
|
|
}
|
||
|
|
Self::start_with_passphrase(home, pass.as_str()).await
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn start_with_passphrase(
|
||
|
|
home: PathBuf,
|
||
|
|
passphrase: &str,
|
||
|
|
) -> Result<Arc<Self>, String> {
|
||
|
|
let store = Store::open_at_with_passphrase(&home, passphrase).map_err(|e| e.to_string())?;
|
||
|
|
// Stored config first (the F7 screen's), env as the migration path.
|
||
|
|
let stored_wallet = store.load_wallet_config().map_err(|e| e.to_string())?;
|
||
|
|
let wallet = Wallet::for_boot(stored_wallet.as_ref());
|
||
|
|
let wallet_status = WalletStatus::idle(wallet.configured());
|
||
|
|
let me = store.self_identity().map_err(|e| e.to_string())?;
|
||
|
|
let keys = Keys::from_self(&me).map_err(|e| e.to_string())?;
|
||
|
|
let nickname = store.hs_nickname().map_err(|e| e.to_string())?;
|
||
|
|
let state = home.join("arti");
|
||
|
|
let cache = home.join("cache");
|
||
|
|
let client = hs::bootstrapped(&state, &cache).await?;
|
||
|
|
let launched = client
|
||
|
|
.launch_onion_service(hs::hs_config(&nickname)?)
|
||
|
|
.map_err(|e| format!("launch_onion_service: {e}"))?
|
||
|
|
.ok_or_else(|| "onion service disabled in config — fail closed".to_string())?;
|
||
|
|
let (svc, rend) = launched;
|
||
|
|
let onion = hs::onion_string(&svc)?;
|
||
|
|
let inbox = file::Inbox::new(home.join("inbox"));
|
||
|
|
let store = Arc::new(Mutex::new(store));
|
||
|
|
let outbox = Arc::new(Outbox::new(
|
||
|
|
Arc::clone(&store),
|
||
|
|
Arc::new(ArtiDeliverer::new(client.clone(), keys.clone())),
|
||
|
|
));
|
||
|
|
if let Err(e) = outbox.reset_stale() {
|
||
|
|
eprintln!("outbox: {e}");
|
||
|
|
}
|
||
|
|
let node = Arc::new(Self {
|
||
|
|
home,
|
||
|
|
store,
|
||
|
|
client,
|
||
|
|
hs: Mutex::new(None),
|
||
|
|
onion: Mutex::new(onion.clone()),
|
||
|
|
keys: Mutex::new(keys),
|
||
|
|
wallet: Mutex::new(wallet),
|
||
|
|
wallet_status: Mutex::new(wallet_status),
|
||
|
|
wallet_child: Mutex::new(None),
|
||
|
|
child_synced: AtomicBool::new(false),
|
||
|
|
child_height: AtomicU64::new(0),
|
||
|
|
child_target: AtomicU64::new(0),
|
||
|
|
child_error: Mutex::new(None),
|
||
|
|
child_wallet: Mutex::new(ChildWalletState::Unknown),
|
||
|
|
incoming_limit: Mutex::new(TokenBucket::default()),
|
||
|
|
inbox: Mutex::new(inbox),
|
||
|
|
outbox: Arc::clone(&outbox),
|
||
|
|
worker: Mutex::new(Some(WorkerHandle(outbox.spawn_worker()))),
|
||
|
|
stopped: AtomicBool::new(false),
|
||
|
|
onion_reachable: AtomicBool::new(false),
|
||
|
|
});
|
||
|
|
// Unlock trigger: flush anything queued by a previous run now, in the
|
||
|
|
// background, rather than waiting out its backoff.
|
||
|
|
spawn_flush_all(Arc::clone(&node.outbox));
|
||
|
|
// Accept rens before waiting so a reachability probe can succeed
|
||
|
|
// while combined status is still Bootstrapping.
|
||
|
|
let rend = spawn_rend(Arc::clone(&node), rend);
|
||
|
|
*node.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle {
|
||
|
|
svc: Arc::clone(&svc),
|
||
|
|
rend,
|
||
|
|
});
|
||
|
|
hs::wait_until_published(&node.client, &svc, &onion).await?;
|
||
|
|
// Published by the same bar `wait_until_published` uses — a probe
|
||
|
|
// success counts, which is the whole reason `tor_state` tracks it
|
||
|
|
// separately from Arti's (slower, flappier) combined status.
|
||
|
|
node.onion_reachable.store(true, Ordering::SeqCst);
|
||
|
|
node.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.set_onion(&onion)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(node)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Observable onion/Tor lifecycle state: `Bootstrapping` / `Published` /
|
||
|
|
/// `DegradedReachable` / `Stopped`.
|
||
|
|
///
|
||
|
|
/// Read-only and cheap (one mutex + one status read, no I/O), so a UI or a
|
||
|
|
/// foreground-service notification can poll it instead of guessing from a
|
||
|
|
/// timer. A poisoned handle is reported as `Stopped` rather than panicking:
|
||
|
|
/// the node is unusable either way, and the caller is often a UI thread.
|
||
|
|
pub fn tor_state(&self) -> TorState {
|
||
|
|
let stopped = self.stopped.load(Ordering::SeqCst);
|
||
|
|
let reachable = self.onion_reachable.load(Ordering::SeqCst);
|
||
|
|
match self.hs.lock() {
|
||
|
|
Ok(guard) => match guard.as_ref() {
|
||
|
|
Some(h) => hs::tor_state_of(h.svc.status().state(), stopped, reachable),
|
||
|
|
// Between `rotate`'s hard cut and the new service being
|
||
|
|
// installed there is no handle; before the first publish there
|
||
|
|
// is none either. Both are "not serving *yet*" unless we stopped.
|
||
|
|
None if stopped => TorState::Stopped,
|
||
|
|
None => TorState::Bootstrapping,
|
||
|
|
},
|
||
|
|
Err(_) => TorState::Stopped,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Drain the outbox: one delivery attempt for every outstanding row, now,
|
||
|
|
/// ignoring its retry schedule. Then checkpoint the WAL.
|
||
|
|
///
|
||
|
|
/// This is the "deliver what is deliverable before we lose the process"
|
||
|
|
/// call. Bounded by [`FLUSH_TIMEOUT`] because a dead peer's onion holds a
|
||
|
|
/// dial for ~20s and the caller is usually a UI thread. Rows that could not
|
||
|
|
/// be delivered stay queued and are picked up by the retry worker on its
|
||
|
|
/// normal backoff.
|
||
|
|
pub async fn flush(&self) -> Result<FlushOutcome, String> {
|
||
|
|
self.ensure_running()?;
|
||
|
|
let outcome = self.drain(FLUSH_TIMEOUT).await?;
|
||
|
|
self.checkpoint();
|
||
|
|
Ok(outcome)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Stop the node.
|
||
|
|
///
|
||
|
|
/// Order matters: drain the outbox while the Tor client is still alive,
|
||
|
|
/// then drop the onion service (its rendezvous task is aborted and the v3
|
||
|
|
/// service goes down), then abort the retry worker so nothing dials after
|
||
|
|
/// this, then checkpoint the WAL.
|
||
|
|
///
|
||
|
|
/// Idempotent: the flag is swapped first, so a second call — or a call
|
||
|
|
/// racing another teardown — returns `Ok(())` without touching anything
|
||
|
|
/// twice. Every other method on a stopped node returns a clean `Err`, never
|
||
|
|
/// a panic. A process killed outright never gets here at all, which is why
|
||
|
|
/// [`flush`](Self::flush) exists.
|
||
|
|
pub async fn shutdown(&self) -> Result<(), String> {
|
||
|
|
if self.stopped.swap(true, Ordering::SeqCst) {
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
// Bounded: teardown must not hang behind a Tor dial. Undelivered rows
|
||
|
|
// survive in sqlite and are retried on the next unlock.
|
||
|
|
match self.drain(SHUTDOWN_FLUSH_TIMEOUT).await {
|
||
|
|
Ok(o) if o.remaining > 0 => {
|
||
|
|
eprintln!("shutdown: {} outbox row(s) still pending", o.remaining)
|
||
|
|
}
|
||
|
|
Ok(_) => {}
|
||
|
|
Err(e) => eprintln!("shutdown: drain failed: {e}"),
|
||
|
|
}
|
||
|
|
match self.hs.lock() {
|
||
|
|
Ok(mut g) => *g = None,
|
||
|
|
Err(_) => eprintln!("shutdown: onion-service lock poisoned"),
|
||
|
|
}
|
||
|
|
match self.worker.lock() {
|
||
|
|
Ok(mut g) => drop(g.take()),
|
||
|
|
Err(_) => eprintln!("shutdown: outbox-worker lock poisoned"),
|
||
|
|
}
|
||
|
|
// The app owns these processes: an exit that left `monero-wallet-rpc`
|
||
|
|
// (a spend authority behind a loopback socket) or `monerod` behind would
|
||
|
|
// outlive the node that started them.
|
||
|
|
match self.wallet_child.lock().map(|mut g| g.take()) {
|
||
|
|
Ok(Some(child)) => {
|
||
|
|
self.reset_child_probe();
|
||
|
|
if let Err(e) = child.stop() {
|
||
|
|
eprintln!("shutdown: wallet child stop failed: {e}");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Ok(None) => {}
|
||
|
|
Err(_) => eprintln!("shutdown: wallet-child lock poisoned"),
|
||
|
|
}
|
||
|
|
self.checkpoint();
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// One bounded pass over every outstanding outbox row.
|
||
|
|
///
|
||
|
|
/// A timeout cancels the pass mid-flight, which can leave a row in
|
||
|
|
/// `sending`; `Outbox::reset_stale` requeues those on the next unlock, the
|
||
|
|
/// same recovery the parent uses for a process that died mid-attempt.
|
||
|
|
async fn drain(&self, budget: Duration) -> Result<FlushOutcome, String> {
|
||
|
|
let attempted = match tokio::time::timeout(budget, self.outbox.flush_all(unix_now())).await
|
||
|
|
{
|
||
|
|
Ok(Ok(rows)) => Some(rows),
|
||
|
|
Ok(Err(e)) => return Err(e),
|
||
|
|
Err(_) => {
|
||
|
|
eprintln!("outbox: drain hit its {budget:?} budget, undelivered rows stay queued");
|
||
|
|
None
|
||
|
|
}
|
||
|
|
};
|
||
|
|
let delivered = attempted
|
||
|
|
.as_ref()
|
||
|
|
.map(|rows| {
|
||
|
|
rows.iter()
|
||
|
|
.filter(|(_, s)| matches!(s, OutboxStatus::Sent))
|
||
|
|
.count()
|
||
|
|
})
|
||
|
|
.unwrap_or(0);
|
||
|
|
Ok(FlushOutcome {
|
||
|
|
// `None` means the pass was cancelled: we know how many rows are
|
||
|
|
// still queued, not how many were started.
|
||
|
|
attempted: attempted.as_ref().map(Vec::len).unwrap_or(0),
|
||
|
|
delivered,
|
||
|
|
remaining: self.pending_rows()?,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Rows the outbox still holds for every friend, queued or terminally
|
||
|
|
/// failed. A message absent here was delivered.
|
||
|
|
fn pending_rows(&self) -> Result<usize, String> {
|
||
|
|
let friends = self.list_friends()?;
|
||
|
|
let mut n = 0usize;
|
||
|
|
for f in &friends {
|
||
|
|
n += self.outbox.pending(&f.pubkey)?.len();
|
||
|
|
}
|
||
|
|
Ok(n)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Checkpoint the sqlite WAL into the main db file and truncate it.
|
||
|
|
///
|
||
|
|
/// Best effort on purpose: WAL replay on open recovers everything committed,
|
||
|
|
/// so this is about leaving less to replay (and less on disk) if the
|
||
|
|
/// process is killed right after teardown — not about correctness.
|
||
|
|
fn checkpoint(&self) {
|
||
|
|
let store = match self.store.lock() {
|
||
|
|
Ok(s) => s,
|
||
|
|
Err(e) => {
|
||
|
|
eprintln!("wal checkpoint: store lock poisoned: {e}");
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
};
|
||
|
|
if let Err(e) = store.checkpoint_wal() {
|
||
|
|
eprintln!("wal checkpoint: {e}");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
fn ensure_running(&self) -> Result<(), String> {
|
||
|
|
if self.stopped.load(Ordering::SeqCst) {
|
||
|
|
return Err("node is stopped — open the identity again".to_string());
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn onion(&self) -> String {
|
||
|
|
self.onion.lock().map(|g| g.clone()).unwrap_or_default()
|
||
|
|
}
|
||
|
|
|
||
|
|
fn keys(&self) -> Result<Keys, String> {
|
||
|
|
self.keys
|
||
|
|
.lock()
|
||
|
|
.map(|g| g.clone())
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn identity_pk(&self) -> [u8; 32] {
|
||
|
|
self.keys().map(|k| k.identity_pk).unwrap_or([0; 32])
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn arti_dir(&self) -> PathBuf {
|
||
|
|
self.home.join("arti")
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn cache_dir(&self) -> PathBuf {
|
||
|
|
self.home.join("cache")
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn qr_payload(&self) -> Result<String, String> {
|
||
|
|
let k = self.keys()?;
|
||
|
|
qr::encode(&k.identity_sk, &self.onion(), &k.prekey_pk).map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn write_backup(&self, path: &str, passphrase: &str) -> Result<(), String> {
|
||
|
|
use std::io::Write;
|
||
|
|
use std::os::unix::fs::OpenOptionsExt;
|
||
|
|
let k = self.keys()?;
|
||
|
|
let blob = crate::backup::seal(
|
||
|
|
passphrase,
|
||
|
|
&crate::backup::BackupKeys {
|
||
|
|
identity_sk: k.identity_sk,
|
||
|
|
identity_pk: k.identity_pk,
|
||
|
|
prekey_sk: k.prekey_sk,
|
||
|
|
prekey_pk: k.prekey_pk,
|
||
|
|
},
|
||
|
|
)?;
|
||
|
|
let mut f = std::fs::OpenOptions::new()
|
||
|
|
.write(true)
|
||
|
|
.create(true)
|
||
|
|
.truncate(true)
|
||
|
|
.mode(0o600)
|
||
|
|
.open(path)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
f.write_all(&blob).map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn restore_backup(&self, path: &str, passphrase: &str) -> Result<(), String> {
|
||
|
|
let blob = std::fs::read(path).map_err(|e| e.to_string())?;
|
||
|
|
let k = crate::backup::open(passphrase, &blob)?;
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.replace_identity_keys(&k.identity_sk, &k.identity_pk, &k.prekey_sk, &k.prekey_pk)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
*self.keys.lock().map_err(|e| e.to_string())? = Keys {
|
||
|
|
identity_sk: k.identity_sk,
|
||
|
|
identity_pk: k.identity_pk,
|
||
|
|
prekey_sk: k.prekey_sk,
|
||
|
|
prekey_pk: k.prekey_pk,
|
||
|
|
};
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn add_friend_from_qr(&self, raw: &str) -> Result<(), String> {
|
||
|
|
let p = qr::decode(raw).map_err(|e| e.to_string())?;
|
||
|
|
self.add_friend_payload(&p)
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn add_friend_payload(&self, p: &qr::QrPayload) -> Result<(), String> {
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
let prekey_changed = store
|
||
|
|
.get_friend(&p.pubkey)
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.map(|f| f.prekey != p.signed_prekey)
|
||
|
|
.unwrap_or(false);
|
||
|
|
store
|
||
|
|
.upsert_friend(&p.pubkey, &p.onion, None)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.set_friend_prekey(&p.pubkey, &p.signed_prekey)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
if prekey_changed {
|
||
|
|
// The bootstrap epoch is derived from the peers' static prekey DH,
|
||
|
|
// so a refreshed invite makes the stored ratchet state unusable on
|
||
|
|
// both sides. Drop it: the next frame rebuilds a fresh state.
|
||
|
|
store.clear_ratchet(&p.pubkey).map_err(|e| e.to_string())?;
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn get_friend(&self, pubkey: &[u8]) -> Result<Option<Friend>, String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.get_friend(pubkey)
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn list_friends(&self) -> Result<Vec<Friend>, String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.list_friends()
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Fingerprint of our own identity key (identity = pubkey).
|
||
|
|
pub fn fingerprint(&self) -> Result<String, String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.self_fingerprint()
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Local-only label. Does not go on the wire.
|
||
|
|
pub fn set_petname(&self, pubkey: &[u8], petname: Option<&str>) -> Result<(), String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.set_petname(pubkey, petname)
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn friend(&self, pubkey: &[u8]) -> Result<Friend, String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.get_friend(pubkey)
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.ok_or_else(|| "friend not found".into())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn list_messages(&self, friend_pk: &[u8]) -> Result<Vec<Message>, String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.list_messages(friend_pk)
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The signed `/pay` invoices and `/tip` receipts that came from one peer,
|
||
|
|
/// oldest row first. A friend with no payment rows is an empty vector, not
|
||
|
|
/// an error.
|
||
|
|
///
|
||
|
|
/// Read-only and fail-closed: it locks the store and nothing else — no Tor
|
||
|
|
/// dial, no wallet RPC. `memo` is the text the peer signed, stored and
|
||
|
|
/// returned as it arrived; a renderer sanitizes it with
|
||
|
|
/// [`crate::sanitize::display_text`] at draw time, exactly as the chat
|
||
|
|
/// bodies from [`Self::list_messages`] are.
|
||
|
|
pub fn list_payments(&self, friend_pk: &[u8]) -> Result<Vec<Payment>, String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.list_payments(friend_pk)
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The live wallet, cloned out of its lock. Every wallet call goes through
|
||
|
|
/// this so a `std::sync::Mutex` guard never lives across an `.await`, and so
|
||
|
|
/// the F7 screen can re-point the wallet mid-session.
|
||
|
|
fn wallet_snapshot(&self) -> Wallet {
|
||
|
|
self.wallet
|
||
|
|
.lock()
|
||
|
|
.map(|w| w.clone())
|
||
|
|
.unwrap_or_else(|_| Wallet::disabled())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The snapshot the TUI draws. Cheap: no dial, no lock on the RPC. It says
|
||
|
|
/// "configured, not probed" (`connected == false`) until a probe has run.
|
||
|
|
pub fn wallet_status(&self) -> WalletStatus {
|
||
|
|
self.wallet_status
|
||
|
|
.lock()
|
||
|
|
.map(|s| s.clone())
|
||
|
|
.unwrap_or_else(|_| WalletStatus::idle(self.wallet_snapshot().configured()))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Probe the configured endpoint once and fold the result into the snapshot.
|
||
|
|
/// This is the only thing that can flip `connected` to true.
|
||
|
|
pub async fn wallet_refresh(&self) -> WalletStatus {
|
||
|
|
let w = self.wallet_snapshot();
|
||
|
|
let status = w.status().await;
|
||
|
|
if let Ok(mut slot) = self.wallet_status.lock() {
|
||
|
|
*slot = status.clone();
|
||
|
|
}
|
||
|
|
status
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The pay/tip readiness guard. Blocking-friendly: the TUI calls this from
|
||
|
|
/// its key handler with `rt.block_on`, like `send_pay`/`send_tip` do.
|
||
|
|
///
|
||
|
|
/// It never dials Tor. It also never dials the wallet when the answer is
|
||
|
|
/// already known locally — an unconfigured wallet and a `/tip` on a
|
||
|
|
/// view-only wallet are refused before any socket is opened.
|
||
|
|
pub async fn wallet_readiness(&self, is_tip: bool) -> Readiness {
|
||
|
|
let w = self.wallet_snapshot();
|
||
|
|
if !w.configured() {
|
||
|
|
return Readiness::NotConfigured;
|
||
|
|
}
|
||
|
|
if is_tip && w.no_spend() {
|
||
|
|
return Readiness::NoSpend;
|
||
|
|
}
|
||
|
|
let status = self.wallet_refresh().await;
|
||
|
|
wallet::readiness(status.configured, status.connected, w.no_spend(), is_tip)
|
||
|
|
}
|
||
|
|
|
||
|
|
// ----- the app-owned wallet child (`src/wallet_child.rs`) ----------------
|
||
|
|
|
||
|
|
pub fn home(&self) -> &Path {
|
||
|
|
&self.home
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The child settings this node would spawn with: the stored record, or the
|
||
|
|
/// defaults (receive-only, binaries by name) when nothing was ever set.
|
||
|
|
pub fn wallet_child_config(&self) -> ChildConfig {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.ok()
|
||
|
|
.and_then(|store| store.load_wallet_child().ok().flatten())
|
||
|
|
.and_then(|raw| ChildConfig::from_record(&raw).ok().flatten())
|
||
|
|
.unwrap_or_default()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Persist the settings a config screen or the SDK set. Validated first, so
|
||
|
|
/// a rejected config is never written; the creds already in the record are
|
||
|
|
/// preserved. A running child is not restarted — the change applies on the
|
||
|
|
/// next `start_wallet_child`.
|
||
|
|
pub fn set_wallet_child_config(&self, cfg: &ChildConfig) -> Result<(), String> {
|
||
|
|
cfg.validate().map_err(|e| e.to_string())?;
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
let existing = store.load_wallet_child().map_err(|e| e.to_string())?;
|
||
|
|
let record = crate::wallet_child::merge_record(existing.as_deref(), cfg.record_fields());
|
||
|
|
store
|
||
|
|
.save_wallet_child(&record)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Store an in-process Cuprate source. Datadirs are split so a pruned
|
||
|
|
/// mainnet store cannot mix with a full one (Cuprate cannot un-prune).
|
||
|
|
pub fn set_in_process_cuprate(
|
||
|
|
&self,
|
||
|
|
network: ChainNetwork,
|
||
|
|
prune: bool,
|
||
|
|
) -> Result<(), String> {
|
||
|
|
let mut cfg = self.wallet_child_config();
|
||
|
|
if cfg.wallet_rpc_bin.as_os_str().is_empty() {
|
||
|
|
cfg.wallet_rpc_bin = PathBuf::from("monero-wallet-rpc");
|
||
|
|
}
|
||
|
|
let name = match (network, prune) {
|
||
|
|
(ChainNetwork::Mainnet, true) => "mainnet-pruned",
|
||
|
|
(ChainNetwork::Mainnet, false) => "mainnet-full",
|
||
|
|
(ChainNetwork::Testnet, _) => "testnet",
|
||
|
|
};
|
||
|
|
cfg.source = ChainSource::InProcessCuprate {
|
||
|
|
datadir: self.home.join("chain").join(name),
|
||
|
|
network,
|
||
|
|
prune: matches!(network, ChainNetwork::Mainnet) && prune,
|
||
|
|
};
|
||
|
|
self.set_wallet_child_config(&cfg)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Point the wallet child at a chain daemon the user runs elsewhere.
|
||
|
|
/// Same shape as [`Self::set_in_process_cuprate`]: read-modify-write on the
|
||
|
|
/// stored settings, an empty `wallet_rpc_bin` filled in, and validation
|
||
|
|
/// before anything is written. A `.onion` host needs no special case here —
|
||
|
|
/// the child pulls in the SOCKS proxy for it (`ChainSource::is_onion`).
|
||
|
|
pub fn set_remote_daemon(&self, host: &str, port: u16) -> Result<(), String> {
|
||
|
|
let mut cfg = self.wallet_child_config();
|
||
|
|
if cfg.wallet_rpc_bin.as_os_str().is_empty() {
|
||
|
|
cfg.wallet_rpc_bin = PathBuf::from("monero-wallet-rpc");
|
||
|
|
}
|
||
|
|
cfg.source = ChainSource::Remote {
|
||
|
|
host: host.trim().to_string(),
|
||
|
|
port,
|
||
|
|
};
|
||
|
|
self.set_wallet_child_config(&cfg)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Spawn a local `monerod`. Datadirs are split exactly as they are for the
|
||
|
|
/// in-process daemon so a pruned store cannot mix with a full one.
|
||
|
|
pub fn set_local_monerod(&self, monerod_bin: &Path, prune: bool) -> Result<(), String> {
|
||
|
|
let datadir = self.local_chain_datadir(prune);
|
||
|
|
self.set_local_monerod_at(monerod_bin, &datadir, prune)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The chain datadir a local node uses when the user did not name one.
|
||
|
|
/// Split by prune mode exactly as it always was, so an existing install
|
||
|
|
/// keeps the store it already has.
|
||
|
|
pub fn local_chain_datadir(&self, prune: bool) -> PathBuf {
|
||
|
|
self.home
|
||
|
|
.join("chain")
|
||
|
|
.join(if prune { "mainnet-pruned" } else { "mainnet-full" })
|
||
|
|
}
|
||
|
|
|
||
|
|
/// [`Self::set_local_monerod`], with the chain datadir spelled out — the
|
||
|
|
/// shape the F7 screen saves when the user typed one.
|
||
|
|
///
|
||
|
|
/// An empty datadir is refused rather than silently replaced with the
|
||
|
|
/// default: a store that moved without the user saying so looks exactly
|
||
|
|
/// like a chain that vanished, and a silent rewrite would resync the whole
|
||
|
|
/// chain into a directory they did not choose.
|
||
|
|
pub fn set_local_monerod_at(
|
||
|
|
&self,
|
||
|
|
monerod_bin: &Path,
|
||
|
|
datadir: &Path,
|
||
|
|
prune: bool,
|
||
|
|
) -> Result<(), String> {
|
||
|
|
if datadir.as_os_str().is_empty() {
|
||
|
|
return Err("chain datadir required for a local node".into());
|
||
|
|
}
|
||
|
|
let mut cfg = self.wallet_child_config();
|
||
|
|
if cfg.wallet_rpc_bin.as_os_str().is_empty() {
|
||
|
|
cfg.wallet_rpc_bin = PathBuf::from("monero-wallet-rpc");
|
||
|
|
}
|
||
|
|
cfg.source = ChainSource::Local {
|
||
|
|
monerod_bin: monerod_bin.to_path_buf(),
|
||
|
|
datadir: datadir.to_path_buf(),
|
||
|
|
prune,
|
||
|
|
};
|
||
|
|
self.set_wallet_child_config(&cfg)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Back to zero: no wallet child, no daemon, no spend. The way out of a
|
||
|
|
/// misconfigured chain source.
|
||
|
|
pub fn set_receive_only(&self) -> Result<(), String> {
|
||
|
|
let mut cfg = self.wallet_child_config();
|
||
|
|
cfg.source = ChainSource::None;
|
||
|
|
self.set_wallet_child_config(&cfg)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Start the app-owned wallet child, point this node's wallet at it, and
|
||
|
|
/// **open its wallet file**.
|
||
|
|
///
|
||
|
|
/// Idempotent: a live wallet child is reported, not respawned. Spawning is
|
||
|
|
/// synchronous — argv is built, the child is spawned, and a `.onion` chain
|
||
|
|
/// source waits up to `SOCKS_READY_TIMEOUT` for the SOCKS listener — which
|
||
|
|
/// is why callers block on it (`rt.block_on` in the TUI).
|
||
|
|
///
|
||
|
|
/// The open is the whole point: `monero-wallet-rpc` starts with no wallet
|
||
|
|
/// open, so a child that came up and was left alone answered every read
|
||
|
|
/// with `-13 No wallet file` — a restart, a Lock/unlock, or a wallet
|
||
|
|
/// re-point silently produced an inert wallet manager. The stored
|
||
|
|
/// passphrase ([`Self::seal_wallet_passphrase`]) opens it.
|
||
|
|
pub fn start_wallet_child(&self) -> Result<(), String> {
|
||
|
|
self.start_wallet_child_with(None)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// [`Self::start_wallet_child`], with a passphrase the caller just collected
|
||
|
|
/// instead of the stored one. Used by [`Self::open_wallet_with_passphrase`]:
|
||
|
|
/// a passphrase is only trusted once a live RPC has opened a file with it.
|
||
|
|
fn start_wallet_child_with(&self, passphrase: Option<&str>) -> Result<(), String> {
|
||
|
|
let cfg = self.wallet_child_config();
|
||
|
|
if !cfg.is_enabled() {
|
||
|
|
return Err("no chain source configured — the wallet child is receive-only".into());
|
||
|
|
}
|
||
|
|
let already_running = self.child_running();
|
||
|
|
if already_running {
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
let child = Arc::new(cfg.build(self.wallet_dir()).map_err(|e| e.to_string())?);
|
||
|
|
// Do not hold SQLCipher across Cuprate/`monerod` launch: `wallet_status`
|
||
|
|
// also locks the store, and a blocked poller is how Android Start looks
|
||
|
|
// like it did nothing.
|
||
|
|
let client = child
|
||
|
|
.start_unlocking_store(&self.store)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let Some(client) = client else {
|
||
|
|
return Err("chain source is receive-only — nothing to start".into());
|
||
|
|
};
|
||
|
|
let wallet = client.into_wallet();
|
||
|
|
let configured = wallet.configured();
|
||
|
|
*self.wallet.lock().map_err(|e| e.to_string())? = wallet;
|
||
|
|
*self.wallet_status.lock().map_err(|e| e.to_string())? = WalletStatus::idle(configured);
|
||
|
|
*self.child_error.lock().map_err(|e| e.to_string())? = None;
|
||
|
|
self.reset_child_probe();
|
||
|
|
*self.wallet_child.lock().map_err(|e| e.to_string())? = Some(child);
|
||
|
|
*self.child_wallet.lock().map_err(|e| e.to_string())? = ChildWalletState::Unknown;
|
||
|
|
if let Err(e) = self.open_child_wallet(passphrase) {
|
||
|
|
// A child whose wallet the RPC would not open is not a child to
|
||
|
|
// leave running: every read answers `-13`, which is exactly the
|
||
|
|
// inert state this path exists to end, so stop it and report why.
|
||
|
|
// A failure to *store* the passphrase is a different thing — the
|
||
|
|
// wallet is open — so that child keeps running and the error says
|
||
|
|
// what was lost.
|
||
|
|
let state = self
|
||
|
|
.child_wallet
|
||
|
|
.lock()
|
||
|
|
.map(|s| *s)
|
||
|
|
.unwrap_or_default();
|
||
|
|
if state != ChildWalletState::Open {
|
||
|
|
self.stop_wallet_child()?;
|
||
|
|
}
|
||
|
|
*self.child_error.lock().map_err(|e| e.to_string())? = Some(e.clone());
|
||
|
|
return Err(e);
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Is a wallet child process alive right now?
|
||
|
|
fn child_running(&self) -> bool {
|
||
|
|
self.wallet_child
|
||
|
|
.lock()
|
||
|
|
.map(|guard| guard.as_ref().is_some_and(|c| c.wallet_rpc_running()))
|
||
|
|
.unwrap_or(false)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Does the catalogue hold this file name? The catalogue is the only
|
||
|
|
/// directory this app has, so it decides what may be opened at all.
|
||
|
|
fn catalogue_holds(&self, filename: &str) -> Result<bool, String> {
|
||
|
|
Ok(self
|
||
|
|
.list_wallets()?
|
||
|
|
.iter()
|
||
|
|
.any(|w| w.wallet_filename == filename))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The wallet-file passphrase this install remembers, or empty. A store
|
||
|
|
/// read: it never dials, and it works with the wallet off.
|
||
|
|
fn stored_wallet_passphrase(&self) -> Result<Zeroizing<String>, String> {
|
||
|
|
let cfg = self
|
||
|
|
.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.load_wallet_config()
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(match cfg {
|
||
|
|
Some(cfg) => cfg.wallet_passphrase,
|
||
|
|
None => Zeroizing::new(String::new()),
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Remember the passphrase that opens the wallet file, sealed beside the
|
||
|
|
/// RPC creds. A read-modify-write: the stored endpoint, login, view-only
|
||
|
|
/// flag and the generated child creds are all untouched.
|
||
|
|
///
|
||
|
|
/// This is the deliberate part of the design (see `docs/THREAT_MODEL.md`):
|
||
|
|
/// the wallet file is only reopenable with its passphrase, `/wipe` keeps
|
||
|
|
/// the wallet file, and a passphrase the user must re-type after every
|
||
|
|
/// restart is a passphrase they will not use. Keeping it makes the store
|
||
|
|
/// passphrase sufficient to spend.
|
||
|
|
fn seal_wallet_passphrase(&self, passphrase: &str) -> Result<(), String> {
|
||
|
|
if passphrase.is_empty() {
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
let mut cfg = store
|
||
|
|
.load_wallet_config()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.unwrap_or_default();
|
||
|
|
if cfg.wallet_passphrase.as_str() == passphrase {
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
cfg.wallet_passphrase = Zeroizing::new(passphrase.to_string());
|
||
|
|
store.save_wallet_config(&cfg).map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Open the wallet file the configured child is pointed at, when this
|
||
|
|
/// install can. `supplied` is a passphrase the user just handed over;
|
||
|
|
/// `None` means "use the stored one".
|
||
|
|
///
|
||
|
|
/// Four outcomes, one of which is an error:
|
||
|
|
/// * the configured file is not in the catalogue → nothing to open
|
||
|
|
/// ([`ChildWalletState::Unknown`], `Ok`);
|
||
|
|
/// * no passphrase is known → the child stays wallet-less and reports
|
||
|
|
/// [`ChildWalletState::NeedsPassphrase`], `Ok`. An install whose wallet
|
||
|
|
/// predates the stored passphrase must still start — the alternative is
|
||
|
|
/// turning a missing secret into a start failure;
|
||
|
|
/// * the file opens → [`ChildWalletState::Open`], and the passphrase is
|
||
|
|
/// sealed;
|
||
|
|
/// * the RPC refuses it → `Err` naming the file, never a generic start
|
||
|
|
/// failure, and the caller stops the child.
|
||
|
|
fn open_child_wallet(&self, supplied: Option<&str>) -> Result<(), String> {
|
||
|
|
let filename = self.wallet_child_config().wallet_filename;
|
||
|
|
if !self.catalogue_holds(&filename)? {
|
||
|
|
*self.child_wallet.lock().map_err(|e| e.to_string())? = ChildWalletState::Unknown;
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
let passphrase = match supplied {
|
||
|
|
Some(p) => Zeroizing::new(p.to_string()),
|
||
|
|
None => self.stored_wallet_passphrase()?,
|
||
|
|
};
|
||
|
|
if passphrase.is_empty() {
|
||
|
|
*self.child_wallet.lock().map_err(|e| e.to_string())? =
|
||
|
|
ChildWalletState::NeedsPassphrase;
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
self.open_wallet_file(&filename, passphrase.as_str())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Issue `open_wallet` against the RPC this node is talking to, and seal the
|
||
|
|
/// passphrase only once a live daemon has accepted it. An unverified
|
||
|
|
/// passphrase is never stored: the next start would then fail on a secret
|
||
|
|
/// the user believed was right.
|
||
|
|
fn open_wallet_file(&self, filename: &str, passphrase: &str) -> Result<(), String> {
|
||
|
|
let wallet = self.wallet_snapshot();
|
||
|
|
match open_wallet_blocking(&wallet, filename, passphrase) {
|
||
|
|
Ok(()) => {
|
||
|
|
*self.child_wallet.lock().map_err(|e| e.to_string())? = ChildWalletState::Open;
|
||
|
|
*self.child_error.lock().map_err(|e| e.to_string())? = None;
|
||
|
|
self.seal_wallet_passphrase(passphrase).map_err(|e| {
|
||
|
|
format!("wallet {filename} opened but its passphrase was not stored: {e}")
|
||
|
|
})
|
||
|
|
}
|
||
|
|
Err(failure) => {
|
||
|
|
let msg = failure.message(filename);
|
||
|
|
*self.child_wallet.lock().map_err(|e| e.to_string())? =
|
||
|
|
ChildWalletState::NeedsPassphrase;
|
||
|
|
*self.child_error.lock().map_err(|e| e.to_string())? = Some(msg.clone());
|
||
|
|
Err(msg)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The wallet file this process just created or imported is the one the
|
||
|
|
/// child holds open — but only while a child is actually up to hold it.
|
||
|
|
fn mark_child_wallet_open(&self) {
|
||
|
|
if self.child_running()
|
||
|
|
&& let Ok(mut state) = self.child_wallet.lock()
|
||
|
|
{
|
||
|
|
*state = ChildWalletState::Open;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Stop the app-owned wallet child (idempotent) and put the wallet back on
|
||
|
|
/// the stored/env config, if any. The next launch starts the child again —
|
||
|
|
/// nothing promises it stays up across a restart, and Android will not.
|
||
|
|
pub fn stop_wallet_child(&self) -> Result<(), String> {
|
||
|
|
let child = self.wallet_child.lock().map_err(|e| e.to_string())?.take();
|
||
|
|
if let Some(child) = child {
|
||
|
|
child.stop().map_err(|e| e.to_string())?;
|
||
|
|
}
|
||
|
|
self.reset_child_probe();
|
||
|
|
// No process, no open wallet file. Whatever the last child managed is
|
||
|
|
// gone with it, and claiming otherwise would make the UI skip the
|
||
|
|
// prompt that opens the next one.
|
||
|
|
*self.child_wallet.lock().map_err(|e| e.to_string())? = ChildWalletState::Unknown;
|
||
|
|
let stored = self
|
||
|
|
.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.load_wallet_config()
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let wallet = Wallet::for_boot(stored.as_ref());
|
||
|
|
let configured = wallet.configured();
|
||
|
|
*self.wallet.lock().map_err(|e| e.to_string())? = wallet;
|
||
|
|
*self.wallet_status.lock().map_err(|e| e.to_string())? = WalletStatus::idle(configured);
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Clear the last child probe: no chain answers, nothing remembered. Called
|
||
|
|
/// wherever the child's lifecycle moves (start, stop, shutdown), so a stale
|
||
|
|
/// height from a previous run can never survive into the next one.
|
||
|
|
fn reset_child_probe(&self) {
|
||
|
|
self.child_synced.store(false, Ordering::Relaxed);
|
||
|
|
self.child_height.store(0, Ordering::Relaxed);
|
||
|
|
self.child_target.store(0, Ordering::Relaxed);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The child's observable state, derived from the real process plus the last
|
||
|
|
/// probe — never from env-var presence. Cheap: no dial, safe on a draw path.
|
||
|
|
pub fn wallet_child_status(&self) -> WalletChildStatus {
|
||
|
|
let cfg = self.wallet_child_config();
|
||
|
|
let child = self
|
||
|
|
.wallet_child
|
||
|
|
.lock()
|
||
|
|
.ok()
|
||
|
|
.and_then(|guard| guard.clone());
|
||
|
|
let running = child
|
||
|
|
.as_ref()
|
||
|
|
.is_some_and(|child| child.wallet_rpc_running());
|
||
|
|
let connected = self
|
||
|
|
.wallet_status
|
||
|
|
.lock()
|
||
|
|
.map(|s| s.connected)
|
||
|
|
.unwrap_or(false);
|
||
|
|
let state = match &child {
|
||
|
|
None => WalletChildState::Off,
|
||
|
|
Some(_) if !running => WalletChildState::Exited,
|
||
|
|
Some(_) if !connected => WalletChildState::Connecting,
|
||
|
|
Some(_) if self.child_synced.load(Ordering::Relaxed) => WalletChildState::Ready,
|
||
|
|
Some(_) => WalletChildState::Syncing,
|
||
|
|
};
|
||
|
|
// Only a live child has anything to say about a chain. An off or exited
|
||
|
|
// child reports unknown (`0/0`), whatever the last probe left behind.
|
||
|
|
let heights = match state {
|
||
|
|
WalletChildState::Off | WalletChildState::Exited => (0, 0),
|
||
|
|
WalletChildState::Connecting | WalletChildState::Syncing | WalletChildState::Ready => (
|
||
|
|
self.child_height.load(Ordering::Relaxed),
|
||
|
|
self.child_target.load(Ordering::Relaxed),
|
||
|
|
),
|
||
|
|
};
|
||
|
|
let child_wallet = self
|
||
|
|
.child_wallet
|
||
|
|
.lock()
|
||
|
|
.map(|state| *state)
|
||
|
|
.unwrap_or_default();
|
||
|
|
// A child that has exited holds nothing, whatever the last run managed.
|
||
|
|
// An `off` node is not the same statement: with no app-owned child the
|
||
|
|
// node may be talking to a remote-mode RPC the user runs themselves, and
|
||
|
|
// an open wallet file there is a real open.
|
||
|
|
let (wallet_open, needs_passphrase) = match state {
|
||
|
|
WalletChildState::Exited => (false, child_wallet == ChildWalletState::NeedsPassphrase),
|
||
|
|
_ => (
|
||
|
|
child_wallet == ChildWalletState::Open,
|
||
|
|
child_wallet == ChildWalletState::NeedsPassphrase,
|
||
|
|
),
|
||
|
|
};
|
||
|
|
WalletChildStatus {
|
||
|
|
state,
|
||
|
|
running,
|
||
|
|
wallet_open,
|
||
|
|
needs_passphrase,
|
||
|
|
configured: cfg.is_enabled(),
|
||
|
|
chain_source: cfg.source_label(),
|
||
|
|
height: heights.0,
|
||
|
|
target_height: heights.1,
|
||
|
|
last_error: self.child_error.lock().ok().and_then(|err| err.clone()),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The one-line child status a TUI row shows. Empty when nothing is
|
||
|
|
/// configured, so an unconfigured install renders no row at all.
|
||
|
|
pub fn wallet_child_line(&self) -> String {
|
||
|
|
self.wallet_child_status().line()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Probe the running child once: is its wallet RPC answering, is the chain
|
||
|
|
/// at the tip, and how far along is the chain daemon? Only this (or a failed
|
||
|
|
/// start) moves the state off `connecting`, and it never invents `ready` for
|
||
|
|
/// a dead child.
|
||
|
|
pub async fn wallet_child_refresh(&self) -> WalletChildStatus {
|
||
|
|
let running = self
|
||
|
|
.wallet_child
|
||
|
|
.lock()
|
||
|
|
.map(|guard| guard.is_some())
|
||
|
|
.unwrap_or(false);
|
||
|
|
if !running {
|
||
|
|
return self.wallet_child_status();
|
||
|
|
}
|
||
|
|
let cfg = self.wallet_child_config();
|
||
|
|
let w = self.wallet_snapshot();
|
||
|
|
if !w.configured() {
|
||
|
|
return self.wallet_child_status();
|
||
|
|
}
|
||
|
|
let status = w.status().await;
|
||
|
|
let connected = status.connected;
|
||
|
|
let error = status.last_error.clone();
|
||
|
|
if let Ok(mut slot) = self.wallet_status.lock() {
|
||
|
|
*slot = status;
|
||
|
|
}
|
||
|
|
// One probe answers both questions: is it synced, and how far along.
|
||
|
|
let progress = if connected {
|
||
|
|
w.chain_info().await.ok()
|
||
|
|
} else {
|
||
|
|
None
|
||
|
|
};
|
||
|
|
// A wallet RPC that answers has a wallet open: `get_address` cannot
|
||
|
|
// answer without one. That is the honest signal that the file is open,
|
||
|
|
// whoever opened it (this node, or the user's own client against a
|
||
|
|
// remote-mode endpoint).
|
||
|
|
if connected && let Ok(mut slot) = self.child_wallet.lock() {
|
||
|
|
*slot = ChildWalletState::Open;
|
||
|
|
}
|
||
|
|
let synced = progress.as_ref().is_some_and(wallet::ChainInfo::ready);
|
||
|
|
let (height, target_height) = match progress {
|
||
|
|
Some(info) => (info.height, info.target_height),
|
||
|
|
// The wallet RPC is the honest source when it answers. When it does
|
||
|
|
// not (a refused connection is the common one), the daemon this box
|
||
|
|
// owns can still say — and a daemon that does not answer leaves
|
||
|
|
// `0/0`, which is "unknown", not "caught up".
|
||
|
|
None => self.chain_daemon_progress(&cfg).await,
|
||
|
|
};
|
||
|
|
self.child_synced.store(synced, Ordering::Relaxed);
|
||
|
|
self.child_height.store(height, Ordering::Relaxed);
|
||
|
|
self.child_target.store(target_height, Ordering::Relaxed);
|
||
|
|
if let Ok(mut slot) = self.child_error.lock() {
|
||
|
|
let previous = slot.clone();
|
||
|
|
*slot = probe_error(connected, error, previous);
|
||
|
|
}
|
||
|
|
self.wallet_child_status()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The chain daemon's own height/target, asked directly because the wallet
|
||
|
|
/// RPC did not answer. Only a daemon on this box is asked (see
|
||
|
|
/// [`ChildConfig::daemon_probe_addr`]) and any failure is `(0, 0)` — a
|
||
|
|
/// daemon still coming up is unknown, not an error to put on the status row.
|
||
|
|
async fn chain_daemon_progress(&self, cfg: &ChildConfig) -> (u64, u64) {
|
||
|
|
let Some(addr) = cfg.daemon_probe_addr() else {
|
||
|
|
return (0, 0);
|
||
|
|
};
|
||
|
|
match wallet::daemon_get_info(&addr, DAEMON_PROBE_BUDGET).await {
|
||
|
|
Ok(info) => (info.height, info.target_height),
|
||
|
|
Err(_) => (0, 0),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The config screen's Test-connection button: one shot against the endpoint
|
||
|
|
/// the user is typing. It does not touch the live wallet or the snapshot —
|
||
|
|
/// a test of an untyped endpoint is not the wallet we are running.
|
||
|
|
pub async fn wallet_test_connection(
|
||
|
|
&self,
|
||
|
|
rpc_url: &str,
|
||
|
|
rpc_login: &str,
|
||
|
|
) -> wallet::PingResult {
|
||
|
|
Wallet::ping(rpc_url, rpc_login).await
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The config the F7 screen should show: the stored one, or the env-derived
|
||
|
|
/// one when only env set the wallet (the migration path).
|
||
|
|
pub fn wallet_config(&self) -> Option<WalletConfig> {
|
||
|
|
if let Ok(store) = self.store.lock()
|
||
|
|
&& let Ok(Some(cfg)) = store.load_wallet_config()
|
||
|
|
{
|
||
|
|
return Some(cfg);
|
||
|
|
}
|
||
|
|
self.wallet_snapshot().config()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Persist the config screen's Save and re-read it: the live wallet and the
|
||
|
|
/// snapshot both follow, so "saved · not connected" is visible without a
|
||
|
|
/// restart. Validation happens before anything is written, so a rejected
|
||
|
|
/// config leaves the running wallet exactly as it was.
|
||
|
|
pub fn wallet_save_config(&self, cfg: &WalletConfig) -> Result<(), String> {
|
||
|
|
Wallet::from_config(cfg).map_err(|e| wallet::redact(&e.to_string(), cfg.secret()))?;
|
||
|
|
let mut cfg = cfg.clone();
|
||
|
|
// The passphrase is the *file's*, not this screen's: keep whatever is
|
||
|
|
// stored, or an F7 save would lock the wallet out of itself.
|
||
|
|
cfg.wallet_passphrase = self.stored_wallet_passphrase()?;
|
||
|
|
{
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
store.save_wallet_config(&cfg).map_err(|e| e.to_string())?;
|
||
|
|
}
|
||
|
|
// Re-read from the store rather than trusting the caller's copy.
|
||
|
|
let stored = self
|
||
|
|
.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.load_wallet_config()
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let wallet = Wallet::for_boot(stored.as_ref());
|
||
|
|
let configured = wallet.configured();
|
||
|
|
*self.wallet.lock().map_err(|e| e.to_string())? = wallet;
|
||
|
|
*self.wallet_status.lock().map_err(|e| e.to_string())? = WalletStatus::idle(configured);
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Current wallet balance as a human-readable XMR string, or `off` when the
|
||
|
|
/// wallet is not configured.
|
||
|
|
pub async fn wallet_balance(&self) -> String {
|
||
|
|
let w = self.wallet_snapshot();
|
||
|
|
if !w.configured() {
|
||
|
|
return "off".into();
|
||
|
|
}
|
||
|
|
match w.get_balance().await {
|
||
|
|
Ok(b) => crate::pay::atomic_to_xmr_str(&b),
|
||
|
|
Err(_) => "err".into(),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn wipe_messages(&self) -> Result<(), String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.wipe_messages()
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn self_profile(&self) -> Result<FriendProfile, String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.self_profile()
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn friend_profile(&self, pubkey: &[u8]) -> Result<Option<FriendProfile>, String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.friend_profile(pubkey)
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn set_self_profile(
|
||
|
|
&self,
|
||
|
|
display_name: &str,
|
||
|
|
bio: &str,
|
||
|
|
xmr_addr: &str,
|
||
|
|
) -> Result<(), String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.set_self_profile(display_name, bio, xmr_addr)
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// One-shot signed `prf` to a friend. Fail closed; no retry, no outbox.
|
||
|
|
pub async fn push_self_profile(&self, friend_pk: &[u8]) -> Result<(), String> {
|
||
|
|
let me = self.self_profile()?;
|
||
|
|
let k = self.keys()?;
|
||
|
|
let prf = profile::sign(
|
||
|
|
&k.identity_sk,
|
||
|
|
&me.display_name,
|
||
|
|
&me.bio,
|
||
|
|
&me.xmr_addr,
|
||
|
|
me.updated_at,
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let pt = profile::encode(&prf);
|
||
|
|
let (onion, prekey) = {
|
||
|
|
let f = self.friend(friend_pk)?;
|
||
|
|
if f.prekey.len() != 32 {
|
||
|
|
return Err("friend missing prekey".into());
|
||
|
|
}
|
||
|
|
(f.onion, f.prekey)
|
||
|
|
};
|
||
|
|
self.try_send(&onion, friend_pk, &prekey, &pt).await
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Sign an invoice with this node's identity key.
|
||
|
|
///
|
||
|
|
/// The signing half of [`Self::pay_invoice`], for callers that build the
|
||
|
|
/// frame themselves (the Android SDK). The ed25519 secret never leaves the
|
||
|
|
/// node: it is signed with here and not handed out. `amount_atomic` is
|
||
|
|
/// piconero; `address` must be a valid Monero address; `memo` may be empty.
|
||
|
|
pub fn sign_invoice(
|
||
|
|
&self,
|
||
|
|
amount_atomic: &str,
|
||
|
|
address: &str,
|
||
|
|
memo: &str,
|
||
|
|
) -> Result<pay::Invoice, String> {
|
||
|
|
let k = self.keys()?;
|
||
|
|
pay::sign_invoice(&k.identity_sk, amount_atomic, address, memo, unix_now())
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Sign a receipt for a transfer that already happened: the signing half of
|
||
|
|
/// [`Self::tip`]. Same key discipline as [`Self::sign_invoice`].
|
||
|
|
pub fn sign_receipt(
|
||
|
|
&self,
|
||
|
|
txid: &str,
|
||
|
|
amount_atomic: &str,
|
||
|
|
address: &str,
|
||
|
|
) -> Result<pay::Receipt, String> {
|
||
|
|
let k = self.keys()?;
|
||
|
|
pay::sign_receipt(&k.identity_sk, txid, amount_atomic, address, unix_now())
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Sign a tip frame (receipt + memo) for a transfer that already happened.
|
||
|
|
/// This signs only — it does not move funds; that is [`Self::tip`].
|
||
|
|
pub fn sign_tip(
|
||
|
|
&self,
|
||
|
|
txid: &str,
|
||
|
|
amount_atomic: &str,
|
||
|
|
address: &str,
|
||
|
|
memo: &str,
|
||
|
|
) -> Result<pay::Tip, String> {
|
||
|
|
let k = self.keys()?;
|
||
|
|
pay::sign_tip(
|
||
|
|
&k.identity_sk,
|
||
|
|
txid,
|
||
|
|
amount_atomic,
|
||
|
|
address,
|
||
|
|
memo,
|
||
|
|
unix_now(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Invoice to receive. Wallet subaddress if up, else self_profile.xmr_addr.
|
||
|
|
pub async fn pay_invoice(
|
||
|
|
&self,
|
||
|
|
friend_pk: &[u8],
|
||
|
|
atomic: &str,
|
||
|
|
memo: &str,
|
||
|
|
) -> Result<(), String> {
|
||
|
|
let address = self.invoice_address().await?;
|
||
|
|
let inv = self.sign_invoice(atomic, &address, memo)?;
|
||
|
|
let pt = pay::encode_invoice(&inv);
|
||
|
|
self.send_once(friend_pk, &pt).await?;
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.insert_payment(
|
||
|
|
friend_pk,
|
||
|
|
PaymentWrite {
|
||
|
|
dir: "out",
|
||
|
|
kind: "invoice",
|
||
|
|
amount_atomic: atomic,
|
||
|
|
address: &address,
|
||
|
|
memo,
|
||
|
|
txid: None,
|
||
|
|
verified: false,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.append_message(
|
||
|
|
friend_pk,
|
||
|
|
"out",
|
||
|
|
pay::invoice_chat_line(atomic, memo).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Pay selected friend via wallet RPC, then signed receipt.
|
||
|
|
pub async fn tip(&self, friend_pk: &[u8], atomic: &str, memo: &str) -> Result<(), String> {
|
||
|
|
let w = self.wallet_snapshot();
|
||
|
|
if !w.configured() {
|
||
|
|
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
||
|
|
}
|
||
|
|
let address = self
|
||
|
|
.friend_profile(friend_pk)?
|
||
|
|
.map(|p| p.xmr_addr)
|
||
|
|
.unwrap_or_default();
|
||
|
|
if address.is_empty() {
|
||
|
|
return Err("friend has no Monero address — they must /profile".into());
|
||
|
|
}
|
||
|
|
pay::check_address(&address).map_err(|e| e.to_string())?;
|
||
|
|
let amount: u64 = atomic
|
||
|
|
.parse()
|
||
|
|
.map_err(|_| "amount too large for wallet RPC".to_string())?;
|
||
|
|
let txid = w
|
||
|
|
.transfer(&address, amount)
|
||
|
|
.await
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let rcp = self.sign_receipt(&txid, atomic, &address)?;
|
||
|
|
let rcp_pt = pay::encode_receipt(&rcp);
|
||
|
|
let tip = self.sign_tip(&txid, atomic, &address, memo)?;
|
||
|
|
let tip_pt = pay::encode_tip(&tip);
|
||
|
|
self.send_once(friend_pk, &rcp_pt).await?;
|
||
|
|
self.send_once(friend_pk, &tip_pt).await?;
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
// The user just *spent* this money: the row is a tip, matching the
|
||
|
|
// inbound `ingest_tip` direction. The receipt frame above is the
|
||
|
|
// recipient's copy of the payment, not the local one.
|
||
|
|
store
|
||
|
|
.insert_payment(
|
||
|
|
friend_pk,
|
||
|
|
PaymentWrite {
|
||
|
|
dir: "out",
|
||
|
|
kind: "tip",
|
||
|
|
amount_atomic: atomic,
|
||
|
|
address: &address,
|
||
|
|
memo,
|
||
|
|
txid: Some(&txid),
|
||
|
|
verified: true,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.append_message(
|
||
|
|
friend_pk,
|
||
|
|
"out",
|
||
|
|
pay::receipt_chat_line(atomic, true).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
// The receipt line is the recipient's view of the frame that arrived;
|
||
|
|
// the payer's own chat shows the tip they just spent (unverified: the
|
||
|
|
// recipient has not confirmed it).
|
||
|
|
store
|
||
|
|
.append_message(
|
||
|
|
friend_pk,
|
||
|
|
"out",
|
||
|
|
pay::tip_chat_line(atomic, memo, false).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn invoice_address(&self) -> Result<String, String> {
|
||
|
|
let w = self.wallet_snapshot();
|
||
|
|
if w.configured()
|
||
|
|
&& let Ok(addr) = w.create_address().await
|
||
|
|
&& pay::check_address(&addr).is_ok()
|
||
|
|
{
|
||
|
|
return Ok(addr);
|
||
|
|
}
|
||
|
|
let profile_addr = self.self_profile()?.xmr_addr;
|
||
|
|
if profile_addr.is_empty() {
|
||
|
|
return Err("no receive address — set profile xmr or ONIONWIRE_WALLET_RPC".into());
|
||
|
|
}
|
||
|
|
pay::check_address(&profile_addr).map_err(|e| e.to_string())?;
|
||
|
|
Ok(profile_addr)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Receive address for the wallet screen: a freshly created subaddress when
|
||
|
|
/// the wallet is configured, else the profile `xmr_addr` fallback. Returns
|
||
|
|
/// the raw address (not a `monero:` URI) so the QR render path can decide
|
||
|
|
/// how to wrap it.
|
||
|
|
pub async fn wallet_receive_address(&self) -> Result<String, String> {
|
||
|
|
let profile_addr = self.self_profile()?.xmr_addr;
|
||
|
|
let w = self.wallet_snapshot();
|
||
|
|
if w.configured()
|
||
|
|
&& let Ok(addr) = w.get_address().await
|
||
|
|
&& pay::check_address(&addr).is_ok()
|
||
|
|
{
|
||
|
|
return Ok(addr);
|
||
|
|
}
|
||
|
|
if !profile_addr.is_empty() {
|
||
|
|
pay::check_address(&profile_addr).map_err(|e| e.to_string())?;
|
||
|
|
return Ok(profile_addr);
|
||
|
|
}
|
||
|
|
Err("no receive address — set profile xmr or ONIONWIRE_WALLET_RPC".into())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Formatted balance for the wallet screen, or "off" when the wallet is not
|
||
|
|
/// configured. Calls `pay::atomic_to_xmr_str` so the UI never parses
|
||
|
|
/// piconero itself.
|
||
|
|
pub async fn wallet_balance_line(&self) -> String {
|
||
|
|
let w = self.wallet_snapshot();
|
||
|
|
if w.configured() {
|
||
|
|
match w.get_balance().await {
|
||
|
|
Ok(b) if !b.is_empty() => {
|
||
|
|
let xmr = pay::atomic_to_xmr_str(&b);
|
||
|
|
if xmr == "0" {
|
||
|
|
"balance 0 XMR".to_string()
|
||
|
|
} else {
|
||
|
|
format!("balance {xmr} XMR")
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Ok(_) => "balance —".to_string(),
|
||
|
|
Err(_) => "balance —".to_string(),
|
||
|
|
}
|
||
|
|
} else {
|
||
|
|
"wallet off".to_string()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Recent in/out transfers for the wallet screen, newest first, capped to a
|
||
|
|
/// small window. Returns the same `TransferRow` shape the existing tests
|
||
|
|
/// already cover.
|
||
|
|
pub async fn wallet_recent_transfers(
|
||
|
|
&self,
|
||
|
|
cap: usize,
|
||
|
|
) -> Result<Vec<wallet::TransferRow>, String> {
|
||
|
|
let w = self.wallet_snapshot();
|
||
|
|
if !w.configured() {
|
||
|
|
return Ok(Vec::new());
|
||
|
|
}
|
||
|
|
let rows = w.get_transfers().await.map_err(|e| e.to_string())?;
|
||
|
|
let mut rows = rows;
|
||
|
|
rows.sort_by(|a, b| b.txid.cmp(&a.txid));
|
||
|
|
Ok(rows.into_iter().take(cap).collect())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Create a new spend-capable wallet and record it in the catalogue. The
|
||
|
|
/// user never pastes a key on this path.
|
||
|
|
///
|
||
|
|
/// The wallet file gets its own name ([`Self::next_wallet_filename`]):
|
||
|
|
/// `wallet_filename` is UNIQUE, so a second create that reused the old
|
||
|
|
/// hardcoded name would open the first wallet's file — or be refused by the
|
||
|
|
/// RPC outright, which is the "cannot create a new wallet" failure. The
|
||
|
|
/// stored row is what makes the wallet survive a restart; the wallet dir is
|
||
|
|
/// not scanned.
|
||
|
|
pub async fn wallet_create(&self, password: &str) -> Result<CreatedWallet, String> {
|
||
|
|
let w = self.wallet_snapshot();
|
||
|
|
if !w.configured() {
|
||
|
|
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
||
|
|
}
|
||
|
|
let filename = self.next_wallet_filename()?;
|
||
|
|
let seed = w
|
||
|
|
.create_wallet(&filename, password)
|
||
|
|
.await
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let record = self
|
||
|
|
.record_wallet(&filename)
|
||
|
|
.map_err(|e| format!("wallet {filename} created but not remembered: {e}"))?;
|
||
|
|
self.point_child_at(&filename).map_err(|e| {
|
||
|
|
format!("wallet {filename} created but the child is not pointed at it: {e}")
|
||
|
|
})?;
|
||
|
|
// The passphrase that opens the file is a thing this app needs again on
|
||
|
|
// the next start: the RPC drops the open wallet when the process goes.
|
||
|
|
self.seal_wallet_passphrase(password).map_err(|e| {
|
||
|
|
format!("wallet {filename} created but its passphrase was not stored: {e}")
|
||
|
|
})?;
|
||
|
|
// This process just created the file, so the RPC has it open — while a
|
||
|
|
// child is running to hold it.
|
||
|
|
self.mark_child_wallet_open();
|
||
|
|
Ok(CreatedWallet { record, seed })
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Re-read the seed of the wallet file the child has open. `create_wallet`
|
||
|
|
/// returns it once; after that this is the only path to it. The seed is a
|
||
|
|
/// spend key, so the caller must only show it on an explicit user action
|
||
|
|
/// and must not log or store it.
|
||
|
|
pub async fn wallet_seed(&self) -> Result<String, String> {
|
||
|
|
let w = self.wallet_snapshot();
|
||
|
|
if !w.configured() {
|
||
|
|
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
||
|
|
}
|
||
|
|
w.mnemonic().await.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The private view key and, when the wallet can spend, the private spend
|
||
|
|
/// key of the wallet file the child currently has **open** (`query_key`).
|
||
|
|
///
|
||
|
|
/// Secrets therefore belong to the open wallet: viewing another saved
|
||
|
|
/// wallet's keys means opening it first. A view-only wallet answers `None`
|
||
|
|
/// for `spend_key` instead of an error (the RPC's `-29`). An unconfigured
|
||
|
|
/// wallet is refused locally, before any dial; a configured but unreachable
|
||
|
|
/// child surfaces the RPC error.
|
||
|
|
///
|
||
|
|
/// The values are spend secrets: never log them and never persist them.
|
||
|
|
pub async fn wallet_keys(&self) -> Result<wallet::WalletKeys, String> {
|
||
|
|
let w = self.wallet_snapshot();
|
||
|
|
if !w.configured() {
|
||
|
|
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
||
|
|
}
|
||
|
|
w.keys().await.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The wallet file the child is currently pointed at, so a client can mark
|
||
|
|
/// the open row in the catalogue. `None` when no wallet-child settings have
|
||
|
|
/// ever been stored (a fresh install): a receive-only install has no open
|
||
|
|
/// wallet file, and the child never points at one until a wallet is created,
|
||
|
|
/// imported, or opened.
|
||
|
|
///
|
||
|
|
/// The name is what the child would spawn with, not a message from the
|
||
|
|
/// running process, and it may not match a catalogue row (an install whose
|
||
|
|
/// wallet predates the catalogue). Match it against
|
||
|
|
/// [`Node::list_wallets`] rather than assuming it is there.
|
||
|
|
pub fn active_wallet_filename(&self) -> Result<Option<String>, String> {
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
let Some(raw) = store.load_wallet_child().map_err(|e| e.to_string())? else {
|
||
|
|
return Ok(None);
|
||
|
|
};
|
||
|
|
let cfg = ChildConfig::from_record(&raw).map_err(|e| e.to_string())?;
|
||
|
|
Ok(cfg.map(|cfg| cfg.wallet_filename))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Import a wallet from an existing 25-word seed. This is the only path
|
||
|
|
/// that takes a user-supplied secret — and, like a create, it is remembered
|
||
|
|
/// in the catalogue under its own file name.
|
||
|
|
///
|
||
|
|
/// `seed_offset` is Monero's optional seed-offset passphrase (a second spend
|
||
|
|
/// secret mixed into the seed at restore time, not the file passphrase). It
|
||
|
|
/// is forwarded to the RPC and nothing else: never sealed, never stored,
|
||
|
|
/// never logged, never on the argv, and a wrong one is not an error — the
|
||
|
|
/// RPC succeeds and the wallet is a different one. Only `password` is sealed
|
||
|
|
/// here, into the same record the next start opens the file with.
|
||
|
|
pub async fn wallet_restore(
|
||
|
|
&self,
|
||
|
|
password: &str,
|
||
|
|
seed: &str,
|
||
|
|
seed_offset: Option<&str>,
|
||
|
|
) -> Result<WalletRecord, String> {
|
||
|
|
let w = self.wallet_snapshot();
|
||
|
|
if !w.configured() {
|
||
|
|
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
||
|
|
}
|
||
|
|
let filename = self.next_wallet_filename()?;
|
||
|
|
w.restore_wallet(&filename, password, seed, seed_offset)
|
||
|
|
.await
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let record = self
|
||
|
|
.record_wallet(&filename)
|
||
|
|
.map_err(|e| format!("wallet {filename} imported but not remembered: {e}"))?;
|
||
|
|
self.point_child_at(&filename).map_err(|e| {
|
||
|
|
format!("wallet {filename} imported but the child is not pointed at it: {e}")
|
||
|
|
})?;
|
||
|
|
// Import is a creation path too: remember the passphrase the RPC just
|
||
|
|
// opened the file with, so the next start can open it again.
|
||
|
|
self.seal_wallet_passphrase(password).map_err(|e| {
|
||
|
|
format!("wallet {filename} imported but its passphrase was not stored: {e}")
|
||
|
|
})?;
|
||
|
|
self.mark_child_wallet_open();
|
||
|
|
Ok(record)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Every wallet this install remembers, oldest first. A store read: it must
|
||
|
|
/// work with no wallet RPC configured, and it never dials.
|
||
|
|
pub fn list_wallets(&self) -> Result<Vec<WalletRecord>, String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.list_wallets()
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Switch the wallet child to a catalogue wallet's file and open it.
|
||
|
|
///
|
||
|
|
/// The catalogue is the only directory this app has, so a file it does not
|
||
|
|
/// hold is refused instead of pointing a spend-capable child at a path. A
|
||
|
|
/// running child is restarted onto the new file and opens it with the
|
||
|
|
/// stored passphrase; an idle one is only re-pointed, and the change
|
||
|
|
/// applies on the next `start_wallet_child`. The write is a
|
||
|
|
/// read-modify-write, so the generated RPC creds survive.
|
||
|
|
///
|
||
|
|
/// When this install holds no passphrase for the file, the child comes up
|
||
|
|
/// with no wallet open and the status reports `needs_passphrase` — not an
|
||
|
|
/// error: [`Self::open_wallet_with_passphrase`] is the one-time fix, and
|
||
|
|
/// after it the passphrase is stored.
|
||
|
|
pub fn open_wallet(&self, filename: &str) -> Result<(), String> {
|
||
|
|
if !self.catalogue_holds(filename)? {
|
||
|
|
return Err(format!("no saved wallet in {filename}"));
|
||
|
|
}
|
||
|
|
let running = self.child_running();
|
||
|
|
if running {
|
||
|
|
self.stop_wallet_child()?;
|
||
|
|
}
|
||
|
|
self.point_child_at(filename)?;
|
||
|
|
if running {
|
||
|
|
self.start_wallet_child()?;
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Open a catalogue wallet with a passphrase the user just supplied, and
|
||
|
|
/// remember it (sealed) once the RPC has accepted it.
|
||
|
|
///
|
||
|
|
/// This is the counterpart of a `needs_passphrase` status: a wallet created
|
||
|
|
/// before the passphrase was stored, or created on another install, is
|
||
|
|
/// opened once here and then reopens on every later start. A passphrase is
|
||
|
|
/// only *verified* by a live RPC, so with a running child this restarts the
|
||
|
|
/// child (opening the file as part of the start); with an idle child it
|
||
|
|
/// dials the RPC this node is already talking to. With nothing to dial it
|
||
|
|
/// refuses rather than sealing an unverified secret.
|
||
|
|
pub fn open_wallet_with_passphrase(
|
||
|
|
&self,
|
||
|
|
filename: &str,
|
||
|
|
passphrase: &str,
|
||
|
|
) -> Result<(), String> {
|
||
|
|
if passphrase.is_empty() {
|
||
|
|
return Err("wallet passphrase required".into());
|
||
|
|
}
|
||
|
|
if !self.catalogue_holds(filename)? {
|
||
|
|
return Err(format!("no saved wallet in {filename}"));
|
||
|
|
}
|
||
|
|
if !self.wallet_snapshot().configured() {
|
||
|
|
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
||
|
|
}
|
||
|
|
let running = self.child_running();
|
||
|
|
if running {
|
||
|
|
self.stop_wallet_child()?;
|
||
|
|
}
|
||
|
|
self.point_child_at(filename)?;
|
||
|
|
if running {
|
||
|
|
return self.start_wallet_child_with(Some(passphrase));
|
||
|
|
}
|
||
|
|
self.open_wallet_file(filename, passphrase)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The file name a wallet created now should live in.
|
||
|
|
///
|
||
|
|
/// `wallet_filename` is UNIQUE and the catalogue is not the whole story:
|
||
|
|
/// `Store::delete_wallet` drops the row and keeps the file, and a create
|
||
|
|
/// whose `record_wallet` failed leaves a file with no row, so a *file* the
|
||
|
|
/// catalogue does not know about is still a name the daemon refuses with
|
||
|
|
/// `-21 Cannot create wallet. Already exists.` — for ever, because the
|
||
|
|
/// catalogue never changed. So the first `<default>-<n>` that is free in
|
||
|
|
/// both places wins, and a wallet dir that cannot be listed is an error
|
||
|
|
/// rather than a guess ([`wallet_name_taken`]).
|
||
|
|
///
|
||
|
|
/// Nothing is deleted here: a file the catalogue does not hold may be the
|
||
|
|
/// only copy of a funded wallet.
|
||
|
|
fn next_wallet_filename(&self) -> Result<String, String> {
|
||
|
|
let taken = self.list_wallets()?;
|
||
|
|
let dir = self.wallet_dir();
|
||
|
|
for n in 1.. {
|
||
|
|
let candidate = format!("{}-{}", wallet::DEFAULT_WALLET_FILENAME, n);
|
||
|
|
if taken.iter().any(|w| w.wallet_filename == candidate) {
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
if wallet_name_taken(&dir, &candidate).map_err(|e| e.to_string())? {
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
return Ok(candidate);
|
||
|
|
}
|
||
|
|
unreachable!("an unused wallet file name always exists")
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Where this install's wallet files live: `$ONIONWIRE_HOME/wallet`, the
|
||
|
|
/// `--wallet-dir` the app-owned child is spawned with. The one path, so
|
||
|
|
/// the picker and the child can never disagree about the directory.
|
||
|
|
fn wallet_dir(&self) -> PathBuf {
|
||
|
|
self.home.join("wallet")
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Point the wallet child at a wallet file. A read-modify-write of the
|
||
|
|
/// sealed record, so the generated RPC creds and every other setting are
|
||
|
|
/// kept. A running child is not restarted: the change applies on the next
|
||
|
|
/// `start_wallet_child`.
|
||
|
|
fn point_child_at(&self, filename: &str) -> Result<(), String> {
|
||
|
|
let mut cfg = self.wallet_child_config();
|
||
|
|
if cfg.wallet_filename == filename {
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
cfg.wallet_filename = filename.to_string();
|
||
|
|
self.set_wallet_child_config(&cfg)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Add a freshly created wallet file to the catalogue: this node's identity
|
||
|
|
/// (several wallets may share one) and the onion it is reachable at right
|
||
|
|
/// now (a locator, and empty until the HS publishes).
|
||
|
|
fn record_wallet(&self, filename: &str) -> Result<WalletRecord, String> {
|
||
|
|
let new = NewWallet {
|
||
|
|
name: None,
|
||
|
|
identity_pubkey: self.identity_pk(),
|
||
|
|
onion_locator: self.onion(),
|
||
|
|
wallet_filename: filename.to_string(),
|
||
|
|
};
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.create_wallet(&new)
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> {
|
||
|
|
self.ensure_running()?;
|
||
|
|
let (onion, prekey) = {
|
||
|
|
let f = self.friend(friend_pk)?;
|
||
|
|
if f.prekey.len() != 32 {
|
||
|
|
return Err("friend missing prekey".into());
|
||
|
|
}
|
||
|
|
(f.onion, f.prekey)
|
||
|
|
};
|
||
|
|
self.try_send(&onion, friend_pk, &prekey, plaintext).await
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Dial a peer's onion. Success is evidence the peer is up, which is one of
|
||
|
|
/// the outbox retry triggers.
|
||
|
|
pub async fn connect_onion(&self, onion: &str) -> Result<(), String> {
|
||
|
|
self.ensure_running()?;
|
||
|
|
tokio::time::timeout(
|
||
|
|
Duration::from_secs(20),
|
||
|
|
self.client.connect((onion, HS_PORT)),
|
||
|
|
)
|
||
|
|
.await
|
||
|
|
.map_err(|_| format!("connect {onion}:{HS_PORT} timed out"))?
|
||
|
|
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
|
||
|
|
if let Ok(Some(friend)) = self
|
||
|
|
.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
.and_then(|s| s.friend_by_onion(onion).map_err(|e| e.to_string()))
|
||
|
|
{
|
||
|
|
spawn_flush_friend(Arc::clone(&self.outbox), friend.pubkey);
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn rotate(self: &Arc<Self>) -> Result<RotateResult, String> {
|
||
|
|
self.ensure_running()?;
|
||
|
|
let old_nick = self
|
||
|
|
.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.hs_nickname()
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let new_nick = next_hs_nickname(&old_nick);
|
||
|
|
let launched = self
|
||
|
|
.client
|
||
|
|
.launch_onion_service(hs::hs_config(&new_nick)?)
|
||
|
|
.map_err(|e| format!("launch_onion_service: {e}"))?
|
||
|
|
.ok_or_else(|| "onion service disabled in config — fail closed".to_string())?;
|
||
|
|
let (svc, rend) = launched;
|
||
|
|
let onion = hs::onion_string(&svc)?;
|
||
|
|
// ponytail: hard-cut old HS before waiting; keeping both stalled ow1 at Bootstrapping.
|
||
|
|
*self.hs.lock().map_err(|e| e.to_string())? = None;
|
||
|
|
// The new service is not reachable until it publishes: the locator in
|
||
|
|
// flight is dead until then, so do not carry the old verdict over.
|
||
|
|
self.onion_reachable.store(false, Ordering::SeqCst);
|
||
|
|
let rend = spawn_rend(Arc::clone(self), rend);
|
||
|
|
*self.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle {
|
||
|
|
svc: Arc::clone(&svc),
|
||
|
|
rend,
|
||
|
|
});
|
||
|
|
hs::wait_until_published(&self.client, &svc, &onion).await?;
|
||
|
|
self.onion_reachable.store(true, Ordering::SeqCst);
|
||
|
|
{
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
store.set_onion(&onion).map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.set_hs_nickname(&new_nick)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
}
|
||
|
|
*self.onion.lock().map_err(|e| e.to_string())? = onion.clone();
|
||
|
|
|
||
|
|
let ts = unix_now();
|
||
|
|
let k = self.keys()?;
|
||
|
|
let loc = loc::sign(&k.identity_sk, &onion, ts).map_err(|e| e.to_string())?;
|
||
|
|
let loc_pt = loc::encode(&loc);
|
||
|
|
let friends = self
|
||
|
|
.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.list_friends()
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let mut notified = 0;
|
||
|
|
for f in &friends {
|
||
|
|
if self
|
||
|
|
.push_loc(&f.pubkey, &f.onion, &f.prekey, &loc_pt)
|
||
|
|
.await
|
||
|
|
.is_ok()
|
||
|
|
{
|
||
|
|
notified += 1;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
Ok(RotateResult {
|
||
|
|
notified,
|
||
|
|
friends: friends.len(),
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Rotate the long-lived signed prekey (F8). Hard cut, like the locator
|
||
|
|
/// rotate: the prekey is our Noise static and the bootstrap ratchet epoch is
|
||
|
|
/// derived from the prekey DH, so every stored session is dead the moment
|
||
|
|
/// this returns and every friend has to F3-paste the new invite. Nothing is
|
||
|
|
/// pushed to peers — a new prekey only travels inside a signed invite. The
|
||
|
|
/// identity key (and therefore the fingerprint) does not move; the caller
|
||
|
|
/// re-encodes the F2 invite around the returned pubkey.
|
||
|
|
pub fn rotate_prekey(&self) -> Result<[u8; 32], String> {
|
||
|
|
let mut k = self.keys()?;
|
||
|
|
let sk = StaticSecret::random_from_rng(OsRng);
|
||
|
|
let pk = X25519Public::from(&sk).to_bytes();
|
||
|
|
{
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
// `replace_identity_keys` rewrites the prekey columns too; the
|
||
|
|
// identity values passed back are the ones already stored.
|
||
|
|
store
|
||
|
|
.replace_identity_keys(&k.identity_sk, &k.identity_pk, &sk.to_bytes(), &pk)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
for f in store.list_friends().map_err(|e| e.to_string())? {
|
||
|
|
store.clear_ratchet(&f.pubkey).map_err(|e| e.to_string())?;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
k.prekey_sk = sk.to_bytes();
|
||
|
|
k.prekey_pk = pk;
|
||
|
|
*self.keys.lock().map_err(|e| e.to_string())? = k;
|
||
|
|
Ok(pk)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// One-shot file to a friend. Fail closed; no outbox, no resume.
|
||
|
|
/// Chunks are paced (`file::CHUNK_PACE`) with bounded per-chunk retry so
|
||
|
|
/// a 1 MiB transfer fits the receiver's rendezvous token bucket.
|
||
|
|
pub async fn send_file(&self, friend_pk: &[u8], path: &Path) -> Result<String, String> {
|
||
|
|
let (name, bytes) = file::read_limited(path).map_err(|e| e.to_string())?;
|
||
|
|
let chunks = file::chunks(&name, &bytes).map_err(|e| e.to_string())?;
|
||
|
|
let frames: Vec<Vec<u8>> = chunks.iter().map(file::encode).collect();
|
||
|
|
file::send_chunks(frames.len(), |i| self.send_once(friend_pk, &frames[i])).await?;
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.append_message(
|
||
|
|
friend_pk,
|
||
|
|
"out",
|
||
|
|
file::chat_line(&name, bytes.len()).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(name)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Send one chat message. Returns `Sent` when it went out now and `Queued`
|
||
|
|
/// when the peer's onion is unreachable — the outbox worker then retries with
|
||
|
|
/// backoff. A real protocol error (signature mismatch, unknown/short/oversize
|
||
|
|
/// frame) still fails immediately and is never retried.
|
||
|
|
///
|
||
|
|
/// Chat travels as a `rat ` frame: the plaintext is ratchet-encrypted once,
|
||
|
|
/// here, before the first attempt, and the frame is what the outbox retries.
|
||
|
|
/// Local history keeps the plaintext (the store is encrypted at rest).
|
||
|
|
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
|
||
|
|
self.ensure_running()?;
|
||
|
|
let keys = self.keys()?;
|
||
|
|
let frame = {
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
encode_chat_frame(&store, &keys, friend_pk, plaintext)?
|
||
|
|
};
|
||
|
|
self.outbox.send_payload(friend_pk, plaintext, &frame).await
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Pending and failed outbox rows for a friend, for UI surfacing.
|
||
|
|
/// Delivered rows are dropped, so a message absent here was sent.
|
||
|
|
pub fn outbox_pending(
|
||
|
|
&self,
|
||
|
|
friend_pk: &[u8],
|
||
|
|
) -> Result<Vec<crate::store::OutboxEntry>, String> {
|
||
|
|
self.outbox.pending(friend_pk)
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn outbox_status_of_message(
|
||
|
|
&self,
|
||
|
|
message_id: i64,
|
||
|
|
) -> Result<Option<OutboxStatus>, String> {
|
||
|
|
self.outbox.status_of_message(message_id)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Foreground/unlock trigger: try every outstanding queued send now.
|
||
|
|
pub fn flush_outbox(&self) {
|
||
|
|
spawn_flush_all(Arc::clone(&self.outbox));
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn push_loc(
|
||
|
|
&self,
|
||
|
|
friend_pk: &[u8],
|
||
|
|
onion: &str,
|
||
|
|
prekey: &[u8],
|
||
|
|
loc_pt: &[u8],
|
||
|
|
) -> Result<(), String> {
|
||
|
|
if prekey.len() != 32 {
|
||
|
|
return Err("friend missing prekey".into());
|
||
|
|
}
|
||
|
|
let deadline = Instant::now() + Duration::from_secs(180);
|
||
|
|
let mut last = None::<String>;
|
||
|
|
while Instant::now() < deadline {
|
||
|
|
match self.try_send(onion, friend_pk, prekey, loc_pt).await {
|
||
|
|
Ok(()) => return Ok(()),
|
||
|
|
Err(e) if e.contains("fingerprint mismatch") => return Err(e),
|
||
|
|
Err(e) => last = Some(e),
|
||
|
|
}
|
||
|
|
tokio::time::sleep(Duration::from_secs(3)).await;
|
||
|
|
}
|
||
|
|
Err(last.unwrap_or_else(|| "loc push timed out".into()))
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn try_send(
|
||
|
|
&self,
|
||
|
|
onion: &str,
|
||
|
|
pinned_id: &[u8],
|
||
|
|
remote_prekey: &[u8],
|
||
|
|
plaintext: &[u8],
|
||
|
|
) -> Result<(), String> {
|
||
|
|
self.outbox
|
||
|
|
.deliverer()
|
||
|
|
.deliver(onion, pinned_id, remote_prekey, plaintext)
|
||
|
|
.await
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn handle_incoming<S>(&self, stream: &mut S) -> Result<(), String>
|
||
|
|
where
|
||
|
|
S: AsyncRead + AsyncWrite + Unpin,
|
||
|
|
{
|
||
|
|
let store = &self.store;
|
||
|
|
let keys = self.keys()?;
|
||
|
|
let mut sess = session::handshake_responder(stream, &keys, |spk| {
|
||
|
|
let Ok(g) = store.lock() else {
|
||
|
|
return None;
|
||
|
|
};
|
||
|
|
g.get_friend_by_prekey(spk).ok().flatten().map(|f| f.pubkey)
|
||
|
|
})
|
||
|
|
.await
|
||
|
|
.map_err(session_err)?;
|
||
|
|
// Trigger (c): the peer just proved they are online. Try their queued
|
||
|
|
// sends now instead of waiting out the backoff, off this stream's path.
|
||
|
|
spawn_flush_friend(Arc::clone(&self.outbox), sess.peer_identity.clone());
|
||
|
|
let ct = frame::read_frame(stream).await.map_err(|e| e.to_string())?;
|
||
|
|
let pt = sess.decrypt(&ct).map_err(session_err)?;
|
||
|
|
match dispatch::classify(&pt) {
|
||
|
|
Kind::Loc => {
|
||
|
|
if let Some(loc) = loc::decode(&pt) {
|
||
|
|
let applied = store.lock().map_err(|e| e.to_string())?.apply_loc(
|
||
|
|
&sess.peer_identity,
|
||
|
|
&loc.onion,
|
||
|
|
loc.ts,
|
||
|
|
&loc.sig,
|
||
|
|
);
|
||
|
|
match applied {
|
||
|
|
Ok(true) => {}
|
||
|
|
Ok(false) => {
|
||
|
|
eprintln!("loc dropped (bad sig, stale ts, or unknown friend)")
|
||
|
|
}
|
||
|
|
Err(e) => return Err(e.to_string()),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
Kind::Profile => {
|
||
|
|
if let Some(prf) = profile::decode(&pt) {
|
||
|
|
let applied = store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.apply_profile(&sess.peer_identity, &prf);
|
||
|
|
match applied {
|
||
|
|
Ok(true) => {}
|
||
|
|
Ok(false) => {
|
||
|
|
eprintln!("prf dropped (bad sig, stale ts, or unknown friend)")
|
||
|
|
}
|
||
|
|
Err(e) => return Err(e.to_string()),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
Kind::Chat => {
|
||
|
|
store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.append_message(
|
||
|
|
&sess.peer_identity,
|
||
|
|
"in",
|
||
|
|
sanitize::display_text(&pt).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
Kind::Ratchet => {
|
||
|
|
// Chat arrives as a ratchet frame: decrypt, log the plaintext,
|
||
|
|
// drop the frame. A bad frame is logged and dropped — the
|
||
|
|
// ciphertext is never stored and there is no plaintext fallback.
|
||
|
|
let keys = self.keys()?;
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
if let Err(e) = ingest_chat_frame(&store, &keys, &sess.peer_identity, &pt) {
|
||
|
|
eprintln!("rat dropped ({e})");
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
Kind::Invoice => self.ingest_invoice(&sess.peer_identity, &pt).await,
|
||
|
|
Kind::Receipt => self.ingest_receipt(&sess.peer_identity, &pt).await,
|
||
|
|
Kind::Tip => self.ingest_tip(&sess.peer_identity, &pt).await,
|
||
|
|
Kind::File => self.ingest_file(&sess.peer_identity, &pt),
|
||
|
|
Kind::Ping | Kind::Drop => Ok(()),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
fn ingest_file(&self, peer: &[u8], pt: &[u8]) -> Result<(), String> {
|
||
|
|
let Some(chunk) = file::decode(pt) else {
|
||
|
|
return Ok(());
|
||
|
|
};
|
||
|
|
let fp: String = peer.iter().map(|b| format!("{b:02x}")).collect();
|
||
|
|
let done = {
|
||
|
|
let mut inbox = self.inbox.lock().map_err(|e| e.to_string())?;
|
||
|
|
match inbox.ingest(&fp, &chunk) {
|
||
|
|
Ok(p) => p,
|
||
|
|
Err(e) => {
|
||
|
|
eprintln!("fil dropped ({e})");
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
}
|
||
|
|
};
|
||
|
|
if let Some(path) = done {
|
||
|
|
let nbytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0) as usize;
|
||
|
|
let name = path
|
||
|
|
.file_name()
|
||
|
|
.and_then(|s| s.to_str())
|
||
|
|
.unwrap_or(&chunk.filename);
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.append_message(
|
||
|
|
peer,
|
||
|
|
"in",
|
||
|
|
sanitize::display_text(file::chat_line(name, nbytes).as_bytes()).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn ingest_invoice(&self, peer: &[u8], pt: &[u8]) -> Result<(), String> {
|
||
|
|
let Some(inv) = pay::decode_invoice(pt) else {
|
||
|
|
return Ok(());
|
||
|
|
};
|
||
|
|
if !pay::verify_invoice(peer, &inv) {
|
||
|
|
eprintln!("inv dropped (bad sig)");
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.insert_payment(
|
||
|
|
peer,
|
||
|
|
PaymentWrite {
|
||
|
|
dir: "in",
|
||
|
|
kind: "invoice",
|
||
|
|
amount_atomic: &inv.amount_atomic,
|
||
|
|
address: &inv.address,
|
||
|
|
memo: &inv.memo,
|
||
|
|
txid: None,
|
||
|
|
verified: false,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.append_message(
|
||
|
|
peer,
|
||
|
|
"in",
|
||
|
|
pay::invoice_chat_line(&inv.amount_atomic, &inv.memo).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn ingest_receipt(&self, peer: &[u8], pt: &[u8]) -> Result<(), String> {
|
||
|
|
let Some(rcp) = pay::decode_receipt(pt) else {
|
||
|
|
return Ok(());
|
||
|
|
};
|
||
|
|
if !pay::verify_receipt(peer, &rcp) {
|
||
|
|
eprintln!("rcp dropped (bad sig)");
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
let id = {
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.insert_payment(
|
||
|
|
peer,
|
||
|
|
PaymentWrite {
|
||
|
|
dir: "in",
|
||
|
|
kind: "receipt",
|
||
|
|
amount_atomic: &rcp.amount_atomic,
|
||
|
|
address: &rcp.address,
|
||
|
|
memo: "",
|
||
|
|
txid: Some(&rcp.txid),
|
||
|
|
verified: false,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
};
|
||
|
|
let mut verified = false;
|
||
|
|
// Honest prerequisite: an unsynced wallet cannot see the tx, so a
|
||
|
|
// get_transfers "miss" would be a lie. Until the chain is ready the
|
||
|
|
// receipt stays verified=0 — that is the correct state, not an error.
|
||
|
|
let w = self.wallet_snapshot();
|
||
|
|
let ready = w.configured() && w.can_verify_receipts().await;
|
||
|
|
if ready {
|
||
|
|
match w.get_transfers().await {
|
||
|
|
Ok(rows)
|
||
|
|
if wallet::transfers_match(
|
||
|
|
&rows,
|
||
|
|
&rcp.txid,
|
||
|
|
&rcp.amount_atomic,
|
||
|
|
&rcp.address,
|
||
|
|
) =>
|
||
|
|
{
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.mark_verified(id)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
verified = true;
|
||
|
|
}
|
||
|
|
Ok(_) => {}
|
||
|
|
Err(e) => eprintln!("receipt unverified: {e}"),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if !verified {
|
||
|
|
eprintln!("receipt unverified");
|
||
|
|
}
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.append_message(
|
||
|
|
peer,
|
||
|
|
"in",
|
||
|
|
pay::receipt_chat_line(&rcp.amount_atomic, verified).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn ingest_tip(&self, peer: &[u8], pt: &[u8]) -> Result<(), String> {
|
||
|
|
let Some(tip) = pay::decode_tip(pt) else {
|
||
|
|
return Ok(());
|
||
|
|
};
|
||
|
|
if !pay::verify_tip(peer, &tip) {
|
||
|
|
eprintln!("tip dropped (bad sig)");
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.insert_payment(
|
||
|
|
peer,
|
||
|
|
PaymentWrite {
|
||
|
|
dir: "in",
|
||
|
|
kind: "tip",
|
||
|
|
amount_atomic: &tip.amount_atomic,
|
||
|
|
address: &tip.address,
|
||
|
|
memo: &tip.memo,
|
||
|
|
txid: Some(&tip.txid),
|
||
|
|
verified: false,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.append_message(
|
||
|
|
peer,
|
||
|
|
"in",
|
||
|
|
pay::tip_chat_line(&tip.amount_atomic, &tip.memo, false).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// How long a freshly spawned child's wallet RPC gets to start answering before
|
||
|
|
/// an `open_wallet` attempt is a failure rather than a start still in progress.
|
||
|
|
/// `monero-wallet-rpc` binds its port well inside this; a child that never
|
||
|
|
/// answers is reported, not waited on forever.
|
||
|
|
const WALLET_OPEN_WAIT: Duration = Duration::from_secs(10);
|
||
|
|
const WALLET_OPEN_POLL: Duration = Duration::from_millis(100);
|
||
|
|
|
||
|
|
/// Why an `open_wallet` did not happen. Split because the two want opposite
|
||
|
|
/// treatment: one is a child still coming up, the other is the RPC's own answer
|
||
|
|
/// and retrying it would only repeat it.
|
||
|
|
enum OpenFailure {
|
||
|
|
/// The RPC never answered inside the budget.
|
||
|
|
NotAnswering(String),
|
||
|
|
/// The RPC answered and refused — a wrong passphrase for that file.
|
||
|
|
Refused(String),
|
||
|
|
}
|
||
|
|
|
||
|
|
impl OpenFailure {
|
||
|
|
/// Display copy. Names the file and the RPC's own reason; carries no secret
|
||
|
|
/// (the passphrase never enters an error string).
|
||
|
|
fn message(&self, filename: &str) -> String {
|
||
|
|
match self {
|
||
|
|
OpenFailure::Refused(detail) => format!(
|
||
|
|
"wallet file {filename} is not open — the RPC refused its passphrase ({detail})"
|
||
|
|
),
|
||
|
|
OpenFailure::NotAnswering(detail) => format!(
|
||
|
|
"wallet file {filename} is not open — the wallet RPC never answered ({detail})"
|
||
|
|
),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Run one `open_wallet` from a synchronous caller, retrying only while the
|
||
|
|
/// child's RPC is still coming up.
|
||
|
|
///
|
||
|
|
/// `Node::start_wallet_child` is synchronous (the TUI's key handler, and the
|
||
|
|
/// SDK's `spawn_blocking` wrapper) while the wallet client is `tokio`, and a
|
||
|
|
/// synchronous caller is not always somewhere the thread may be parked: a
|
||
|
|
/// current-thread runtime (every `#[tokio::test]` here) shares its single thread
|
||
|
|
/// with the reactor the future needs, so a nested `block_on` there would
|
||
|
|
/// deadlock. The RPC therefore runs on a scratch thread with its own runtime —
|
||
|
|
/// no nested runtime, no assumption about the caller.
|
||
|
|
fn open_wallet_blocking(
|
||
|
|
wallet: &Wallet,
|
||
|
|
filename: &str,
|
||
|
|
passphrase: &str,
|
||
|
|
) -> std::result::Result<(), OpenFailure> {
|
||
|
|
let wallet = wallet.clone();
|
||
|
|
let filename = filename.to_string();
|
||
|
|
let passphrase = Zeroizing::new(passphrase.to_string());
|
||
|
|
std::thread::scope(|scope| {
|
||
|
|
scope
|
||
|
|
.spawn(|| {
|
||
|
|
let rt = tokio::runtime::Builder::new_current_thread()
|
||
|
|
.enable_all()
|
||
|
|
.build()
|
||
|
|
.map_err(|e| OpenFailure::NotAnswering(format!("runtime: {e}")))?;
|
||
|
|
rt.block_on(async {
|
||
|
|
let deadline = tokio::time::Instant::now() + WALLET_OPEN_WAIT;
|
||
|
|
loop {
|
||
|
|
match wallet.open_wallet(&filename, passphrase.as_str()).await {
|
||
|
|
Ok(()) => return Ok(()),
|
||
|
|
Err(e) if e.is_unreachable() => {
|
||
|
|
if tokio::time::Instant::now() >= deadline {
|
||
|
|
return Err(OpenFailure::NotAnswering(e.to_string()));
|
||
|
|
}
|
||
|
|
tokio::time::sleep(WALLET_OPEN_POLL).await;
|
||
|
|
}
|
||
|
|
Err(e) => return Err(OpenFailure::Refused(e.to_string())),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
})
|
||
|
|
})
|
||
|
|
.join()
|
||
|
|
.map_err(|_| OpenFailure::NotAnswering("open_wallet thread panicked".into()))?
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
/// HKDF info strings for the bootstrap derivation (see [`bootstrap_ratchet`]).
|
||
|
|
const RATCHET_BOOTSTRAP_SALT: &[u8] = b"onionwire-ratchet-v1-bootstrap";
|
||
|
|
const RATCHET_BOOTSTRAP_ROOT_INFO: &[u8] = b"root";
|
||
|
|
const RATCHET_BOOTSTRAP_KEY_INFO: &[u8] = b"ratchet-key";
|
||
|
|
|
||
|
|
/// Bootstrap a peer's ratchet state from key material both sides already have.
|
||
|
|
///
|
||
|
|
/// The Noise handshake is frozen and carries no payload, so no wire field can
|
||
|
|
/// hand over an initial ratchet public key. Both peers instead derive the
|
||
|
|
/// bootstrap epoch from the X25519 DH of the two signed prekeys — each side
|
||
|
|
/// computes the same secret — and seed each side's initial ratchet keypair with
|
||
|
|
/// that DH plus *its own* identity pubkey. Each peer therefore derives its own
|
||
|
|
/// keypair and the peer's, and the two agree on the epoch without a new wire
|
||
|
|
/// field; fresh entropy enters at the first DH ratchet step. Because the
|
||
|
|
/// derivation is prekey-bound, a peer whose prekey changed gets its stored state
|
||
|
|
/// dropped (`Node::add_friend_payload`).
|
||
|
|
fn bootstrap_ratchet(
|
||
|
|
keys: &Keys,
|
||
|
|
peer_pk: &[u8],
|
||
|
|
peer_prekey: &[u8],
|
||
|
|
) -> Result<RatchetState, String> {
|
||
|
|
let peer_pk: [u8; 32] = peer_pk
|
||
|
|
.try_into()
|
||
|
|
.map_err(|_| "peer pubkey is not 32 bytes".to_string())?;
|
||
|
|
let peer_prekey: [u8; 32] = peer_prekey
|
||
|
|
.try_into()
|
||
|
|
.map_err(|_| "peer prekey is not 32 bytes".to_string())?;
|
||
|
|
let shared =
|
||
|
|
StaticSecret::from(keys.prekey_sk).diffie_hellman(&X25519Public::from(peer_prekey));
|
||
|
|
let hk = Hkdf::<Sha256>::new(Some(RATCHET_BOOTSTRAP_SALT), shared.as_bytes());
|
||
|
|
|
||
|
|
let mut root_key = [0u8; 32];
|
||
|
|
hk.expand(RATCHET_BOOTSTRAP_ROOT_INFO, &mut root_key)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let local = RatchetKeyPair::from_secret(ratchet_seed(&hk, &keys.identity_pk)?);
|
||
|
|
let remote = ratchet_seed(&hk, &peer_pk)?;
|
||
|
|
let remote_pub = X25519Public::from(&StaticSecret::from(remote)).to_bytes();
|
||
|
|
Ok(RatchetState::bootstrap(root_key, local, remote_pub))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// `HKDF(info = "ratchet-key" || pubkey)` — the initial ratchet secret both
|
||
|
|
/// peers compute for the peer with that identity pubkey.
|
||
|
|
fn ratchet_seed(hk: &Hkdf<Sha256>, pubkey: &[u8; 32]) -> Result<[u8; 32], String> {
|
||
|
|
let mut info = Vec::with_capacity(RATCHET_BOOTSTRAP_KEY_INFO.len() + 32);
|
||
|
|
info.extend_from_slice(RATCHET_BOOTSTRAP_KEY_INFO);
|
||
|
|
info.extend_from_slice(pubkey);
|
||
|
|
let mut seed = Zeroizing::new([0u8; 32]);
|
||
|
|
hk.expand(&info, &mut seed[..]).map_err(|e| e.to_string())?;
|
||
|
|
Ok(*seed)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The peer's ratchet state: the persisted blob when there is one, a freshly
|
||
|
|
/// bootstrapped state otherwise.
|
||
|
|
///
|
||
|
|
/// The blob is opaque to the store; `RatchetState::to_bytes`/`from_bytes` own
|
||
|
|
/// the format. Nothing is written here — the caller persists once, after a
|
||
|
|
/// successful encrypt/decrypt, so a rejected frame cannot leave a half-created
|
||
|
|
/// session behind.
|
||
|
|
fn ratchet_for(store: &Store, keys: &Keys, friend_pk: &[u8]) -> Result<RatchetState, String> {
|
||
|
|
if let Some(blob) = store.load_ratchet(friend_pk).map_err(|e| e.to_string())? {
|
||
|
|
return RatchetState::from_bytes(&blob).map_err(|e| format!("ratchet state: {e}"));
|
||
|
|
}
|
||
|
|
let f = store
|
||
|
|
.get_friend(friend_pk)
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.ok_or_else(|| "unknown friend".to_string())?;
|
||
|
|
if f.prekey.len() != 32 {
|
||
|
|
return Err("friend missing prekey".into());
|
||
|
|
}
|
||
|
|
bootstrap_ratchet(keys, friend_pk, &f.prekey)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Encode one chat send as a `rat ` frame, then persist the advanced state.
|
||
|
|
///
|
||
|
|
/// Exactly one frame per call, and the caller passes those bytes to
|
||
|
|
/// `Outbox::send_payload`, so a retry re-sends them verbatim instead of
|
||
|
|
/// advancing the sending chain a second time.
|
||
|
|
///
|
||
|
|
/// Public because it is the wire half of `Node::send`: `tests/ratchet_wire.rs`
|
||
|
|
/// drives the real path without Tor. Callers hold the store lock across
|
||
|
|
/// load → encrypt → save.
|
||
|
|
pub fn encode_chat_frame(
|
||
|
|
store: &Store,
|
||
|
|
keys: &Keys,
|
||
|
|
friend_pk: &[u8],
|
||
|
|
plaintext: &[u8],
|
||
|
|
) -> Result<Vec<u8>, String> {
|
||
|
|
let mut state = ratchet_for(store, keys, friend_pk)?;
|
||
|
|
let frame = state.encrypt(plaintext).map_err(|e| e.to_string())?;
|
||
|
|
let blob = Zeroizing::new(state.to_bytes());
|
||
|
|
store
|
||
|
|
.save_ratchet(friend_pk, &blob)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(frame)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Decrypt one inbound `rat ` frame and append it to the chat log as an
|
||
|
|
/// incoming line, then persist the advanced state.
|
||
|
|
///
|
||
|
|
/// Returns the logged plaintext, or `Err` for anything that did not
|
||
|
|
/// authenticate — a bad frame writes no chat row and leaves the stored state
|
||
|
|
/// untouched, because `RatchetState` validates fully before it mutates. The
|
||
|
|
/// ciphertext is never stored and there is no plaintext fallback.
|
||
|
|
///
|
||
|
|
/// Public for the same reason as [`encode_chat_frame`]. Callers hold the store
|
||
|
|
/// lock across load → decrypt → append → save, which is what makes the
|
||
|
|
/// read-modify-write atomic against a second inbound session on the same peer.
|
||
|
|
pub fn ingest_chat_frame(
|
||
|
|
store: &Store,
|
||
|
|
keys: &Keys,
|
||
|
|
peer_pk: &[u8],
|
||
|
|
frame: &[u8],
|
||
|
|
) -> Result<Vec<u8>, String> {
|
||
|
|
let mut state = ratchet_for(store, keys, peer_pk)?;
|
||
|
|
let plaintext = state.decrypt(frame).map_err(|e| e.to_string())?;
|
||
|
|
let line = Zeroizing::new(sanitize::display_text(&plaintext).as_bytes().to_vec());
|
||
|
|
store
|
||
|
|
.append_message(peer_pk, "in", &line[..])
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let blob = Zeroizing::new(state.to_bytes());
|
||
|
|
store
|
||
|
|
.save_ratchet(peer_pk, &blob)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(line.to_vec())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The error a wallet-child probe leaves on the status row.
|
||
|
|
///
|
||
|
|
/// `probed` is what the probe said (`None` when the RPC answered); `previous` is
|
||
|
|
/// what the row already held. A wallet RPC that refuses the connection because
|
||
|
|
/// it is still coming up is not an error to show — the row would flash
|
||
|
|
/// `wallet connect: Connection refused` and then clear itself on the next tick.
|
||
|
|
/// It is not silent either: whatever real error the row already held survives.
|
||
|
|
/// A timeout, `-13`, `No wallet file`, or a bad passphrase is the RPC's own
|
||
|
|
/// answer and is kept, as is the same connect text once the child is up and
|
||
|
|
/// answering (`connected`) and then stops.
|
||
|
|
pub(crate) fn probe_error(
|
||
|
|
connected: bool,
|
||
|
|
probed: Option<String>,
|
||
|
|
previous: Option<String>,
|
||
|
|
) -> Option<String> {
|
||
|
|
if connected {
|
||
|
|
return None;
|
||
|
|
}
|
||
|
|
match probed {
|
||
|
|
Some(err) if wallet::error_is_unreachable(&err) => {
|
||
|
|
previous.filter(|prev| !wallet::error_is_unreachable(prev))
|
||
|
|
}
|
||
|
|
other => other,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
fn spawn_rend(
|
||
|
|
node: Arc<Node>,
|
||
|
|
rend: impl futures::Stream<Item = tor_hsservice::RendRequest> + Send + 'static,
|
||
|
|
) -> tokio::task::JoinHandle<()> {
|
||
|
|
tokio::spawn(async move {
|
||
|
|
let mut requests = std::pin::pin!(handle_rend_requests(rend));
|
||
|
|
while let Some(req) = requests.next().await {
|
||
|
|
let allow = node
|
||
|
|
.incoming_limit
|
||
|
|
.lock()
|
||
|
|
.map(|mut b| b.try_acquire())
|
||
|
|
.unwrap_or(false);
|
||
|
|
if !allow {
|
||
|
|
eprintln!("rate-limit drop");
|
||
|
|
drop(req);
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
let serve = Arc::clone(&node);
|
||
|
|
tokio::spawn(async move {
|
||
|
|
let Ok(mut stream) = req.accept(Connected::new_empty()).await else {
|
||
|
|
return;
|
||
|
|
};
|
||
|
|
if let Err(e) = serve.handle_incoming(&mut stream).await {
|
||
|
|
eprintln!("incoming: {e}");
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Foreground/unlock flush: every outstanding queued send gets one attempt now.
|
||
|
|
fn spawn_flush_all(outbox: Arc<Outbox>) {
|
||
|
|
tokio::spawn(async move {
|
||
|
|
if let Err(e) = outbox.flush_all(unix_now()).await {
|
||
|
|
eprintln!("outbox: {e}");
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
/// We just saw this peer (handshake or successful dial): try their queue now.
|
||
|
|
fn spawn_flush_friend(outbox: Arc<Outbox>, friend_pk: Vec<u8>) {
|
||
|
|
tokio::spawn(async move {
|
||
|
|
if let Err(e) = outbox.flush_friend(&friend_pk, unix_now()).await {
|
||
|
|
eprintln!("outbox: {e}");
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
fn next_hs_nickname(cur: &str) -> String {
|
||
|
|
let n = cur
|
||
|
|
.strip_prefix("ow")
|
||
|
|
.and_then(|s| s.parse::<u32>().ok())
|
||
|
|
.unwrap_or(0);
|
||
|
|
format!("ow{}", n.saturating_add(1))
|
||
|
|
}
|
||
|
|
|
||
|
|
fn unix_now() -> i64 {
|
||
|
|
SystemTime::now()
|
||
|
|
.duration_since(UNIX_EPOCH)
|
||
|
|
.map(|d| d.as_secs() as i64)
|
||
|
|
.unwrap_or(0)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn session_err(e: session::Error) -> String {
|
||
|
|
if e.is_fingerprint_mismatch() {
|
||
|
|
crate::tui::fingerprint_mismatch_banner().to_string()
|
||
|
|
} else {
|
||
|
|
e.to_string()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool {
|
||
|
|
let mut stack = vec![dir.to_path_buf()];
|
||
|
|
while let Some(p) = stack.pop() {
|
||
|
|
let Ok(rd) = std::fs::read_dir(&p) else {
|
||
|
|
continue;
|
||
|
|
};
|
||
|
|
for ent in rd.flatten() {
|
||
|
|
let path = ent.path();
|
||
|
|
if path.is_dir() {
|
||
|
|
stack.push(path);
|
||
|
|
} else if let Ok(bytes) = std::fs::read(&path)
|
||
|
|
&& bytes.windows(needle.len()).any(|w| w == needle)
|
||
|
|
{
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
false
|
||
|
|
}
|
||
|
|
|
||
|
|
#[cfg(test)]
|
||
|
|
/// A catalogue row written straight into the store, for tests that need a saved
|
||
|
|
/// wallet without a wallet RPC.
|
||
|
|
pub(crate) fn test_record_wallet(store: &Store, file: &str, label: &str) {
|
||
|
|
let identity_pubkey: [u8; 32] = store
|
||
|
|
.self_identity()
|
||
|
|
.expect("self identity")
|
||
|
|
.identity_pk
|
||
|
|
.try_into()
|
||
|
|
.expect("32-byte identity");
|
||
|
|
store
|
||
|
|
.create_wallet(&NewWallet {
|
||
|
|
name: (!label.trim().is_empty()).then(|| label.to_string()),
|
||
|
|
identity_pubkey,
|
||
|
|
onion_locator: format!("{file}.onion"),
|
||
|
|
wallet_filename: file.to_string(),
|
||
|
|
})
|
||
|
|
.expect("create wallet");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A real `Node` with no Tor and a seeded wallet catalogue, for the TUI's own
|
||
|
|
/// tests: `App` reads the catalogue, and the only public `Node` constructor
|
||
|
|
/// bootstraps Tor. `wallets` is `(file name, label)` — a blank label is stored
|
||
|
|
/// as `NULL`, like a wallet created without one.
|
||
|
|
#[cfg(test)]
|
||
|
|
pub(crate) fn test_node_with_wallets(home: &Path, wallets: &[(&str, &str)]) -> Arc<Node> {
|
||
|
|
{
|
||
|
|
let store = Store::open_at_with_passphrase(home, tests::PASS).expect("open store");
|
||
|
|
for (file, label) in wallets {
|
||
|
|
test_record_wallet(&store, file, label);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Arc::new(tests::offline_node(home, Arc::new(tests::NoDial)))
|
||
|
|
}
|
||
|
|
|
||
|
|
#[cfg(test)]
|
||
|
|
pub(crate) mod tests {
|
||
|
|
use super::*;
|
||
|
|
use crate::wallet_child::DEFAULT_MONEROD_RPC_PORT;
|
||
|
|
use crate::wallet_child::test_support::PublishedPortHold;
|
||
|
|
use std::pin::Pin;
|
||
|
|
|
||
|
|
use crate::wallet::ChainSource;
|
||
|
|
use std::task::{Context, Poll};
|
||
|
|
|
||
|
|
use futures::io::{AsyncRead, AsyncWrite};
|
||
|
|
use tokio::io::AsyncRead as TokioRead;
|
||
|
|
use tokio::io::AsyncWrite as TokioWrite;
|
||
|
|
|
||
|
|
pub(crate) const PASS: &str = "node-ratchet-test-pass";
|
||
|
|
|
||
|
|
/// Never dials: every send queues, which is what leaves the encoded frame
|
||
|
|
/// visible on the outbox row.
|
||
|
|
pub(crate) struct NoDial;
|
||
|
|
|
||
|
|
impl crate::outbox::Deliverer for NoDial {
|
||
|
|
fn deliver<'a>(
|
||
|
|
&'a self,
|
||
|
|
_onion: &'a str,
|
||
|
|
_pinned_id: &'a [u8],
|
||
|
|
_prekey: &'a [u8],
|
||
|
|
_payload: &'a [u8],
|
||
|
|
) -> crate::outbox::BoxFut<'a, Result<(), String>> {
|
||
|
|
Box::pin(async { Err("connect peer.onion:80: timed out".to_string()) })
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// `handle_incoming` is generic over `futures::io` streams while
|
||
|
|
/// `tokio::io::duplex` hands out `tokio::io` ones; one line per method
|
||
|
|
/// beats a new dev-dependency.
|
||
|
|
struct Duplex(tokio::io::DuplexStream);
|
||
|
|
|
||
|
|
impl AsyncRead for Duplex {
|
||
|
|
fn poll_read(
|
||
|
|
self: Pin<&mut Self>,
|
||
|
|
cx: &mut Context<'_>,
|
||
|
|
buf: &mut [u8],
|
||
|
|
) -> Poll<std::io::Result<usize>> {
|
||
|
|
let mut read_buf = tokio::io::ReadBuf::new(buf);
|
||
|
|
match Pin::new(&mut self.get_mut().0).poll_read(cx, &mut read_buf) {
|
||
|
|
Poll::Ready(Ok(())) => Poll::Ready(Ok(read_buf.filled().len())),
|
||
|
|
Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
|
||
|
|
Poll::Pending => Poll::Pending,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
impl AsyncWrite for Duplex {
|
||
|
|
fn poll_write(
|
||
|
|
self: Pin<&mut Self>,
|
||
|
|
cx: &mut Context<'_>,
|
||
|
|
buf: &[u8],
|
||
|
|
) -> Poll<std::io::Result<usize>> {
|
||
|
|
Pin::new(&mut self.get_mut().0).poll_write(cx, buf)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||
|
|
Pin::new(&mut self.get_mut().0).poll_flush(cx)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||
|
|
Pin::new(&mut self.get_mut().0).poll_shutdown(cx)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A real `Node` with no Tor: an unbootstrapped client, no onion service,
|
||
|
|
/// and a deliverer that never dials. `Node::start` / `start_with_passphrase`
|
||
|
|
/// are the only public constructors and both bootstrap Tor and publish an
|
||
|
|
/// onion service, so this is the only way to drive the shipped send and
|
||
|
|
/// receive path offline.
|
||
|
|
pub(crate) fn offline_node(home: &Path, deliverer: Arc<dyn crate::outbox::Deliverer>) -> Node {
|
||
|
|
offline_node_with_wallet(home, deliverer, Wallet::disabled())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// [`offline_node`] with a wallet child attached: the outbound tip path
|
||
|
|
/// cannot get past `Wallet::configured()` without one.
|
||
|
|
fn offline_node_with_wallet(
|
||
|
|
home: &Path,
|
||
|
|
deliverer: Arc<dyn crate::outbox::Deliverer>,
|
||
|
|
wallet: Wallet,
|
||
|
|
) -> Node {
|
||
|
|
std::fs::create_dir_all(home).expect("create home");
|
||
|
|
// The app-owned child creates the wallet dir 0700 before a wallet can
|
||
|
|
// be configured, and the picker now insists on listing it.
|
||
|
|
std::fs::create_dir_all(home.join("wallet")).expect("create wallet dir");
|
||
|
|
let store = Store::open_at_with_passphrase(home, PASS).expect("open store");
|
||
|
|
let keys = Keys::from_self(&store.self_identity().expect("self identity")).expect("keys");
|
||
|
|
let client = arti_client::TorClient::builder()
|
||
|
|
.config(hs::client_config(&home.join("arti"), &home.join("cache")))
|
||
|
|
.create_unbootstrapped()
|
||
|
|
.expect("unbootstrapped Tor client");
|
||
|
|
let store = Arc::new(Mutex::new(store));
|
||
|
|
let outbox = Arc::new(Outbox::new(Arc::clone(&store), deliverer));
|
||
|
|
let wallet_status = WalletStatus::idle(wallet.configured());
|
||
|
|
Node {
|
||
|
|
home: home.to_path_buf(),
|
||
|
|
store,
|
||
|
|
client,
|
||
|
|
hs: Mutex::new(None),
|
||
|
|
onion: Mutex::new("test.onion".to_string()),
|
||
|
|
keys: Mutex::new(keys),
|
||
|
|
wallet: Mutex::new(wallet),
|
||
|
|
wallet_status: Mutex::new(wallet_status),
|
||
|
|
wallet_child: Mutex::new(None),
|
||
|
|
child_synced: AtomicBool::new(false),
|
||
|
|
child_height: AtomicU64::new(0),
|
||
|
|
child_target: AtomicU64::new(0),
|
||
|
|
child_error: Mutex::new(None),
|
||
|
|
child_wallet: Mutex::new(ChildWalletState::Unknown),
|
||
|
|
incoming_limit: Mutex::new(TokenBucket::default()),
|
||
|
|
inbox: Mutex::new(file::Inbox::new(home.join("inbox"))),
|
||
|
|
outbox,
|
||
|
|
worker: Mutex::new(None),
|
||
|
|
stopped: AtomicBool::new(false),
|
||
|
|
onion_reachable: AtomicBool::new(false),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The friend row a scanned invite leaves behind.
|
||
|
|
fn befriend(store: &Store, other_pk: &[u8], other_prekey: &[u8], onion: &str) {
|
||
|
|
store
|
||
|
|
.upsert_friend(other_pk, onion, None)
|
||
|
|
.expect("upsert friend");
|
||
|
|
store
|
||
|
|
.set_friend_prekey(other_pk, other_prekey)
|
||
|
|
.expect("set friend prekey");
|
||
|
|
}
|
||
|
|
|
||
|
|
fn node_prekey(node: &Node) -> [u8; 32] {
|
||
|
|
node.keys.lock().unwrap().prekey_pk
|
||
|
|
}
|
||
|
|
|
||
|
|
/// One peer→node dial, end to end: a real Noise IK handshake and one
|
||
|
|
/// already-encoded frame over an in-memory stream, into `handle_incoming`.
|
||
|
|
async fn deliver_frame(node: &Node, peer: &Keys, frame: &[u8]) -> Result<(), String> {
|
||
|
|
let node_pk = node.identity_pk();
|
||
|
|
let node_prekey = node_prekey(node);
|
||
|
|
let (client_side, server_side) = tokio::io::duplex(64 * 1024);
|
||
|
|
|
||
|
|
let send = async {
|
||
|
|
let mut stream = Duplex(client_side);
|
||
|
|
let mut sess = session::handshake_initiator(&mut stream, peer, &node_pk, &node_prekey)
|
||
|
|
.await
|
||
|
|
.map_err(|e| e.into_message())?;
|
||
|
|
let ct = sess.encrypt(frame).map_err(|e| e.into_message())?;
|
||
|
|
frame::write_frame(&mut stream, &ct)
|
||
|
|
.await
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
};
|
||
|
|
let receive = async {
|
||
|
|
let mut stream = Duplex(server_side);
|
||
|
|
node.handle_incoming(&mut stream).await
|
||
|
|
};
|
||
|
|
let (sent, received) = futures::join!(send, receive);
|
||
|
|
sent?;
|
||
|
|
received
|
||
|
|
}
|
||
|
|
|
||
|
|
fn chat_lines(node: &Node, peer: &Keys) -> Vec<(String, String)> {
|
||
|
|
node.list_messages(&peer.identity_pk)
|
||
|
|
.expect("list messages")
|
||
|
|
.into_iter()
|
||
|
|
.map(|m| {
|
||
|
|
(
|
||
|
|
m.dir,
|
||
|
|
String::from_utf8(m.plaintext).expect("utf8 chat line"),
|
||
|
|
)
|
||
|
|
})
|
||
|
|
.collect()
|
||
|
|
}
|
||
|
|
|
||
|
|
#[tokio::test]
|
||
|
|
async fn send_queues_one_ratchet_frame_and_keeps_the_plaintext_local() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||
|
|
let peer = Keys::generate();
|
||
|
|
befriend(
|
||
|
|
&node.store.lock().unwrap(),
|
||
|
|
&peer.identity_pk,
|
||
|
|
&peer.prekey_pk,
|
||
|
|
"peer.onion",
|
||
|
|
);
|
||
|
|
|
||
|
|
assert_eq!(
|
||
|
|
node.send(&peer.identity_pk, b"hello bob").await.unwrap(),
|
||
|
|
OutboxStatus::Queued,
|
||
|
|
"with nothing to dial, the send queues for the retry worker"
|
||
|
|
);
|
||
|
|
|
||
|
|
let rows = node.outbox_pending(&peer.identity_pk).unwrap();
|
||
|
|
assert_eq!(rows.len(), 1);
|
||
|
|
let payload = rows[0]
|
||
|
|
.payload
|
||
|
|
.clone()
|
||
|
|
.expect("the encoded frame rides on the outbox row");
|
||
|
|
assert!(
|
||
|
|
payload.starts_with(b"rat "),
|
||
|
|
"chat goes out as a ratchet frame"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
!payload.windows(9).any(|w| w == b"hello bob"),
|
||
|
|
"the plaintext is not on the wire"
|
||
|
|
);
|
||
|
|
assert_eq!(
|
||
|
|
rows[0].body, b"hello bob",
|
||
|
|
"local history keeps the plaintext"
|
||
|
|
);
|
||
|
|
|
||
|
|
assert_eq!(
|
||
|
|
chat_lines(&node, &peer),
|
||
|
|
vec![("out".to_string(), "hello bob".to_string())]
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[tokio::test]
|
||
|
|
async fn an_inbound_frame_is_dispatched_to_the_ratchet_and_logged() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||
|
|
let peer = Keys::generate();
|
||
|
|
befriend(
|
||
|
|
&node.store.lock().unwrap(),
|
||
|
|
&peer.identity_pk,
|
||
|
|
&peer.prekey_pk,
|
||
|
|
"peer.onion",
|
||
|
|
);
|
||
|
|
// The peer's own store holds its ratchet state, as a second Node does.
|
||
|
|
let peer_store =
|
||
|
|
Store::open_at_with_passphrase(&dir.path().join("alice"), PASS).expect("peer store");
|
||
|
|
befriend(
|
||
|
|
&peer_store,
|
||
|
|
&node.identity_pk(),
|
||
|
|
&node_prekey(&node),
|
||
|
|
"node.onion",
|
||
|
|
);
|
||
|
|
|
||
|
|
let frame =
|
||
|
|
encode_chat_frame(&peer_store, &peer, &node.identity_pk(), b"hi bob").expect("encode");
|
||
|
|
deliver_frame(&node, &peer, &frame).await.expect("receive");
|
||
|
|
|
||
|
|
assert_eq!(
|
||
|
|
chat_lines(&node, &peer),
|
||
|
|
vec![("in".to_string(), "hi bob".to_string())],
|
||
|
|
"`rat ` is dispatched to the ratchet, not logged as ciphertext chat"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[tokio::test]
|
||
|
|
async fn the_receive_path_keeps_arrival_order_and_drops_replays_and_garbage() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||
|
|
let peer = Keys::generate();
|
||
|
|
befriend(
|
||
|
|
&node.store.lock().unwrap(),
|
||
|
|
&peer.identity_pk,
|
||
|
|
&peer.prekey_pk,
|
||
|
|
"peer.onion",
|
||
|
|
);
|
||
|
|
let peer_store =
|
||
|
|
Store::open_at_with_passphrase(&dir.path().join("alice"), PASS).expect("peer store");
|
||
|
|
befriend(
|
||
|
|
&peer_store,
|
||
|
|
&node.identity_pk(),
|
||
|
|
&node_prekey(&node),
|
||
|
|
"node.onion",
|
||
|
|
);
|
||
|
|
|
||
|
|
let frames: Vec<Vec<u8>> = ["m0", "m1", "m2"]
|
||
|
|
.iter()
|
||
|
|
.map(|t| {
|
||
|
|
encode_chat_frame(&peer_store, &peer, &node.identity_pk(), t.as_bytes())
|
||
|
|
.expect("encode")
|
||
|
|
})
|
||
|
|
.collect();
|
||
|
|
|
||
|
|
// Arrival order 2, 0, 1 — the ratchet holds the two it has not seen.
|
||
|
|
deliver_frame(&node, &peer, &frames[2]).await.unwrap();
|
||
|
|
deliver_frame(&node, &peer, &frames[0]).await.unwrap();
|
||
|
|
deliver_frame(&node, &peer, &frames[1]).await.unwrap();
|
||
|
|
// A replay of an already-consumed frame, and a corrupted one: both are
|
||
|
|
// dropped inside `handle_incoming` without a chat row and without
|
||
|
|
// wedging the session.
|
||
|
|
deliver_frame(&node, &peer, &frames[0]).await.unwrap();
|
||
|
|
let mut corrupt = frames[1].clone();
|
||
|
|
let last = corrupt.len() - 1;
|
||
|
|
corrupt[last] ^= 0x01;
|
||
|
|
deliver_frame(&node, &peer, &corrupt).await.unwrap();
|
||
|
|
|
||
|
|
assert_eq!(
|
||
|
|
chat_lines(&node, &peer),
|
||
|
|
vec![
|
||
|
|
("in".to_string(), "m2".to_string()),
|
||
|
|
("in".to_string(), "m0".to_string()),
|
||
|
|
("in".to_string(), "m1".to_string())
|
||
|
|
],
|
||
|
|
"three lines, arrival order, no duplicates"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The peer takes the frame: one-shot payment sends are fail-closed, so the
|
||
|
|
/// tip path only reaches its chat rows when the deliverer answers `Ok`.
|
||
|
|
struct DialOk;
|
||
|
|
|
||
|
|
impl crate::outbox::Deliverer for DialOk {
|
||
|
|
fn deliver<'a>(
|
||
|
|
&'a self,
|
||
|
|
_onion: &'a str,
|
||
|
|
_pinned_id: &'a [u8],
|
||
|
|
_prekey: &'a [u8],
|
||
|
|
_payload: &'a [u8],
|
||
|
|
) -> crate::outbox::BoxFut<'a, Result<(), String>> {
|
||
|
|
Box::pin(async { Ok(()) })
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Same documented mainnet standard as `tests/wallet.rs`.
|
||
|
|
fn xmr_addr() -> String {
|
||
|
|
"4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge"
|
||
|
|
.to_string()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Serve a mock wallet RPC whose Digest state is **per connection**, the way
|
||
|
|
/// epee does it: the nonce is minted by the socket that answered 401 and is
|
||
|
|
/// valid nowhere else, so a client that retries on a fresh socket is refused
|
||
|
|
/// forever. `reply` maps a request to its JSON-RPC body. The socket closes
|
||
|
|
/// after an authenticated reply — the client asks for `Connection: close`
|
||
|
|
/// there and the real server honours it.
|
||
|
|
async fn serve_mock_rpc(
|
||
|
|
listener: tokio::net::TcpListener,
|
||
|
|
reply: Arc<dyn Fn(&str) -> String + Send + Sync>,
|
||
|
|
) {
|
||
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||
|
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||
|
|
|
||
|
|
static NEXT_NONCE: AtomicUsize = AtomicUsize::new(1);
|
||
|
|
|
||
|
|
while let Ok((mut sock, _)) = listener.accept().await {
|
||
|
|
let reply = Arc::clone(&reply);
|
||
|
|
tokio::spawn(async move {
|
||
|
|
let mut nonce: Option<String> = None;
|
||
|
|
loop {
|
||
|
|
let mut buf = vec![0u8; 8192];
|
||
|
|
let Ok(n) = sock.read(&mut buf).await else {
|
||
|
|
return;
|
||
|
|
};
|
||
|
|
if n == 0 {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
let req = String::from_utf8_lossy(&buf[..n]).to_string();
|
||
|
|
let answered = req.contains("Authorization:")
|
||
|
|
&& nonce.as_deref().is_some_and(|held| req.contains(held));
|
||
|
|
if !answered {
|
||
|
|
let fresh = format!("nonce{}", NEXT_NONCE.fetch_add(1, Ordering::Relaxed));
|
||
|
|
let challenge = format!(
|
||
|
|
"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"{fresh}\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\n\r\n"
|
||
|
|
);
|
||
|
|
if sock.write_all(challenge.as_bytes()).await.is_err() {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
nonce = Some(fresh);
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
let body = reply(&req);
|
||
|
|
let ok = format!(
|
||
|
|
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
|
||
|
|
body.len()
|
||
|
|
);
|
||
|
|
let _ = sock.write_all(ok.as_bytes()).await;
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A loopback wallet RPC that answers what the tip path actually asks for:
|
||
|
|
/// a digest challenge, then a synced `get_info` for the readiness gate and
|
||
|
|
/// `tx_hash` for the transfer. The old single-answer mock stopped covering
|
||
|
|
/// the path when `Wallet::transfer` started probing the chain tip first —
|
||
|
|
/// it answered `tx_hash` to `get_info` and every tip was refused as unsynced.
|
||
|
|
async fn mock_wallet() -> Wallet {
|
||
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||
|
|
.await
|
||
|
|
.expect("bind mock wallet");
|
||
|
|
let port = listener.local_addr().expect("mock wallet addr").port();
|
||
|
|
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(|req: &str| {
|
||
|
|
if req.contains("get_info") {
|
||
|
|
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"#
|
||
|
|
.to_string()
|
||
|
|
} else {
|
||
|
|
r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#.to_string()
|
||
|
|
}
|
||
|
|
});
|
||
|
|
tokio::spawn(serve_mock_rpc(listener, reply));
|
||
|
|
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
|
||
|
|
}
|
||
|
|
/// The payer of a tip must see it in their own chat: `receipt_chat_line` is
|
||
|
|
/// the recipient's view of the frame that arrived, `tip_chat_line` is what
|
||
|
|
/// the sender just spent.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn outbound_tip_appends_the_senders_own_tip_chat_line() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node_with_wallet(
|
||
|
|
&dir.path().join("bob"),
|
||
|
|
Arc::new(DialOk),
|
||
|
|
mock_wallet().await,
|
||
|
|
);
|
||
|
|
let peer = Keys::generate();
|
||
|
|
let addr = xmr_addr();
|
||
|
|
{
|
||
|
|
let store = node.store.lock().unwrap();
|
||
|
|
befriend(&store, &peer.identity_pk, &peer.prekey_pk, "peer.onion");
|
||
|
|
let prf = crate::profile::sign(&peer.identity_sk, "peer", "", &addr, 1)
|
||
|
|
.expect("sign peer profile");
|
||
|
|
assert!(store.apply_profile(&peer.identity_pk, &prf).unwrap());
|
||
|
|
}
|
||
|
|
|
||
|
|
node.tip(&peer.identity_pk, "500000000000", "lunch")
|
||
|
|
.await
|
||
|
|
.expect("tip");
|
||
|
|
|
||
|
|
assert_eq!(
|
||
|
|
chat_lines(&node, &peer),
|
||
|
|
vec![
|
||
|
|
("out".to_string(), "[receipt] 0.5 XMR".to_string()),
|
||
|
|
(
|
||
|
|
"out".to_string(),
|
||
|
|
"[tip] 0.5 XMR — lunch (pending)".to_string()
|
||
|
|
),
|
||
|
|
],
|
||
|
|
"the sender's chat must show the tip they just paid"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// F8: rotate the long-lived signed prekey. The identity must not move, the
|
||
|
|
/// stored/dialed prekey must, every prekey-bound ratchet epoch must be
|
||
|
|
/// dropped, and the F2 invite must be re-encodable around the new prekey.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn rotating_the_prekey_keeps_identity_and_drops_stale_ratchet_state() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||
|
|
let peer = Keys::generate();
|
||
|
|
let old_identity = node.identity_pk();
|
||
|
|
let old_prekey = node_prekey(&node);
|
||
|
|
*node.onion.lock().unwrap() = format!("{}.onion", "a".repeat(56));
|
||
|
|
{
|
||
|
|
let store = node.store.lock().unwrap();
|
||
|
|
befriend(&store, &peer.identity_pk, &peer.prekey_pk, "peer.onion");
|
||
|
|
store
|
||
|
|
.save_ratchet(&peer.identity_pk, b"epoch-bound-to-the-old-prekey")
|
||
|
|
.expect("seed ratchet state");
|
||
|
|
}
|
||
|
|
|
||
|
|
let new_prekey = node.rotate_prekey().expect("rotate prekey");
|
||
|
|
|
||
|
|
assert_ne!(new_prekey, old_prekey, "the prekey must actually change");
|
||
|
|
assert_eq!(node_prekey(&node), new_prekey, "the live keys follow");
|
||
|
|
assert_eq!(
|
||
|
|
node.identity_pk(),
|
||
|
|
old_identity,
|
||
|
|
"identity = pubkey, it stays"
|
||
|
|
);
|
||
|
|
{
|
||
|
|
let store = node.store.lock().unwrap();
|
||
|
|
assert_eq!(
|
||
|
|
store.self_identity().unwrap().prekey_pk,
|
||
|
|
new_prekey.to_vec(),
|
||
|
|
"the self row carries the new prekey"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
store.load_ratchet(&peer.identity_pk).unwrap().is_none(),
|
||
|
|
"the bootstrap epoch is prekey-bound, so the stored state is stale"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
let payload = qr::decode(&node.qr_payload().expect("re-encode the invite"))
|
||
|
|
.expect("the re-encoded invite decodes");
|
||
|
|
assert_eq!(payload.signed_prekey, new_prekey.to_vec());
|
||
|
|
assert_eq!(
|
||
|
|
payload.pubkey,
|
||
|
|
old_identity.to_vec(),
|
||
|
|
"the new invite still names the same identity"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// An outbound tip must be recorded as a *tip*. The receipt row is the
|
||
|
|
/// recipient's view of a receipt frame; for money the user just spent the
|
||
|
|
/// wallet history wants the tip they paid. `ingest_tip` already stores
|
||
|
|
/// `kind = "tip"` for the inbound direction.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn outbound_tip_records_a_tip_payment_row() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node_with_wallet(
|
||
|
|
&dir.path().join("bob"),
|
||
|
|
Arc::new(DialOk),
|
||
|
|
mock_wallet().await,
|
||
|
|
);
|
||
|
|
let peer = Keys::generate();
|
||
|
|
let addr = xmr_addr();
|
||
|
|
{
|
||
|
|
let store = node.store.lock().unwrap();
|
||
|
|
befriend(&store, &peer.identity_pk, &peer.prekey_pk, "peer.onion");
|
||
|
|
let prf = crate::profile::sign(&peer.identity_sk, "peer", "", &addr, 1)
|
||
|
|
.expect("sign peer profile");
|
||
|
|
assert!(store.apply_profile(&peer.identity_pk, &prf).unwrap());
|
||
|
|
}
|
||
|
|
|
||
|
|
node.tip(&peer.identity_pk, "500000000000", "lunch")
|
||
|
|
.await
|
||
|
|
.expect("tip");
|
||
|
|
|
||
|
|
let store = node.store.lock().unwrap();
|
||
|
|
let rows = store.list_payments(&peer.identity_pk).expect("payments");
|
||
|
|
assert_eq!(rows.len(), 1, "one row for one outbound tip");
|
||
|
|
assert_eq!(rows[0].dir, "out");
|
||
|
|
assert_eq!(rows[0].kind, "tip", "an outbound tip is stored as a tip");
|
||
|
|
assert_eq!(rows[0].amount_atomic, "500000000000");
|
||
|
|
assert_eq!(rows[0].txid.as_deref(), Some("abc123"));
|
||
|
|
assert_eq!(rows[0].memo, "lunch");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Same storage for the other direction: a tip signed by the peer lands as
|
||
|
|
/// a `kind = "tip"` row plus the `[tip]` line. This is the path the
|
||
|
|
/// payments CHECK constraint had been rejecting.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn an_inbound_tip_is_recorded_and_shown() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||
|
|
let peer = Keys::generate();
|
||
|
|
befriend(
|
||
|
|
&node.store.lock().unwrap(),
|
||
|
|
&peer.identity_pk,
|
||
|
|
&peer.prekey_pk,
|
||
|
|
"peer.onion",
|
||
|
|
);
|
||
|
|
let tip = pay::sign_tip(
|
||
|
|
&peer.identity_sk,
|
||
|
|
"abc123",
|
||
|
|
"500000000000",
|
||
|
|
&xmr_addr(),
|
||
|
|
"lunch",
|
||
|
|
1,
|
||
|
|
)
|
||
|
|
.expect("sign peer tip");
|
||
|
|
|
||
|
|
node.ingest_tip(&peer.identity_pk, &pay::encode_tip(&tip))
|
||
|
|
.await
|
||
|
|
.expect("inbound tip must be stored");
|
||
|
|
|
||
|
|
assert_eq!(
|
||
|
|
chat_lines(&node, &peer),
|
||
|
|
vec![(
|
||
|
|
"in".to_string(),
|
||
|
|
"[tip] 0.5 XMR — lunch (pending)".to_string()
|
||
|
|
)],
|
||
|
|
"the receiver's chat shows the tip that arrived"
|
||
|
|
);
|
||
|
|
let rows = node.store.lock().unwrap().list_payments(&peer.identity_pk);
|
||
|
|
let rows = rows.expect("payments");
|
||
|
|
assert_eq!(rows.len(), 1, "one row for one inbound tip");
|
||
|
|
assert_eq!(rows[0].dir, "in");
|
||
|
|
assert_eq!(rows[0].kind, "tip");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The peer payment history the TUI needs: `Store::list_payments` existed but
|
||
|
|
/// nothing on `Node` reached it, so the signed invoice/receipt frames a peer
|
||
|
|
/// sent were invisible to the app. One row per stored frame, oldest first,
|
||
|
|
/// and a friend with no rows is an empty vector, not an error.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn list_payments_round_trips_a_peers_invoice_and_receipt() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||
|
|
let peer = Keys::generate();
|
||
|
|
let stranger = Keys::generate();
|
||
|
|
let addr = xmr_addr();
|
||
|
|
befriend(
|
||
|
|
&node.store.lock().unwrap(),
|
||
|
|
&peer.identity_pk,
|
||
|
|
&peer.prekey_pk,
|
||
|
|
"peer.onion",
|
||
|
|
);
|
||
|
|
{
|
||
|
|
let store = node.store.lock().unwrap();
|
||
|
|
store
|
||
|
|
.insert_payment(
|
||
|
|
&peer.identity_pk,
|
||
|
|
PaymentWrite {
|
||
|
|
dir: "in",
|
||
|
|
kind: "invoice",
|
||
|
|
amount_atomic: "500000000000",
|
||
|
|
address: &addr,
|
||
|
|
memo: "rent",
|
||
|
|
txid: None,
|
||
|
|
verified: false,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
.expect("store inbound invoice");
|
||
|
|
store
|
||
|
|
.insert_payment(
|
||
|
|
&peer.identity_pk,
|
||
|
|
PaymentWrite {
|
||
|
|
dir: "in",
|
||
|
|
kind: "receipt",
|
||
|
|
amount_atomic: "250000000000",
|
||
|
|
address: &addr,
|
||
|
|
memo: "",
|
||
|
|
txid: Some("deadbeef"),
|
||
|
|
verified: false,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
.expect("store inbound receipt");
|
||
|
|
}
|
||
|
|
|
||
|
|
let rows = node.list_payments(&peer.identity_pk).expect("payments");
|
||
|
|
assert_eq!(rows.len(), 2, "one row per stored frame");
|
||
|
|
assert_eq!(rows[0].kind, "invoice", "oldest row first");
|
||
|
|
assert_eq!(rows[0].dir, "in");
|
||
|
|
assert_eq!(rows[0].amount_atomic, "500000000000");
|
||
|
|
assert_eq!(rows[0].memo, "rent");
|
||
|
|
assert_eq!(rows[1].kind, "receipt");
|
||
|
|
assert_eq!(rows[1].txid.as_deref(), Some("deadbeef"));
|
||
|
|
|
||
|
|
let none = node
|
||
|
|
.list_payments(&stranger.identity_pk)
|
||
|
|
.expect("a friend with no rows is an empty vector, not an error");
|
||
|
|
assert!(none.is_empty());
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A stand-in for `monero-wallet-rpc`: it records its argv, then does what
|
||
|
|
/// the test needs. The wallet child spawns a real process, so this is the
|
||
|
|
/// only honest way to drive the start path offline.
|
||
|
|
///
|
||
|
|
/// The argv is `mv`d into place in one step rather than truncated and
|
||
|
|
/// appended: a poller must never read half of it. It did — the port was
|
||
|
|
/// parsed while it was still being written, so `42765` read as `427`, and
|
||
|
|
/// the mock was bound on a port nothing dialled.
|
||
|
|
///
|
||
|
|
/// Every child also writes its own copy at `<log>.<pid>`, which no other
|
||
|
|
/// child can touch, and the shared copy lands first, so a pid-named file
|
||
|
|
/// implies the shared one is already complete. The shared path is what the
|
||
|
|
/// single-child tests read; a test that spans two children reads the
|
||
|
|
/// pid-named one, because a previous child's write into the shared path is
|
||
|
|
/// unsequenced against the test (see [`wait_for_child_rpc_port`]).
|
||
|
|
pub(crate) fn fake_child_bin(dir: &Path, name: &str, log: &Path, body: &str) -> PathBuf {
|
||
|
|
fake_child_bin_after(dir, name, log, "", body)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// [`fake_child_bin`] with `prelude` run *before* the argv is written: the
|
||
|
|
/// stand-in for a runner that schedules this child's exec late.
|
||
|
|
fn fake_child_bin_after(
|
||
|
|
dir: &Path,
|
||
|
|
name: &str,
|
||
|
|
log: &Path,
|
||
|
|
prelude: &str,
|
||
|
|
body: &str,
|
||
|
|
) -> PathBuf {
|
||
|
|
std::fs::create_dir_all(dir).expect("fake bin dir");
|
||
|
|
let path = dir.join(name);
|
||
|
|
let script = format!(
|
||
|
|
"#!/bin/sh\n{prelude}\ntmp='{log}'.$$.writing\n: > \"$tmp\"\nprintf '%s\\n' \"$0\" >> \"$tmp\"\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> \"$tmp\"; done\ncp -f \"$tmp\" '{log}'.$$.shared\nmv -f '{log}'.$$.shared '{log}'\nmv -f \"$tmp\" '{log}'.$$\n{body}\n",
|
||
|
|
prelude = prelude,
|
||
|
|
log = log.display(),
|
||
|
|
body = body
|
||
|
|
);
|
||
|
|
std::fs::write(&path, script).expect("write fake bin");
|
||
|
|
let mut perms = std::fs::metadata(&path).expect("stat").permissions();
|
||
|
|
std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o700);
|
||
|
|
std::fs::set_permissions(&path, perms).expect("chmod");
|
||
|
|
path
|
||
|
|
}
|
||
|
|
|
||
|
|
/// [`fake_child_bin`] with the shared log written *last*: this child's own
|
||
|
|
/// `<log>.<pid>` lands immediately and the path a harness that reads it
|
||
|
|
/// would take lags behind — a killed child's write landing after a clear
|
||
|
|
/// (CI run 905, job 1373).
|
||
|
|
fn fake_child_bin_shared_late(
|
||
|
|
dir: &Path,
|
||
|
|
name: &str,
|
||
|
|
log: &Path,
|
||
|
|
delay: &str,
|
||
|
|
body: &str,
|
||
|
|
) -> PathBuf {
|
||
|
|
std::fs::create_dir_all(dir).expect("fake bin dir");
|
||
|
|
let path = dir.join(name);
|
||
|
|
let script = format!(
|
||
|
|
"#!/bin/sh\ntmp='{log}'.$$.writing\n: > \"$tmp\"\nprintf '%s\\n' \"$0\" >> \"$tmp\"\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> \"$tmp\"; done\nmv -f \"$tmp\" '{log}'.$$\n{delay}\ncp -f '{log}'.$$ '{log}'.$$.shared\nmv -f '{log}'.$$.shared '{log}'\n{body}\n",
|
||
|
|
log = log.display(),
|
||
|
|
delay = delay,
|
||
|
|
body = body
|
||
|
|
);
|
||
|
|
std::fs::write(&path, script).expect("write fake bin");
|
||
|
|
let mut perms = std::fs::metadata(&path).expect("stat").permissions();
|
||
|
|
std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o700);
|
||
|
|
std::fs::set_permissions(&path, perms).expect("chmod");
|
||
|
|
path
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A loopback daemon is the one source that spawns no SOCKS child, so the
|
||
|
|
/// test drives exactly one process.
|
||
|
|
fn loopback_child_config(bin: PathBuf, filename: &str) -> ChildConfig {
|
||
|
|
ChildConfig {
|
||
|
|
source: ChainSource::Remote {
|
||
|
|
host: "127.0.0.1".into(),
|
||
|
|
port: 18081,
|
||
|
|
},
|
||
|
|
wallet_rpc_bin: bin,
|
||
|
|
arti_bin: PathBuf::from("arti"),
|
||
|
|
wallet_filename: filename.to_string(),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A loopback wallet RPC that answers the *status* probe: a digest
|
||
|
|
/// challenge, then `get_address` / `get_balance` / `get_info`, with the
|
||
|
|
/// chain numbers a syncing daemon reports. [`mock_wallet`] above answers the
|
||
|
|
/// *transfer* path; this one answers a refresh, which never transfers.
|
||
|
|
/// A loopback wallet RPC that answers the *status* probe: a digest
|
||
|
|
/// challenge, then `get_address` / `get_balance` / `get_info`, with the
|
||
|
|
/// chain numbers a syncing daemon reports. [`mock_wallet`] above answers the
|
||
|
|
/// *transfer* path; this one answers a refresh, which never transfers.
|
||
|
|
async fn mock_syncing_wallet(height: u64, target: u64) -> Wallet {
|
||
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||
|
|
.await
|
||
|
|
.expect("bind mock wallet");
|
||
|
|
let port = listener.local_addr().expect("mock wallet addr").port();
|
||
|
|
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(move |req: &str| {
|
||
|
|
if req.contains("get_info") {
|
||
|
|
format!(
|
||
|
|
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target},"synchronized":true}}}}"#
|
||
|
|
)
|
||
|
|
} else if req.contains("get_address") {
|
||
|
|
format!(
|
||
|
|
r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#,
|
||
|
|
addr = xmr_addr()
|
||
|
|
)
|
||
|
|
} else {
|
||
|
|
r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0"}}"#.to_string()
|
||
|
|
}
|
||
|
|
});
|
||
|
|
tokio::spawn(serve_mock_rpc(listener, reply));
|
||
|
|
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Point `node`'s wallet client at a mock. The child process stays whatever
|
||
|
|
/// `start_wallet_child` spawned; only the dial target moves.
|
||
|
|
pub(crate) fn test_install_wallet(node: &Node, wallet: Wallet) {
|
||
|
|
*node.wallet.lock().expect("wallet") = wallet;
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Like [`mock_syncing_wallet`], but `height` is read on every `get_info`,
|
||
|
|
/// so a later store is a later answer. `synchronized` stays false: the
|
||
|
|
/// status line is a syncing chain, not a caught-up one.
|
||
|
|
pub(crate) async fn mock_wallet_at(
|
||
|
|
height: std::sync::Arc<std::sync::atomic::AtomicU64>,
|
||
|
|
target: u64,
|
||
|
|
) -> Wallet {
|
||
|
|
use std::sync::atomic::Ordering;
|
||
|
|
|
||
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||
|
|
.await
|
||
|
|
.expect("bind mock wallet");
|
||
|
|
let port = listener.local_addr().expect("mock wallet addr").port();
|
||
|
|
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(move |req: &str| {
|
||
|
|
if req.contains("get_info") {
|
||
|
|
let h = height.load(Ordering::Relaxed);
|
||
|
|
format!(
|
||
|
|
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{h},"target_height":{target},"synchronized":false}}}}"#
|
||
|
|
)
|
||
|
|
} else if req.contains("get_address") {
|
||
|
|
r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4test"}}"#.to_string()
|
||
|
|
} else {
|
||
|
|
r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0"}}"#.to_string()
|
||
|
|
}
|
||
|
|
});
|
||
|
|
tokio::spawn(serve_mock_rpc(listener, reply));
|
||
|
|
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A loopback daemon that answers `get_info` on the port the child probes
|
||
|
|
/// when its wallet RPC is down. `None` when that port is already held (a real
|
||
|
|
/// `monerod` on this box): that daemon is not ours to replace, and the test
|
||
|
|
/// must not claim to have served the answer.
|
||
|
|
async fn mock_daemon_on_default_port(height: u64, target: u64) -> Option<()> {
|
||
|
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||
|
|
|
||
|
|
let listener =
|
||
|
|
tokio::net::TcpListener::bind(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}"))
|
||
|
|
.await
|
||
|
|
.ok()?;
|
||
|
|
tokio::spawn(async move {
|
||
|
|
for _ in 0..4 {
|
||
|
|
let Ok((mut sock, _)) = listener.accept().await else {
|
||
|
|
return;
|
||
|
|
};
|
||
|
|
let mut buf = vec![0u8; 4096];
|
||
|
|
let _ = sock.read(&mut buf).await;
|
||
|
|
let body = format!(
|
||
|
|
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target}}}}}"#
|
||
|
|
);
|
||
|
|
let _ = sock
|
||
|
|
.write_all(
|
||
|
|
format!(
|
||
|
|
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||
|
|
body.len()
|
||
|
|
)
|
||
|
|
.as_bytes(),
|
||
|
|
)
|
||
|
|
.await;
|
||
|
|
}
|
||
|
|
});
|
||
|
|
Some(())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The status row carries the real chain numbers: a wallet RPC that answers
|
||
|
|
/// `get_info` fills height and target, and the one-liner shows them. A
|
||
|
|
/// daemon that reports no target is not a caught-up chain — `h/0` with no
|
||
|
|
/// invented percentage.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn a_wallet_that_answers_get_info_fills_the_chain_progress() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
|
||
|
|
let log = dir.path().join("argv.log");
|
||
|
|
let bin = fake_child_bin(
|
||
|
|
&dir.path().join("fake-bins"),
|
||
|
|
"monero-wallet-rpc",
|
||
|
|
&log,
|
||
|
|
"sleep 30",
|
||
|
|
);
|
||
|
|
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire"))
|
||
|
|
.expect("set config");
|
||
|
|
// The gate dials the port the fake was told to bind; a shell fake cannot
|
||
|
|
// bind one, so hold it here.
|
||
|
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
|
||
|
|
node.start_wallet_child().expect("start");
|
||
|
|
// The child is a fake process; the wallet the node actually talks to is
|
||
|
|
// the mock RPC, which is where the numbers come from.
|
||
|
|
*node.wallet.lock().unwrap() = mock_syncing_wallet(4549, 0).await;
|
||
|
|
|
||
|
|
let status = node.wallet_child_refresh().await;
|
||
|
|
assert_eq!(status.state, WalletChildState::Ready, "{status:?}");
|
||
|
|
assert_eq!(status.height, 4549, "{status:?}");
|
||
|
|
assert_eq!(status.target_height, 0, "{status:?}");
|
||
|
|
assert!(status.line().contains("sync 4549/0"), "{}", status.line());
|
||
|
|
assert!(!status.line().contains('%'), "{}", status.line());
|
||
|
|
|
||
|
|
node.stop_wallet_child().expect("stop");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Holds [`crate::wallet_child::test_support::unrestricted_port_lock`] on a
|
||
|
|
/// thread of its own. The guard is not `Send`, and this test awaits, so the
|
||
|
|
/// async fn must not hold it (`clippy::await_holding_lock`).
|
||
|
|
#[cfg(feature = "cuprate-daemon")]
|
||
|
|
struct UnrestrictedPortHold {
|
||
|
|
tx: Option<std::sync::mpsc::Sender<()>>,
|
||
|
|
handle: Option<std::thread::JoinHandle<()>>,
|
||
|
|
}
|
||
|
|
|
||
|
|
#[cfg(feature = "cuprate-daemon")]
|
||
|
|
impl UnrestrictedPortHold {
|
||
|
|
fn new() -> Self {
|
||
|
|
let (ready_tx, ready_rx) = std::sync::mpsc::channel();
|
||
|
|
let (tx, rx) = std::sync::mpsc::channel();
|
||
|
|
let handle = std::thread::spawn(move || {
|
||
|
|
let _guard = crate::wallet_child::test_support::unrestricted_port_lock();
|
||
|
|
let _ = ready_tx.send(());
|
||
|
|
let _ = rx.recv();
|
||
|
|
});
|
||
|
|
ready_rx
|
||
|
|
.recv()
|
||
|
|
.expect("the port lock thread must answer before the test binds");
|
||
|
|
Self {
|
||
|
|
tx: Some(tx),
|
||
|
|
handle: Some(handle),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
#[cfg(feature = "cuprate-daemon")]
|
||
|
|
impl Drop for UnrestrictedPortHold {
|
||
|
|
fn drop(&mut self) {
|
||
|
|
drop(self.tx.take());
|
||
|
|
if let Some(handle) = self.handle.take() {
|
||
|
|
let _ = handle.join();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The case the user hit: the wallet RPC is refused (`os error 111`) while
|
||
|
|
/// the chain source is this box's own daemon. The status still shows the
|
||
|
|
/// chain's height and target — asked of the daemon directly — and the state
|
||
|
|
/// stays `connecting`, because the *wallet* is what did not answer.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn a_refused_wallet_rpc_falls_back_to_the_local_daemons_own_height() {
|
||
|
|
// The in-process launch tests bind this same port. Hold it for the
|
||
|
|
// whole test so a default build (feature on) does not race them.
|
||
|
|
#[cfg(feature = "cuprate-daemon")]
|
||
|
|
let _port = UnrestrictedPortHold::new();
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let home = dir.path().join("child");
|
||
|
|
let Some(()) = mock_daemon_on_default_port(1160, 3_090_939).await else {
|
||
|
|
eprintln!(
|
||
|
|
"skipping: 127.0.0.1:{DEFAULT_MONEROD_RPC_PORT} is already held by something else"
|
||
|
|
);
|
||
|
|
return;
|
||
|
|
};
|
||
|
|
let node = offline_node(&home, Arc::new(NoDial));
|
||
|
|
let monerod = fake_child_bin(
|
||
|
|
&dir.path().join("fake-bins"),
|
||
|
|
"monerod",
|
||
|
|
&dir.path().join("monerod.argv"),
|
||
|
|
"sleep 30",
|
||
|
|
);
|
||
|
|
let rpc = fake_child_bin(
|
||
|
|
&dir.path().join("fake-bins"),
|
||
|
|
"monero-wallet-rpc",
|
||
|
|
&dir.path().join("rpc.argv"),
|
||
|
|
"sleep 30",
|
||
|
|
);
|
||
|
|
node.set_wallet_child_config(&ChildConfig {
|
||
|
|
source: ChainSource::Local {
|
||
|
|
monerod_bin: monerod,
|
||
|
|
datadir: dir.path().join("chain"),
|
||
|
|
prune: true,
|
||
|
|
},
|
||
|
|
wallet_rpc_bin: rpc,
|
||
|
|
arti_bin: PathBuf::from("arti"),
|
||
|
|
wallet_filename: "onionwire".to_string(),
|
||
|
|
})
|
||
|
|
.expect("set config");
|
||
|
|
// The gate dials the port the fake was told to bind; a shell fake cannot
|
||
|
|
// bind one, so hold the port it publishes.
|
||
|
|
let _hold = PublishedPortHold::watching(&[dir.path().join("rpc.argv")]);
|
||
|
|
node.start_wallet_child().expect("start");
|
||
|
|
|
||
|
|
let status = node.wallet_child_refresh().await;
|
||
|
|
assert_eq!(status.state, WalletChildState::Connecting, "{status:?}");
|
||
|
|
assert_eq!(status.height, 1160, "{status:?}");
|
||
|
|
assert_eq!(status.target_height, 3_090_939, "{status:?}");
|
||
|
|
assert!(
|
||
|
|
status.line().contains("sync 1160/3090939"),
|
||
|
|
"{}",
|
||
|
|
status.line()
|
||
|
|
);
|
||
|
|
|
||
|
|
node.stop_wallet_child().expect("stop");
|
||
|
|
}
|
||
|
|
|
||
|
|
fn sealed_creds(node: &Node) -> (String, String) {
|
||
|
|
let raw = node
|
||
|
|
.store
|
||
|
|
.lock()
|
||
|
|
.expect("store")
|
||
|
|
.load_wallet_child()
|
||
|
|
.expect("record")
|
||
|
|
.expect("a start seals the creds");
|
||
|
|
let parsed: serde_json::Value = serde_json::from_str(&raw).expect("json");
|
||
|
|
(
|
||
|
|
parsed["user"].as_str().expect("user").to_string(),
|
||
|
|
parsed["pass"].as_str().expect("pass").to_string(),
|
||
|
|
)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A receive-only node says `off` and starts nothing: the status comes from
|
||
|
|
/// the real configuration, never from a guess or an env var.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn a_receive_only_node_reports_off_and_refuses_to_start_a_child() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
|
||
|
|
let status = node.wallet_child_status();
|
||
|
|
assert_eq!(status.state, WalletChildState::Off);
|
||
|
|
assert!(!status.running);
|
||
|
|
assert!(!status.configured);
|
||
|
|
assert_eq!(status.chain_source, "receive-only");
|
||
|
|
assert!(status.last_error.is_none());
|
||
|
|
assert_eq!(
|
||
|
|
node.wallet_child_line(),
|
||
|
|
"",
|
||
|
|
"an unconfigured install renders no status row"
|
||
|
|
);
|
||
|
|
let err = node
|
||
|
|
.start_wallet_child()
|
||
|
|
.expect_err("receive-only cannot start anything");
|
||
|
|
assert!(err.contains("no chain source configured"), "{err}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The call the TUI makes. A direct `CuprateNode::launch` does not prove
|
||
|
|
/// `start_wallet_child` pointed the wallet child at that node.
|
||
|
|
///
|
||
|
|
/// Testnet, no peers: RPC answers at genesis. Not a sync.
|
||
|
|
#[cfg(feature = "cuprate-daemon")]
|
||
|
|
#[test]
|
||
|
|
fn start_wallet_child_in_process_cuprate_answers_get_info() {
|
||
|
|
let _port = crate::wallet_child::test_support::unrestricted_port_lock();
|
||
|
|
let rt = tokio::runtime::Builder::new_current_thread()
|
||
|
|
.enable_all()
|
||
|
|
.build()
|
||
|
|
.expect("runtime");
|
||
|
|
rt.block_on(start_wallet_child_in_process_cuprate_answers_get_info_inner());
|
||
|
|
}
|
||
|
|
|
||
|
|
#[cfg(feature = "cuprate-daemon")]
|
||
|
|
async fn start_wallet_child_in_process_cuprate_answers_get_info_inner() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let home = dir.path().join("child");
|
||
|
|
let node = offline_node(&home, Arc::new(NoDial));
|
||
|
|
let log = dir.path().join("wallet-rpc.argv");
|
||
|
|
let bin = fake_child_bin(
|
||
|
|
&dir.path().join("fake-bins"),
|
||
|
|
"monero-wallet-rpc",
|
||
|
|
&log,
|
||
|
|
"sleep 60",
|
||
|
|
);
|
||
|
|
node.set_in_process_cuprate(ChainNetwork::Testnet, false)
|
||
|
|
.expect("store an in-process testnet source");
|
||
|
|
let mut cfg = node.wallet_child_config();
|
||
|
|
let ChainSource::InProcessCuprate {
|
||
|
|
datadir,
|
||
|
|
network,
|
||
|
|
prune,
|
||
|
|
} = &cfg.source
|
||
|
|
else {
|
||
|
|
panic!("stored source is not in-process: {:?}", cfg.source);
|
||
|
|
};
|
||
|
|
assert_eq!(*network, ChainNetwork::Testnet);
|
||
|
|
assert!(!prune);
|
||
|
|
assert!(
|
||
|
|
datadir.starts_with(&home),
|
||
|
|
"datadir must live under the wallet home: {}",
|
||
|
|
datadir.display()
|
||
|
|
);
|
||
|
|
let datadir = datadir.clone();
|
||
|
|
cfg.wallet_rpc_bin = bin;
|
||
|
|
node.set_wallet_child_config(&cfg)
|
||
|
|
.expect("point the child at the fake wallet rpc");
|
||
|
|
assert!(
|
||
|
|
WalletChild::chain_copy(&node.wallet_child_config().source)
|
||
|
|
.contains(crate::cuprate::TESTNET_ONLY),
|
||
|
|
"an in-process status line must keep the testnet caveat"
|
||
|
|
);
|
||
|
|
|
||
|
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
|
||
|
|
node.start_wallet_child()
|
||
|
|
.expect("the TUI start path launches the in-process daemon");
|
||
|
|
|
||
|
|
let addr = format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}");
|
||
|
|
let mut argv = String::new();
|
||
|
|
for _ in 0..200 {
|
||
|
|
argv = std::fs::read_to_string(&log).unwrap_or_default();
|
||
|
|
if argv.contains("--daemon-address") {
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
||
|
|
}
|
||
|
|
let lines: Vec<&str> = argv.lines().collect();
|
||
|
|
assert!(
|
||
|
|
lines
|
||
|
|
.windows(2)
|
||
|
|
.any(|w| w == ["--daemon-address", addr.as_str()]),
|
||
|
|
"the wallet child must be pointed at the in-process RPC, got {argv}"
|
||
|
|
);
|
||
|
|
|
||
|
|
let budget = Duration::from_secs(5);
|
||
|
|
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(Duration::from_millis(250)).await;
|
||
|
|
}
|
||
|
|
let info = info.expect("the unrestricted RPC the child points at never answered get_info");
|
||
|
|
assert!(info.height >= 1, "genesis is height 1: {info:?}");
|
||
|
|
assert_eq!(
|
||
|
|
info.target_height, 0,
|
||
|
|
"a testnet node with no peers reports no target: {info:?}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
datadir.join("testnet").join("fjall").is_dir(),
|
||
|
|
"the chain store must live under the wallet home: {}",
|
||
|
|
datadir.display()
|
||
|
|
);
|
||
|
|
|
||
|
|
node.stop_wallet_child().expect("stop");
|
||
|
|
let mut closed = false;
|
||
|
|
for _ in 0..40 {
|
||
|
|
if tokio::net::TcpStream::connect(&addr).await.is_err() {
|
||
|
|
closed = true;
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
tokio::time::sleep(Duration::from_millis(250)).await;
|
||
|
|
}
|
||
|
|
assert!(
|
||
|
|
closed,
|
||
|
|
"the unrestricted RPC was still accepting after stop_wallet_child"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Same call, feature off: the refusal names the feature and spawns nothing.
|
||
|
|
#[cfg(not(feature = "cuprate-daemon"))]
|
||
|
|
#[tokio::test]
|
||
|
|
async fn start_wallet_child_without_the_feature_returns_no_feature_msg() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let home = dir.path().join("child");
|
||
|
|
let node = offline_node(&home, Arc::new(NoDial));
|
||
|
|
let log = dir.path().join("wallet-rpc.argv");
|
||
|
|
let bin = fake_child_bin(
|
||
|
|
&dir.path().join("fake-bins"),
|
||
|
|
"monero-wallet-rpc",
|
||
|
|
&log,
|
||
|
|
"sleep 30",
|
||
|
|
);
|
||
|
|
node.set_in_process_cuprate(ChainNetwork::Testnet, false)
|
||
|
|
.expect("store an in-process source");
|
||
|
|
let mut cfg = node.wallet_child_config();
|
||
|
|
cfg.wallet_rpc_bin = bin;
|
||
|
|
node.set_wallet_child_config(&cfg).expect("set bin");
|
||
|
|
|
||
|
|
let err = node
|
||
|
|
.start_wallet_child()
|
||
|
|
.expect_err("a build without the feature must not start a daemon");
|
||
|
|
assert!(err.contains(crate::cuprate::NO_FEATURE_MSG), "{err}");
|
||
|
|
assert!(
|
||
|
|
!log.exists(),
|
||
|
|
"the wallet RPC must not be spawned against a daemon that never started"
|
||
|
|
);
|
||
|
|
assert!(!node.wallet_child_status().running, "{err}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The start path honours `with_wallet_rpc_bin` — the configured absolute
|
||
|
|
/// path is what gets spawned, not a name off `PATH` — and the status tracks
|
||
|
|
/// the real process.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn start_wallet_child_honours_the_configured_binary() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let home = dir.path().join("child");
|
||
|
|
let node = offline_node(&home, Arc::new(NoDial));
|
||
|
|
let log = dir.path().join("argv.log");
|
||
|
|
let bin = fake_child_bin(
|
||
|
|
&dir.path().join("fake-bins"),
|
||
|
|
"monero-wallet-rpc",
|
||
|
|
&log,
|
||
|
|
"sleep 30",
|
||
|
|
);
|
||
|
|
node.set_wallet_child_config(&loopback_child_config(bin.clone(), "onionwire"))
|
||
|
|
.expect("set config");
|
||
|
|
|
||
|
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
|
||
|
|
node.start_wallet_child().expect("start");
|
||
|
|
let status = node.wallet_child_status();
|
||
|
|
assert!(status.running, "{status:?}");
|
||
|
|
assert_eq!(
|
||
|
|
status.state,
|
||
|
|
WalletChildState::Connecting,
|
||
|
|
"nothing has answered the wallet RPC yet"
|
||
|
|
);
|
||
|
|
assert!(status.configured);
|
||
|
|
assert_eq!(status.chain_source, "remote daemon");
|
||
|
|
|
||
|
|
let mut argv: Vec<String> = Vec::new();
|
||
|
|
for _ in 0..200 {
|
||
|
|
argv = std::fs::read_to_string(&log)
|
||
|
|
.unwrap_or_default()
|
||
|
|
.lines()
|
||
|
|
.map(str::to_string)
|
||
|
|
.collect();
|
||
|
|
if !argv.is_empty() {
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
||
|
|
}
|
||
|
|
assert_eq!(
|
||
|
|
argv.first().map(String::as_str),
|
||
|
|
bin.to_str(),
|
||
|
|
"the configured binary ($0) is what got spawned: {argv:?}"
|
||
|
|
);
|
||
|
|
assert!(argv.iter().any(|a| a == "--wallet-dir"), "{argv:?}");
|
||
|
|
assert!(
|
||
|
|
argv.iter()
|
||
|
|
.any(|a| a == &home.join("wallet").display().to_string()),
|
||
|
|
"{argv:?}"
|
||
|
|
);
|
||
|
|
assert!(argv.iter().any(|a| a == "--daemon-address"), "{argv:?}");
|
||
|
|
assert!(
|
||
|
|
!argv.iter().any(|a| a == "--trusted-daemon"),
|
||
|
|
"a remote daemon is never trusted: {argv:?}"
|
||
|
|
);
|
||
|
|
|
||
|
|
// Idempotent: a live child is reported, not respawned.
|
||
|
|
node.start_wallet_child().expect("second start");
|
||
|
|
assert!(node.wallet_child_status().running);
|
||
|
|
|
||
|
|
node.stop_wallet_child().expect("stop");
|
||
|
|
let after = node.wallet_child_status();
|
||
|
|
assert_eq!(after.state, WalletChildState::Off);
|
||
|
|
assert!(!after.running, "stop must not leave a process behind");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A child that dies on its own is `exited` — never `ready` — and stopping
|
||
|
|
/// after that is still a clean no-op.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn a_died_child_reports_exited_and_never_ready() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
|
||
|
|
let log = dir.path().join("argv.log");
|
||
|
|
let bin = fake_child_bin(
|
||
|
|
&dir.path().join("fake-bins"),
|
||
|
|
"monero-wallet-rpc",
|
||
|
|
&log,
|
||
|
|
"exit 0",
|
||
|
|
);
|
||
|
|
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire"))
|
||
|
|
.expect("set config");
|
||
|
|
|
||
|
|
// The fake exits instead of binding its port; the gate must still see
|
||
|
|
// the accept the real child would have offered before it died.
|
||
|
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
|
||
|
|
node.start_wallet_child().expect("start");
|
||
|
|
let mut status = node.wallet_child_status();
|
||
|
|
for _ in 0..300 {
|
||
|
|
status = node.wallet_child_status();
|
||
|
|
if status.state == WalletChildState::Exited {
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
||
|
|
}
|
||
|
|
assert_eq!(status.state, WalletChildState::Exited, "{status:?}");
|
||
|
|
assert!(!status.running);
|
||
|
|
assert_ne!(status.state.as_str(), "ready");
|
||
|
|
node.stop_wallet_child()
|
||
|
|
.expect("stop is a no-op after an exit");
|
||
|
|
assert_eq!(node.wallet_child_status().state, WalletChildState::Off);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The settings live in the sealed store, so they survive a restart, and
|
||
|
|
/// re-saving them does not clobber the RPC creds a start already sealed.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn chain_source_persists_and_keeps_the_sealed_creds() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let home = dir.path().join("child");
|
||
|
|
let log = dir.path().join("argv.log");
|
||
|
|
let bin = fake_child_bin(
|
||
|
|
&dir.path().join("fake-bins"),
|
||
|
|
"monero-wallet-rpc",
|
||
|
|
&log,
|
||
|
|
"sleep 30",
|
||
|
|
);
|
||
|
|
let saved = loopback_child_config(bin.clone(), "onionwire");
|
||
|
|
{
|
||
|
|
let node = offline_node(&home, Arc::new(NoDial));
|
||
|
|
node.set_wallet_child_config(&saved).expect("set config");
|
||
|
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
|
||
|
|
node.start_wallet_child().expect("start");
|
||
|
|
let before = sealed_creds(&node);
|
||
|
|
|
||
|
|
let mut other = saved.clone();
|
||
|
|
other.source = ChainSource::Remote {
|
||
|
|
host: "127.0.0.1".into(),
|
||
|
|
port: 18089,
|
||
|
|
};
|
||
|
|
node.set_wallet_child_config(&other).expect("re-save");
|
||
|
|
assert_eq!(sealed_creds(&node), before, "creds survived the rewrite");
|
||
|
|
node.stop_wallet_child().expect("stop");
|
||
|
|
}
|
||
|
|
|
||
|
|
let node = offline_node(&home, Arc::new(NoDial));
|
||
|
|
assert_eq!(
|
||
|
|
node.wallet_child_config(),
|
||
|
|
ChildConfig {
|
||
|
|
source: ChainSource::Remote {
|
||
|
|
host: "127.0.0.1".into(),
|
||
|
|
port: 18089,
|
||
|
|
},
|
||
|
|
..saved
|
||
|
|
},
|
||
|
|
"the saved source outlives the process"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A binary that cannot be spawned is an error and leaves no half-started
|
||
|
|
/// child behind.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn a_missing_binary_fails_the_start_and_leaves_no_child() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
|
||
|
|
node.set_wallet_child_config(&loopback_child_config(
|
||
|
|
PathBuf::from("/nonexistent/onionwire-wallet-rpc"),
|
||
|
|
"onionwire",
|
||
|
|
))
|
||
|
|
.expect("set config");
|
||
|
|
let err = node
|
||
|
|
.start_wallet_child()
|
||
|
|
.expect_err("a missing binary fails");
|
||
|
|
assert!(err.contains("spawn"), "{err}");
|
||
|
|
let status = node.wallet_child_status();
|
||
|
|
assert_eq!(status.state, WalletChildState::Off);
|
||
|
|
assert!(!status.running);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A rejected setting is rejected before it is written: the stored config is
|
||
|
|
/// unchanged, so a bad form never points the child at nothing.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn a_rejected_chain_source_is_not_persisted() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
|
||
|
|
let bin = dir.path().join("fake-bins").join("monero-wallet-rpc");
|
||
|
|
let saved = loopback_child_config(bin.clone(), "onionwire");
|
||
|
|
node.set_wallet_child_config(&saved).expect("set config");
|
||
|
|
|
||
|
|
let mut no_host = saved.clone();
|
||
|
|
no_host.source = ChainSource::Remote {
|
||
|
|
host: " ".into(),
|
||
|
|
port: 18081,
|
||
|
|
};
|
||
|
|
let err = node
|
||
|
|
.set_wallet_child_config(&no_host)
|
||
|
|
.expect_err("an empty host is rejected");
|
||
|
|
assert!(err.contains("daemon host required"), "{err}");
|
||
|
|
assert_eq!(
|
||
|
|
node.wallet_child_config(),
|
||
|
|
saved,
|
||
|
|
"the stored config is intact"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The F7 screen's three chain-source choices each round-trip through the
|
||
|
|
/// sealed record, and `receive-only` is the way back to zero.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn the_setup_screen_persists_each_chain_source() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let home = dir.path().join("child");
|
||
|
|
let node = offline_node(&home, Arc::new(NoDial));
|
||
|
|
assert_eq!(
|
||
|
|
node.wallet_child_config().source,
|
||
|
|
ChainSource::None,
|
||
|
|
"a fresh install is receive-only"
|
||
|
|
);
|
||
|
|
|
||
|
|
node.set_remote_daemon("127.0.0.1", 18089)
|
||
|
|
.expect("remote daemon");
|
||
|
|
let remote = node.wallet_child_config();
|
||
|
|
assert_eq!(
|
||
|
|
remote.source,
|
||
|
|
ChainSource::Remote {
|
||
|
|
host: "127.0.0.1".into(),
|
||
|
|
port: 18089,
|
||
|
|
}
|
||
|
|
);
|
||
|
|
assert!(!remote.source.is_onion());
|
||
|
|
assert_eq!(
|
||
|
|
remote.wallet_rpc_bin,
|
||
|
|
PathBuf::from("monero-wallet-rpc"),
|
||
|
|
"an empty binary is filled in, like the in-process source"
|
||
|
|
);
|
||
|
|
|
||
|
|
node.set_remote_daemon("peer.onion", 18089)
|
||
|
|
.expect("onion daemon");
|
||
|
|
assert!(
|
||
|
|
node.wallet_child_config().source.is_onion(),
|
||
|
|
"a .onion host is the source's own SOCKS case, not a special one"
|
||
|
|
);
|
||
|
|
|
||
|
|
node.set_local_monerod(Path::new("/opt/monerod"), true)
|
||
|
|
.expect("local node");
|
||
|
|
assert_eq!(
|
||
|
|
node.wallet_child_config().source,
|
||
|
|
ChainSource::Local {
|
||
|
|
monerod_bin: PathBuf::from("/opt/monerod"),
|
||
|
|
datadir: home.join("chain").join("mainnet-pruned"),
|
||
|
|
prune: true,
|
||
|
|
}
|
||
|
|
);
|
||
|
|
|
||
|
|
node.set_receive_only().expect("receive-only");
|
||
|
|
assert_eq!(node.wallet_child_config().source, ChainSource::None);
|
||
|
|
|
||
|
|
// The last write is what a restart sees.
|
||
|
|
node.set_local_monerod(Path::new("/opt/monerod"), false)
|
||
|
|
.expect("local node");
|
||
|
|
drop(node);
|
||
|
|
let node = offline_node(&home, Arc::new(NoDial));
|
||
|
|
assert_eq!(
|
||
|
|
node.wallet_child_config().source,
|
||
|
|
ChainSource::Local {
|
||
|
|
monerod_bin: PathBuf::from("/opt/monerod"),
|
||
|
|
datadir: home.join("chain").join("mainnet-full"),
|
||
|
|
prune: false,
|
||
|
|
},
|
||
|
|
"the source outlives the process"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A chain source the user typed wrong is rejected before it is written, so
|
||
|
|
/// a bad form never points the child at nothing.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn a_rejected_setup_chain_source_is_not_persisted() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
|
||
|
|
node.set_remote_daemon("127.0.0.1", 18089)
|
||
|
|
.expect("remote daemon");
|
||
|
|
let saved = node.wallet_child_config();
|
||
|
|
|
||
|
|
let err = node
|
||
|
|
.set_remote_daemon(" ", 18089)
|
||
|
|
.expect_err("an empty host is refused");
|
||
|
|
assert!(err.contains("daemon host required"), "{err}");
|
||
|
|
let err = node
|
||
|
|
.set_remote_daemon("127.0.0.1", 0)
|
||
|
|
.expect_err("port 0 is refused");
|
||
|
|
assert!(err.contains("daemon port required"), "{err}");
|
||
|
|
let err = node
|
||
|
|
.set_local_monerod(Path::new(""), false)
|
||
|
|
.expect_err("an empty binary path is refused");
|
||
|
|
assert!(err.contains("monerod path required"), "{err}");
|
||
|
|
assert_eq!(
|
||
|
|
node.wallet_child_config(),
|
||
|
|
saved,
|
||
|
|
"a rejected source leaves the stored one alone"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The F7 screen's save round-trips through the sealed record, and a save
|
||
|
|
/// can never lock the wallet out of itself: the file passphrase the screen
|
||
|
|
/// does not carry is preserved.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn a_screen_save_round_trips_and_keeps_the_wallet_passphrase() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
|
||
|
|
assert!(
|
||
|
|
node.wallet_config().is_none(),
|
||
|
|
"a fresh install has stored nothing"
|
||
|
|
);
|
||
|
|
|
||
|
|
node.wallet_save_config(&WalletConfig::new(
|
||
|
|
"http://127.0.0.1:18083/json_rpc",
|
||
|
|
"ow:hunter2",
|
||
|
|
false,
|
||
|
|
))
|
||
|
|
.expect("save");
|
||
|
|
let read = node.wallet_config().expect("the save is readable");
|
||
|
|
assert_eq!(read.rpc_url, "http://127.0.0.1:18083/json_rpc");
|
||
|
|
assert_eq!(read.rpc_login.as_str(), "ow:hunter2");
|
||
|
|
assert!(!read.no_spend);
|
||
|
|
assert_eq!(read.wallet_passphrase.as_str(), "");
|
||
|
|
assert!(
|
||
|
|
node.wallet_status().configured(),
|
||
|
|
"the live snapshot follows the save"
|
||
|
|
);
|
||
|
|
|
||
|
|
// The file passphrase is sealed by the open path, not by this screen.
|
||
|
|
node.seal_wallet_passphrase("wallet-file-pass")
|
||
|
|
.expect("seal");
|
||
|
|
assert_eq!(
|
||
|
|
node.wallet_config().expect("stored").wallet_passphrase.as_str(),
|
||
|
|
"wallet-file-pass"
|
||
|
|
);
|
||
|
|
|
||
|
|
// A screen save (which never holds the file passphrase) keeps the stored
|
||
|
|
// one instead of blanking it — a save can never lock the wallet out of
|
||
|
|
// itself. A passphrase a caller hands `wallet_save_config` is ignored
|
||
|
|
// for the same reason: the file's passphrase is not the screen's.
|
||
|
|
let mut screen_save =
|
||
|
|
WalletConfig::new("http://127.0.0.1:18083/json_rpc", "ow:hunter2", true);
|
||
|
|
screen_save.wallet_passphrase = Zeroizing::new("not-the-files".to_string());
|
||
|
|
node.wallet_save_config(&screen_save).expect("resave");
|
||
|
|
let read = node.wallet_config().expect("the resave is readable");
|
||
|
|
assert!(read.no_spend, "the view-only toggle reached the store");
|
||
|
|
assert_eq!(read.wallet_passphrase.as_str(), "wallet-file-pass");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A rejected form leaves the stored config exactly as it was. The node is
|
||
|
|
/// the validator — the screen does not reimplement it.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn a_rejected_wallet_config_is_not_persisted() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
|
||
|
|
node.wallet_save_config(&WalletConfig::new(
|
||
|
|
"http://127.0.0.1:18083/json_rpc",
|
||
|
|
"ow:hunter2",
|
||
|
|
false,
|
||
|
|
))
|
||
|
|
.expect("save");
|
||
|
|
let before = node.wallet_config().expect("stored");
|
||
|
|
|
||
|
|
for bad in [
|
||
|
|
WalletConfig::new("", "ow:hunter2", false),
|
||
|
|
WalletConfig::new("http://192.0.2.10:18083/json_rpc", "ow:hunter2", false),
|
||
|
|
WalletConfig::new("http://127.0.0.1:18083/json_rpc", "", false),
|
||
|
|
] {
|
||
|
|
let err = node
|
||
|
|
.wallet_save_config(&bad)
|
||
|
|
.expect_err("a bad form is refused");
|
||
|
|
assert!(!err.is_empty());
|
||
|
|
assert_eq!(
|
||
|
|
node.wallet_config().expect("stored"),
|
||
|
|
before,
|
||
|
|
"the stored config is intact"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// `shutdown` stops the processes the app owns: an exit must not orphan a
|
||
|
|
/// spend-capable wallet RPC behind a loopback socket.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn shutdown_stops_the_wallet_child() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
|
||
|
|
let log = dir.path().join("argv.log");
|
||
|
|
let pid_file = dir.path().join("child.pid");
|
||
|
|
let bin = fake_child_bin(
|
||
|
|
&dir.path().join("fake-bins"),
|
||
|
|
"monero-wallet-rpc",
|
||
|
|
&log,
|
||
|
|
&format!("echo $$ > '{}'; exec sleep 30", pid_file.display()),
|
||
|
|
);
|
||
|
|
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire"))
|
||
|
|
.expect("set config");
|
||
|
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
|
||
|
|
node.start_wallet_child().expect("start");
|
||
|
|
|
||
|
|
let mut pid = 0u32;
|
||
|
|
for _ in 0..200 {
|
||
|
|
if let Ok(raw) = std::fs::read_to_string(&pid_file)
|
||
|
|
&& let Ok(parsed) = raw.trim().parse::<u32>()
|
||
|
|
{
|
||
|
|
pid = parsed;
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
||
|
|
}
|
||
|
|
assert!(pid > 0, "the fake child recorded its pid");
|
||
|
|
|
||
|
|
node.shutdown().await.expect("shutdown");
|
||
|
|
let mut gone = false;
|
||
|
|
for _ in 0..300 {
|
||
|
|
if !Path::new(&format!("/proc/{pid}")).exists() {
|
||
|
|
gone = true;
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
||
|
|
}
|
||
|
|
assert!(gone, "shutdown must not leave the wallet child behind");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A loopback wallet RPC for the setup path: a per-socket digest challenge,
|
||
|
|
/// then the method's own result. `create_wallet` and
|
||
|
|
/// `restore_deterministic_wallet` both answer `{}`; only the seed backup
|
||
|
|
/// query has a body worth reading.
|
||
|
|
async fn mock_wallet_setup() -> Wallet {
|
||
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||
|
|
.await
|
||
|
|
.expect("bind mock wallet");
|
||
|
|
let port = listener.local_addr().expect("mock wallet addr").port();
|
||
|
|
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(|req: &str| {
|
||
|
|
if req.contains("query_key") {
|
||
|
|
r#"{"jsonrpc":"2.0","id":"0","result":{"key":"lumber tacit lemon ivory risk"}}"#
|
||
|
|
.to_string()
|
||
|
|
} else {
|
||
|
|
r#"{"jsonrpc":"2.0","id":"0","result":{}}"#.to_string()
|
||
|
|
}
|
||
|
|
});
|
||
|
|
tokio::spawn(serve_mock_rpc(listener, reply));
|
||
|
|
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The reported bug: a created wallet was never remembered, because the
|
||
|
|
/// creation path never reached the store's catalogue.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn creating_a_wallet_records_it_in_the_catalogue() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let home = dir.path().join("bob");
|
||
|
|
let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await);
|
||
|
|
|
||
|
|
let created = node.wallet_create("hunter2").await.expect("create wallet");
|
||
|
|
|
||
|
|
assert!(created.record.id > 0, "the store assigns the row id");
|
||
|
|
assert_eq!(created.record.wallet_filename, "onionwire-1");
|
||
|
|
assert_eq!(created.record.identity_pubkey, node.identity_pk());
|
||
|
|
assert_eq!(created.record.onion_locator, "test.onion");
|
||
|
|
assert_eq!(created.seed, "lumber tacit lemon ivory risk");
|
||
|
|
assert_eq!(
|
||
|
|
node.list_wallets().expect("list wallets"),
|
||
|
|
vec![created.record],
|
||
|
|
"the wallet just created is the catalogue"
|
||
|
|
);
|
||
|
|
assert_eq!(
|
||
|
|
sealed_passphrase(&node),
|
||
|
|
"hunter2",
|
||
|
|
"the passphrase that opens the file is remembered, or the next \
|
||
|
|
start cannot open it"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The second half of the bug: a second create reused the one hardcoded file
|
||
|
|
/// name, so the RPC refused it — and nothing was remembered across a restart.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn a_second_wallet_gets_its_own_file_and_both_survive_a_reopen() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let home = dir.path().join("bob");
|
||
|
|
let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await);
|
||
|
|
|
||
|
|
let first = node.wallet_create("p1").await.expect("first wallet");
|
||
|
|
let second = node.wallet_create("p1").await.expect("second wallet");
|
||
|
|
|
||
|
|
assert_ne!(
|
||
|
|
first.record.wallet_filename, second.record.wallet_filename,
|
||
|
|
"a second wallet must not reuse the first one's file"
|
||
|
|
);
|
||
|
|
drop(node);
|
||
|
|
let reopened = Store::open_at_with_passphrase(&home, PASS).expect("reopen store");
|
||
|
|
assert_eq!(
|
||
|
|
reopened.list_wallets().expect("list wallets").len(),
|
||
|
|
2,
|
||
|
|
"both wallets are remembered across a restart"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Import is a creation path too: it takes the same hardcoded name today.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn importing_a_wallet_records_it_in_the_catalogue() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node_with_wallet(
|
||
|
|
&dir.path().join("bob"),
|
||
|
|
Arc::new(NoDial),
|
||
|
|
mock_wallet_setup().await,
|
||
|
|
);
|
||
|
|
|
||
|
|
let imported = node
|
||
|
|
.wallet_restore("hunter2", "lumber tacit lemon ivory risk", None)
|
||
|
|
.await
|
||
|
|
.expect("restore wallet");
|
||
|
|
|
||
|
|
assert_eq!(imported.wallet_filename, "onionwire-1");
|
||
|
|
assert_eq!(
|
||
|
|
node.list_wallets().expect("list wallets").len(),
|
||
|
|
1,
|
||
|
|
"an imported wallet is remembered too"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A catalogue row the child never opens is still a broken wallet: the
|
||
|
|
/// child's stored config defaults to `onionwire`, which no created wallet
|
||
|
|
/// uses any more.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn creating_a_wallet_points_the_child_at_its_own_file() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node_with_wallet(
|
||
|
|
&dir.path().join("bob"),
|
||
|
|
Arc::new(NoDial),
|
||
|
|
mock_wallet_setup().await,
|
||
|
|
);
|
||
|
|
|
||
|
|
let first = node.wallet_create("p1").await.expect("first wallet");
|
||
|
|
assert_eq!(
|
||
|
|
node.wallet_child_config().wallet_filename,
|
||
|
|
first.record.wallet_filename,
|
||
|
|
"the child must open the wallet that was just created"
|
||
|
|
);
|
||
|
|
|
||
|
|
let second = node.wallet_create("p1").await.expect("second wallet");
|
||
|
|
assert_eq!(
|
||
|
|
node.wallet_child_config().wallet_filename,
|
||
|
|
second.record.wallet_filename
|
||
|
|
);
|
||
|
|
assert_eq!(
|
||
|
|
node.list_wallets().expect("list wallets")[0].wallet_filename,
|
||
|
|
first.record.wallet_filename,
|
||
|
|
"the first wallet keeps its own file"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A catalogue name is still skipped: the disk check is an addition, not a
|
||
|
|
/// replacement, and a remembered wallet must keep its own file.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn a_catalogue_name_is_still_skipped_by_the_picker() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let home = dir.path().join("bob");
|
||
|
|
let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await);
|
||
|
|
{
|
||
|
|
let store = node.store.lock().expect("store");
|
||
|
|
test_record_wallet(&store, "onionwire-1", "");
|
||
|
|
}
|
||
|
|
|
||
|
|
let created = node.wallet_create("p1").await.expect("create wallet");
|
||
|
|
|
||
|
|
assert_eq!(created.record.wallet_filename, "onionwire-2");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The reported bug: a wallet file whose catalogue row is gone — an
|
||
|
|
/// explicit `Store::delete_wallet`, or a create whose `record_wallet`
|
||
|
|
/// failed — is still on disk, so a catalogue-only picker proposes the same
|
||
|
|
/// name for ever and the daemon answers `-21 Cannot create wallet. Already
|
||
|
|
/// exists.` with no way out from the UI.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn wallet_files_on_disk_are_skipped_when_picking_a_name() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let home = dir.path().join("bob");
|
||
|
|
let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await);
|
||
|
|
// No catalogue rows at all: only the disk knows about these two, and
|
||
|
|
// monero writes two files per wallet, so either one means "taken".
|
||
|
|
std::fs::write(home.join("wallet").join("onionwire-1.keys"), b"keys").unwrap();
|
||
|
|
std::fs::write(home.join("wallet").join("onionwire-2"), b"wallet").unwrap();
|
||
|
|
|
||
|
|
let created = node.wallet_create("p1").await.expect("create wallet");
|
||
|
|
|
||
|
|
assert_eq!(
|
||
|
|
created.record.wallet_filename, "onionwire-3",
|
||
|
|
"the stray `.keys` file and the stray wallet file are both taken"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A stray file under some *other* name must not bump the picker: the
|
||
|
|
/// check is about this candidate, not about the directory being busy.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn an_unrelated_file_on_disk_does_not_cost_the_first_name() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let home = dir.path().join("bob");
|
||
|
|
let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await);
|
||
|
|
std::fs::write(home.join("wallet").join("someone-elses"), b"x").unwrap();
|
||
|
|
|
||
|
|
let created = node.wallet_create("p1").await.expect("create wallet");
|
||
|
|
|
||
|
|
assert_eq!(created.record.wallet_filename, "onionwire-1");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Fail closed: a wallet directory that cannot be listed is an error, not
|
||
|
|
/// "every name is free". Guessing here is how the collision comes back.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn the_wallet_name_picker_fails_closed_when_the_dir_cannot_be_read() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let home = dir.path().join("bob");
|
||
|
|
let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await);
|
||
|
|
std::fs::remove_dir_all(home.join("wallet")).unwrap();
|
||
|
|
|
||
|
|
let err = node
|
||
|
|
.wallet_create("p1")
|
||
|
|
.await
|
||
|
|
.expect_err("an unreadable wallet dir must refuse, not guess");
|
||
|
|
|
||
|
|
assert!(
|
||
|
|
err.contains("wallet dir"),
|
||
|
|
"the error must name the directory it could not list: {err}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
node.list_wallets().expect("list wallets").is_empty(),
|
||
|
|
"a refused create records nothing"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The catalogue is a store fact, not a wallet-RPC fact: listing must work
|
||
|
|
/// with no wallet configured, and creating must still refuse without one.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn a_wallet_off_install_lists_an_empty_catalogue() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||
|
|
|
||
|
|
assert!(node.list_wallets().expect("list wallets").is_empty());
|
||
|
|
let err = node
|
||
|
|
.wallet_create("hunter2")
|
||
|
|
.await
|
||
|
|
.expect_err("no wallet RPC");
|
||
|
|
assert!(err.contains("ONIONWIRE_WALLET_RPC"), "{err}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Switching wallets is a catalogue read plus a child re-point: the chosen
|
||
|
|
/// row's file name is what the child opens, and the generated RPC creds in
|
||
|
|
/// the same sealed record survive the read-modify-write.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn open_wallet_points_the_child_at_the_chosen_file_and_keeps_the_creds() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let home = dir.path().join("bob");
|
||
|
|
let node = offline_node(&home, Arc::new(NoDial));
|
||
|
|
{
|
||
|
|
let store = node.store.lock().unwrap();
|
||
|
|
store
|
||
|
|
.save_wallet_child(
|
||
|
|
r#"{"user":"owuser","pass":"ow-secret-pass-xyz","wallet_filename":"onionwire"}"#,
|
||
|
|
)
|
||
|
|
.unwrap();
|
||
|
|
for file in ["onionwire", "onionwire-1"] {
|
||
|
|
store
|
||
|
|
.create_wallet(&NewWallet {
|
||
|
|
name: None,
|
||
|
|
identity_pubkey: [7u8; 32],
|
||
|
|
onion_locator: "abcd.onion".into(),
|
||
|
|
wallet_filename: file.to_string(),
|
||
|
|
})
|
||
|
|
.unwrap();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
node.open_wallet("onionwire-1")
|
||
|
|
.expect("open a saved wallet");
|
||
|
|
assert_eq!(
|
||
|
|
node.wallet_child_config().wallet_filename,
|
||
|
|
"onionwire-1",
|
||
|
|
"the child must open the wallet that was chosen"
|
||
|
|
);
|
||
|
|
let sealed = node
|
||
|
|
.store
|
||
|
|
.lock()
|
||
|
|
.unwrap()
|
||
|
|
.load_wallet_child()
|
||
|
|
.unwrap()
|
||
|
|
.expect("sealed record");
|
||
|
|
assert!(
|
||
|
|
sealed.contains("ow-secret-pass-xyz"),
|
||
|
|
"the re-point dropped the generated creds: {sealed}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
sealed.contains("\"user\":\"owuser\""),
|
||
|
|
"the re-point dropped the generated creds: {sealed}"
|
||
|
|
);
|
||
|
|
|
||
|
|
// A restart re-reads the record, so the choice is remembered.
|
||
|
|
drop(node);
|
||
|
|
let restarted = offline_node(&home, Arc::new(NoDial));
|
||
|
|
assert_eq!(
|
||
|
|
restarted.wallet_child_config().wallet_filename,
|
||
|
|
"onionwire-1",
|
||
|
|
"the chosen wallet must survive a restart"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The catalogue is the only directory the app has, so a file it does not
|
||
|
|
/// hold is refused instead of pointing a spend-capable child at a path.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn open_wallet_refuses_a_file_the_catalogue_does_not_hold() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||
|
|
{
|
||
|
|
let store = node.store.lock().unwrap();
|
||
|
|
store
|
||
|
|
.save_wallet_child(r#"{"user":"owuser","pass":"p","wallet_filename":"onionwire"}"#)
|
||
|
|
.unwrap();
|
||
|
|
store
|
||
|
|
.create_wallet(&NewWallet {
|
||
|
|
name: None,
|
||
|
|
identity_pubkey: [7u8; 32],
|
||
|
|
onion_locator: String::new(),
|
||
|
|
wallet_filename: "onionwire".to_string(),
|
||
|
|
})
|
||
|
|
.unwrap();
|
||
|
|
}
|
||
|
|
|
||
|
|
let err = node
|
||
|
|
.open_wallet("onionwire-9")
|
||
|
|
.expect_err("not a saved wallet");
|
||
|
|
assert!(err.contains("no saved wallet"), "{err}");
|
||
|
|
assert_eq!(
|
||
|
|
node.wallet_child_config().wallet_filename,
|
||
|
|
"onionwire",
|
||
|
|
"a refused switch must leave the child where it was"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The active wallet is a child-config fact, not a catalogue fact: a row in
|
||
|
|
/// the catalogue that the child was never pointed at is not open, and a
|
||
|
|
/// fresh install has no open wallet at all.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn active_wallet_filename_is_none_until_the_child_has_been_pointed() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||
|
|
|
||
|
|
assert_eq!(
|
||
|
|
node.active_wallet_filename().expect("read"),
|
||
|
|
None,
|
||
|
|
"a fresh install has no open wallet file"
|
||
|
|
);
|
||
|
|
|
||
|
|
// A record written before the settings were persisted (creds, no
|
||
|
|
// source block) is not an open wallet either.
|
||
|
|
node.store
|
||
|
|
.lock()
|
||
|
|
.unwrap()
|
||
|
|
.save_wallet_child(r#"{"user":"owuser","pass":"ow-pass"}"#)
|
||
|
|
.unwrap();
|
||
|
|
assert_eq!(
|
||
|
|
node.active_wallet_filename().expect("read"),
|
||
|
|
None,
|
||
|
|
"a creds-only record does not name a wallet file"
|
||
|
|
);
|
||
|
|
|
||
|
|
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
|
||
|
|
assert_eq!(
|
||
|
|
node.active_wallet_filename().expect("read"),
|
||
|
|
None,
|
||
|
|
"a catalogue row alone does not open the wallet"
|
||
|
|
);
|
||
|
|
|
||
|
|
node.open_wallet("onionwire-1")
|
||
|
|
.expect("open a saved wallet");
|
||
|
|
assert_eq!(
|
||
|
|
node.active_wallet_filename().expect("read").as_deref(),
|
||
|
|
Some("onionwire-1"),
|
||
|
|
"the open wallet is the file the child was pointed at"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// No wallet, no dial: the refusal is the configured-guard copy, not a
|
||
|
|
/// connection error, and it happens before any socket is opened.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn wallet_keys_without_a_wallet_refuses_without_dialing() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||
|
|
let err = node.wallet_keys().await.expect_err("no wallet configured");
|
||
|
|
assert_eq!(err, wallet::NOT_CONFIGURED_MSG);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The node-level path a Kotlin caller takes: two `query_key` calls against
|
||
|
|
/// the open wallet's RPC, with the view-only `-29` arriving as
|
||
|
|
/// `spend_key: None` rather than as an error.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn wallet_keys_of_a_view_only_wallet_returns_no_spend_key() {
|
||
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||
|
|
.await
|
||
|
|
.expect("bind mock wallet");
|
||
|
|
let port = listener.local_addr().expect("mock wallet addr").port();
|
||
|
|
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(|req: &str| {
|
||
|
|
if req.contains("spend_key") {
|
||
|
|
r#"{"jsonrpc":"2.0","id":"0","error":{"code":-29,"message":"The wallet is watch-only. Cannot retrieve spend key."}}"#
|
||
|
|
.to_string()
|
||
|
|
} else {
|
||
|
|
r#"{"jsonrpc":"2.0","id":"0","result":{"key":"aabbccdd"}}"#.to_string()
|
||
|
|
}
|
||
|
|
});
|
||
|
|
tokio::spawn(serve_mock_rpc(listener, reply));
|
||
|
|
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node_with_wallet(
|
||
|
|
&dir.path().join("bob"),
|
||
|
|
Arc::new(NoDial),
|
||
|
|
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url"),
|
||
|
|
);
|
||
|
|
|
||
|
|
let keys = node.wallet_keys().await.expect("keys");
|
||
|
|
assert_eq!(keys.view_key, "aabbccdd");
|
||
|
|
assert_eq!(
|
||
|
|
keys.spend_key, None,
|
||
|
|
"the RPC's -29 is the wallet's answer, not a failure"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A loopback wallet RPC that records every request it is asked and answers
|
||
|
|
/// what a reopened wallet needs: `open_wallet`, `get_address` /
|
||
|
|
/// `get_balance`, and a synced `get_info`. The request log is the evidence —
|
||
|
|
/// a mock that answers whatever it is asked cannot tell a client that opened
|
||
|
|
/// the file from one that never asked.
|
||
|
|
fn recording_wallet_reply(
|
||
|
|
requests: Arc<Mutex<Vec<String>>>,
|
||
|
|
) -> Arc<dyn Fn(&str) -> String + Send + Sync> {
|
||
|
|
Arc::new(move |req: &str| {
|
||
|
|
requests.lock().expect("requests").push(req.to_string());
|
||
|
|
if req.contains("open_wallet") {
|
||
|
|
r#"{"jsonrpc":"2.0","id":"0","result":{}}"#.to_string()
|
||
|
|
} else if req.contains("get_address") {
|
||
|
|
format!(
|
||
|
|
r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#,
|
||
|
|
addr = xmr_addr()
|
||
|
|
)
|
||
|
|
} else if req.contains("get_info") {
|
||
|
|
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"#
|
||
|
|
.to_string()
|
||
|
|
} else {
|
||
|
|
r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0","unlocked_balance":"0"}}"#
|
||
|
|
.to_string()
|
||
|
|
}
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The pid of the running wallet child. Panics when there is none: every
|
||
|
|
/// caller has just started one.
|
||
|
|
fn child_pid(node: &Node) -> u32 {
|
||
|
|
node.wallet_child
|
||
|
|
.lock()
|
||
|
|
.ok()
|
||
|
|
.and_then(|guard| guard.clone())
|
||
|
|
.and_then(|child| child.wallet_rpc_pid())
|
||
|
|
.expect("a running wallet child")
|
||
|
|
}
|
||
|
|
|
||
|
|
/// `--rpc-bind-port <port>` out of a fake child's argv log.
|
||
|
|
fn rpc_port_in(raw: &str) -> Option<u16> {
|
||
|
|
let lines: Vec<&str> = raw.lines().collect();
|
||
|
|
let i = lines.iter().position(|line| *line == "--rpc-bind-port")?;
|
||
|
|
lines
|
||
|
|
.get(i + 1)
|
||
|
|
.and_then(|port| port.trim().parse::<u16>().ok())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The port the child with this pid was spawned with, read out of the argv
|
||
|
|
/// log that child alone writes — `<log>.<pid>`, `mv`d into place in one step.
|
||
|
|
///
|
||
|
|
/// The shared path must not be used for this. Every child writes it and a
|
||
|
|
/// previous child's write is unsequenced against the test, so on a loaded
|
||
|
|
/// runner it lands after a poller has cleared the file: the poller then binds
|
||
|
|
/// its mock on the port of a child that has already been killed, and the
|
||
|
|
/// restarted child's `open_wallet` is refused for the whole
|
||
|
|
/// `WALLET_OPEN_WAIT` (CI run 905, job 1373 — the same message in run 901,
|
||
|
|
/// green 3/3 on a 16-core host). A pid in the file name is a handshake the
|
||
|
|
/// child cannot lose.
|
||
|
|
async fn wait_for_child_rpc_port(argv_log: &Path, pid: u32) -> u16 {
|
||
|
|
let mut name = argv_log.as_os_str().to_owned();
|
||
|
|
name.push(format!(".{pid}"));
|
||
|
|
let path = PathBuf::from(name);
|
||
|
|
for _ in 0..600 {
|
||
|
|
if let Ok(raw) = std::fs::read_to_string(&path)
|
||
|
|
&& let Some(port) = rpc_port_in(&raw)
|
||
|
|
{
|
||
|
|
return port;
|
||
|
|
}
|
||
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
||
|
|
}
|
||
|
|
panic!(
|
||
|
|
"the fake child {pid} never wrote an --rpc-bind-port to {}",
|
||
|
|
path.display()
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The port the *next* child was spawned with, read from the argv log that
|
||
|
|
/// child alone owns — `<log>.<pid>`.
|
||
|
|
///
|
||
|
|
/// The pid comes from the directory, not from the node: the node publishes
|
||
|
|
/// the child only after the readiness gate saw its RPC accept, so a test
|
||
|
|
/// that must *be* that listener has to find the port from the outside. The
|
||
|
|
/// shared path is still the wrong one for the same reason
|
||
|
|
/// [`wait_for_child_rpc_port`] documents.
|
||
|
|
async fn wait_for_restarted_rpc_port(argv_log: &Path, previous_pid: u32) -> u16 {
|
||
|
|
let name = argv_log
|
||
|
|
.file_name()
|
||
|
|
.and_then(|name| name.to_str())
|
||
|
|
.expect("the argv log has a file name");
|
||
|
|
let dir = argv_log.parent().expect("the argv log has a directory");
|
||
|
|
let prefix = format!("{name}.");
|
||
|
|
for _ in 0..600 {
|
||
|
|
if let Ok(entries) = std::fs::read_dir(dir) {
|
||
|
|
for entry in entries.flatten() {
|
||
|
|
let path = entry.path();
|
||
|
|
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
|
||
|
|
continue;
|
||
|
|
};
|
||
|
|
let Some(suffix) = name.strip_prefix(prefix.as_str()) else {
|
||
|
|
continue;
|
||
|
|
};
|
||
|
|
// `<log>.<pid>` only. A child killed between its shared write
|
||
|
|
// and its own leaves `<log>.<pid>.writing` behind, and that
|
||
|
|
// temp file still names the *previous* child's port.
|
||
|
|
let Ok(pid) = suffix.parse::<u32>() else {
|
||
|
|
continue;
|
||
|
|
};
|
||
|
|
if pid == previous_pid {
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
if let Ok(raw) = std::fs::read_to_string(&path)
|
||
|
|
&& let Some(port) = rpc_port_in(&raw)
|
||
|
|
{
|
||
|
|
return port;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
||
|
|
}
|
||
|
|
panic!(
|
||
|
|
"no child other than pid {previous_pid} published an --rpc-bind-port under {}",
|
||
|
|
dir.display()
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Bind the restarted child's mock on `port`, retrying while the readiness
|
||
|
|
/// stand-in still holds it: the stand-in releases the port on the gate's own
|
||
|
|
/// probe, and the mock must own it from then on.
|
||
|
|
async fn bind_when_free(port: u16) -> tokio::net::TcpListener {
|
||
|
|
for _ in 0..500 {
|
||
|
|
if let Ok(listener) = tokio::net::TcpListener::bind(("127.0.0.1", port)).await {
|
||
|
|
return listener;
|
||
|
|
}
|
||
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
||
|
|
}
|
||
|
|
panic!("the readiness stand-in never released port {port}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The wallet-file passphrase this install remembers, `""` when none.
|
||
|
|
fn sealed_passphrase(node: &Node) -> String {
|
||
|
|
node.store
|
||
|
|
.lock()
|
||
|
|
.expect("store")
|
||
|
|
.load_wallet_config()
|
||
|
|
.expect("load wallet config")
|
||
|
|
.map(|cfg| cfg.wallet_passphrase.as_str().to_string())
|
||
|
|
.unwrap_or_default()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A wallet RPC that is not answering *yet* is not a row error: it is the
|
||
|
|
/// child coming up, and the row would otherwise flash the string the user
|
||
|
|
/// saw. Everything else — a timeout, `-13`, a refused passphrase — is the
|
||
|
|
/// RPC's own answer and stays on the row.
|
||
|
|
#[test]
|
||
|
|
fn an_unreachable_probe_is_not_a_status_error() {
|
||
|
|
use crate::wallet::error_is_unreachable;
|
||
|
|
assert!(error_is_unreachable(
|
||
|
|
"wallet connect: Connection refused (os error 111)"
|
||
|
|
));
|
||
|
|
assert!(error_is_unreachable("wallet write: Connection reset"));
|
||
|
|
assert!(!error_is_unreachable("wallet RPC timed out"));
|
||
|
|
assert!(!error_is_unreachable("No wallet file"));
|
||
|
|
assert_eq!(
|
||
|
|
probe_error(
|
||
|
|
false,
|
||
|
|
Some("wallet connect: Connection refused (os error 111)".into()),
|
||
|
|
None
|
||
|
|
),
|
||
|
|
None,
|
||
|
|
"a connect refusal while coming up is not a row error"
|
||
|
|
);
|
||
|
|
assert_eq!(
|
||
|
|
probe_error(
|
||
|
|
false,
|
||
|
|
Some("wallet connect: Connection refused (os error 111)".into()),
|
||
|
|
Some("bad passphrase".into())
|
||
|
|
),
|
||
|
|
Some("bad passphrase".into()),
|
||
|
|
"a connect refusal must not replace a real error"
|
||
|
|
);
|
||
|
|
assert_eq!(
|
||
|
|
probe_error(false, Some("No wallet file".into()), None),
|
||
|
|
Some("No wallet file".into()),
|
||
|
|
"an RPC answer is still stored"
|
||
|
|
);
|
||
|
|
assert_eq!(
|
||
|
|
probe_error(true, Some("ignored".into()), Some("old".into())),
|
||
|
|
None
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The bug this card exists for: `monero-wallet-rpc` keeps a wallet open
|
||
|
|
/// only for the life of its process, so a restarted child answered every
|
||
|
|
/// read with `-13 No wallet file` while the file sat on disk. The second
|
||
|
|
/// start must issue `open_wallet` with the file and the stored passphrase,
|
||
|
|
/// and the read after it must take the success path.
|
||
|
|
///
|
||
|
|
/// Multi-threaded on purpose: the start path is synchronous and blocks, so
|
||
|
|
/// only another worker can answer on the restarted child's port while it
|
||
|
|
/// waits for its RPC to come up.
|
||
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||
|
|
async fn a_restart_opens_the_stored_wallet_file() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let home = dir.path().join("child");
|
||
|
|
let argv_log = dir.path().join("argv.log");
|
||
|
|
let bin = fake_child_bin(
|
||
|
|
&dir.path().join("fake-bins"),
|
||
|
|
"monero-wallet-rpc",
|
||
|
|
&argv_log,
|
||
|
|
"sleep 30",
|
||
|
|
);
|
||
|
|
let node = Arc::new(offline_node(&home, Arc::new(NoDial)));
|
||
|
|
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire-1"))
|
||
|
|
.expect("set config");
|
||
|
|
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
|
||
|
|
|
||
|
|
// First start: the catalogue holds the file, but this install holds no
|
||
|
|
// passphrase for it. That is a state, not a failure. The gate needs the
|
||
|
|
// port the fake was told to bind; the restart below is answered by this
|
||
|
|
// test's own mock, so the hold is dropped before it.
|
||
|
|
let hold = PublishedPortHold::watching(std::slice::from_ref(&argv_log));
|
||
|
|
node.start_wallet_child().expect("first start");
|
||
|
|
let status = node.wallet_child_status();
|
||
|
|
assert!(status.running, "{status:?}");
|
||
|
|
assert!(!status.wallet_open, "{status:?}");
|
||
|
|
assert!(status.needs_passphrase, "{status:?}");
|
||
|
|
assert!(status.last_error.is_none(), "{status:?}");
|
||
|
|
drop(hold);
|
||
|
|
|
||
|
|
// Restart it with the passphrase the user supplied. The child picks a
|
||
|
|
// fresh port, so the mock is bound to the port *this* spawn named while
|
||
|
|
// the open waits for its RPC to answer — read from the argv log the new
|
||
|
|
// pid owns, never from the shared path the previous child wrote: a loaded
|
||
|
|
// runner lands that write after a clear (CI run 905, job 1373).
|
||
|
|
//
|
||
|
|
// The node cannot name that pid any more (it publishes the child only
|
||
|
|
// once the gate has seen the RPC accept), so the port comes from the
|
||
|
|
// directory — and the mock must own it *before* the gate's probe, not
|
||
|
|
// after: a listener that accepts the probe and then closes resets the
|
||
|
|
// client's own dial, which is an RPC answer, not an unreachable child.
|
||
|
|
let first_pid = child_pid(&node);
|
||
|
|
std::fs::write(&argv_log, b"").expect("clear the argv log");
|
||
|
|
let requests = Arc::new(Mutex::new(Vec::new()));
|
||
|
|
let starter = Arc::clone(&node);
|
||
|
|
let started = tokio::task::spawn_blocking(move || {
|
||
|
|
starter.open_wallet_with_passphrase("onionwire-1", "walletfile-pass")
|
||
|
|
});
|
||
|
|
let port = wait_for_restarted_rpc_port(&argv_log, first_pid).await;
|
||
|
|
let listener = bind_when_free(port).await;
|
||
|
|
tokio::spawn(serve_mock_rpc(
|
||
|
|
listener,
|
||
|
|
recording_wallet_reply(Arc::clone(&requests)),
|
||
|
|
));
|
||
|
|
started
|
||
|
|
.await
|
||
|
|
.expect("join the start")
|
||
|
|
.expect("open the wallet with a passphrase");
|
||
|
|
|
||
|
|
let sent = requests.lock().unwrap().join("\n");
|
||
|
|
assert!(
|
||
|
|
sent.contains(r#""method":"open_wallet""#),
|
||
|
|
"the restart never asked the RPC to open the file: {sent}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
sent.contains(r#""filename":"onionwire-1""#),
|
||
|
|
"the restart opened the wrong file: {sent}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
sent.contains(r#""password":"walletfile-pass""#),
|
||
|
|
"the restart did not send the passphrase it was handed: {sent}"
|
||
|
|
);
|
||
|
|
assert_eq!(
|
||
|
|
sealed_passphrase(&node),
|
||
|
|
"walletfile-pass",
|
||
|
|
"a verified passphrase is kept, or the next restart cannot open the file"
|
||
|
|
);
|
||
|
|
|
||
|
|
// The read after the restart takes the success path: the same mock
|
||
|
|
// answers `get_address`/`get_balance`/`get_info`.
|
||
|
|
let status = node.wallet_child_refresh().await;
|
||
|
|
assert!(status.wallet_open, "{status:?}");
|
||
|
|
assert!(!status.needs_passphrase, "{status:?}");
|
||
|
|
assert_eq!(status.state, WalletChildState::Ready, "{status:?}");
|
||
|
|
assert!(
|
||
|
|
requests
|
||
|
|
.lock()
|
||
|
|
.unwrap()
|
||
|
|
.iter()
|
||
|
|
.any(|r| r.contains("get_balance")),
|
||
|
|
"the wallet was read back through the reopened file"
|
||
|
|
);
|
||
|
|
|
||
|
|
node.stop_wallet_child().expect("stop");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The port the restarted child's mock listens on must come from *that*
|
||
|
|
/// child, not from the shared argv path a previous child has already written.
|
||
|
|
/// The old harness cleared that path and read it anyway, and the clear is not
|
||
|
|
/// a synchronisation: on a loaded runner the killed child's write lands after
|
||
|
|
/// it, so the mock was bound on a port nothing dialled and the restarted
|
||
|
|
/// child's `open_wallet` was refused for the whole `WALLET_OPEN_WAIT` (CI run
|
||
|
|
/// 905, job 1373; the same message in run 901, green 3/3 on a 16-core host).
|
||
|
|
/// Here the killed child's argv is left in place — the worst case of that
|
||
|
|
/// race — and the restart still reaches the mock on its own port.
|
||
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||
|
|
async fn a_restart_is_not_given_the_stopped_childs_port() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let home = dir.path().join("child");
|
||
|
|
let argv_log = dir.path().join("argv.log");
|
||
|
|
let bin = fake_child_bin(
|
||
|
|
&dir.path().join("fake-bins"),
|
||
|
|
"monero-wallet-rpc",
|
||
|
|
&argv_log,
|
||
|
|
"sleep 30",
|
||
|
|
);
|
||
|
|
let node = Arc::new(offline_node(&home, Arc::new(NoDial)));
|
||
|
|
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire-1"))
|
||
|
|
.expect("set config");
|
||
|
|
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
|
||
|
|
|
||
|
|
let hold = PublishedPortHold::watching(std::slice::from_ref(&argv_log));
|
||
|
|
node.start_wallet_child().expect("first start");
|
||
|
|
let first_pid = child_pid(&node);
|
||
|
|
// The killed child's argv is in the shared path (its own log lands first,
|
||
|
|
// so this waits for both) — the content the old harness would read.
|
||
|
|
let stale_port = wait_for_child_rpc_port(&argv_log, first_pid).await;
|
||
|
|
|
||
|
|
// The restart's own log lands at once, while the shared path lags 2s
|
||
|
|
// behind — the way a loaded runner lands the killed child's write after
|
||
|
|
// a clear. The lag is what makes the shared read below wrong; it is not
|
||
|
|
// the child's exec that is late, because the readiness gate now runs
|
||
|
|
// before the child is published and cannot wait 2s for an argv file.
|
||
|
|
let restart = fake_child_bin_shared_late(
|
||
|
|
&dir.path().join("fake-bins-restart"),
|
||
|
|
"monero-wallet-rpc",
|
||
|
|
&argv_log,
|
||
|
|
"sleep 2",
|
||
|
|
"sleep 30",
|
||
|
|
);
|
||
|
|
node.set_wallet_child_config(&loopback_child_config(restart, "onionwire-1"))
|
||
|
|
.expect("re-point the child at the late-write stand-in");
|
||
|
|
let requests = Arc::new(Mutex::new(Vec::new()));
|
||
|
|
let starter = Arc::clone(&node);
|
||
|
|
drop(hold);
|
||
|
|
let started = tokio::task::spawn_blocking(move || {
|
||
|
|
starter.open_wallet_with_passphrase("onionwire-1", "walletfile-pass")
|
||
|
|
});
|
||
|
|
// The premise of the test, asserted while it is true: the shared path
|
||
|
|
// still holds the killed child's argv, so a harness that reads it binds
|
||
|
|
// the mock on the wrong port and the restart never reaches a mock at all.
|
||
|
|
assert_eq!(
|
||
|
|
rpc_port_in(&std::fs::read_to_string(&argv_log).unwrap_or_default()),
|
||
|
|
Some(stale_port),
|
||
|
|
"the restarted child must not have written the shared path yet"
|
||
|
|
);
|
||
|
|
let port = wait_for_restarted_rpc_port(&argv_log, first_pid).await;
|
||
|
|
let listener = bind_when_free(port).await;
|
||
|
|
tokio::spawn(serve_mock_rpc(
|
||
|
|
listener,
|
||
|
|
recording_wallet_reply(Arc::clone(&requests)),
|
||
|
|
));
|
||
|
|
started
|
||
|
|
.await
|
||
|
|
.expect("join the start")
|
||
|
|
.expect("open the wallet with a passphrase");
|
||
|
|
|
||
|
|
assert!(
|
||
|
|
requests
|
||
|
|
.lock()
|
||
|
|
.unwrap()
|
||
|
|
.iter()
|
||
|
|
.any(|request| request.contains("open_wallet")),
|
||
|
|
"the restart never reached the mock on the port it dialled"
|
||
|
|
);
|
||
|
|
node.stop_wallet_child().expect("stop");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// No stored passphrase: the child starts with no wallet open and the status
|
||
|
|
/// says `needs passphrase`. It must not fail the start — a wallet created
|
||
|
|
/// before the passphrase was stored still has a working node — and it must
|
||
|
|
/// not send an `open_wallet` it has no passphrase for.
|
||
|
|
///
|
||
|
|
/// Multi-threaded so the mock can answer while the start blocks, which is
|
||
|
|
/// what makes "no `open_wallet` was sent" a measurement rather than a
|
||
|
|
/// consequence of nothing being able to listen.
|
||
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||
|
|
async fn a_catalogue_wallet_without_a_sealed_passphrase_never_asks_to_open() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let home = dir.path().join("child");
|
||
|
|
let argv_log = dir.path().join("argv.log");
|
||
|
|
let bin = fake_child_bin(
|
||
|
|
&dir.path().join("fake-bins"),
|
||
|
|
"monero-wallet-rpc",
|
||
|
|
&argv_log,
|
||
|
|
"sleep 30",
|
||
|
|
);
|
||
|
|
let node = Arc::new(offline_node(&home, Arc::new(NoDial)));
|
||
|
|
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire-1"))
|
||
|
|
.expect("set config");
|
||
|
|
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
|
||
|
|
|
||
|
|
let hold = PublishedPortHold::watching(std::slice::from_ref(&argv_log));
|
||
|
|
node.start_wallet_child()
|
||
|
|
.expect("a wallet-less child still starts");
|
||
|
|
let status = node.wallet_child_status();
|
||
|
|
assert!(status.running, "{status:?}");
|
||
|
|
assert!(!status.wallet_open, "{status:?}");
|
||
|
|
assert!(status.needs_passphrase, "{status:?}");
|
||
|
|
let first_pid = child_pid(&node);
|
||
|
|
node.stop_wallet_child().expect("stop");
|
||
|
|
|
||
|
|
// A second start, this time with an RPC listening on the port it was
|
||
|
|
// spawned with: had the start tried to open a file it would have dialed
|
||
|
|
// this and left the request in the log (or died trying, and failed).
|
||
|
|
std::fs::write(&argv_log, b"").expect("clear the argv log");
|
||
|
|
let requests = Arc::new(Mutex::new(Vec::new()));
|
||
|
|
let starter = Arc::clone(&node);
|
||
|
|
// The second start is answered by the mock this test binds, and the node
|
||
|
|
// cannot name its pid: it publishes the child only once the gate has seen
|
||
|
|
// the RPC accept. The mock is bound from the child's own log, in time for
|
||
|
|
// the gate's next probe.
|
||
|
|
drop(hold);
|
||
|
|
let started = tokio::task::spawn_blocking(move || starter.start_wallet_child());
|
||
|
|
let port = wait_for_restarted_rpc_port(&argv_log, first_pid).await;
|
||
|
|
let listener = bind_when_free(port).await;
|
||
|
|
tokio::spawn(serve_mock_rpc(
|
||
|
|
listener,
|
||
|
|
recording_wallet_reply(Arc::clone(&requests)),
|
||
|
|
));
|
||
|
|
started
|
||
|
|
.await
|
||
|
|
.expect("join the start")
|
||
|
|
.expect("second start");
|
||
|
|
|
||
|
|
let status = node.wallet_child_status();
|
||
|
|
assert!(status.running, "{status:?}");
|
||
|
|
assert!(status.needs_passphrase, "{status:?}");
|
||
|
|
assert!(
|
||
|
|
!requests
|
||
|
|
.lock()
|
||
|
|
.unwrap()
|
||
|
|
.iter()
|
||
|
|
.any(|r| r.contains("open_wallet")),
|
||
|
|
"there is no passphrase to open with, so no open_wallet may be sent"
|
||
|
|
);
|
||
|
|
node.stop_wallet_child().expect("stop");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A refused passphrase is its own error, not a generic start failure, and
|
||
|
|
/// an unverified passphrase is never stored: the next start must not be
|
||
|
|
/// broken by a secret the user believed was right.
|
||
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||
|
|
async fn a_refused_passphrase_is_a_distinct_error_and_is_not_sealed() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||
|
|
.await
|
||
|
|
.expect("bind mock wallet");
|
||
|
|
let port = listener.local_addr().expect("mock wallet addr").port();
|
||
|
|
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(|req: &str| {
|
||
|
|
if req.contains("open_wallet") {
|
||
|
|
r#"{"jsonrpc":"2.0","id":"0","error":{"code":-1,"message":"Failed to open wallet"}}"#
|
||
|
|
.to_string()
|
||
|
|
} else {
|
||
|
|
r#"{"jsonrpc":"2.0","id":"0","result":{}}"#.to_string()
|
||
|
|
}
|
||
|
|
});
|
||
|
|
tokio::spawn(serve_mock_rpc(listener, reply));
|
||
|
|
let node = offline_node_with_wallet(
|
||
|
|
&dir.path().join("bob"),
|
||
|
|
Arc::new(NoDial),
|
||
|
|
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url"),
|
||
|
|
);
|
||
|
|
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
|
||
|
|
|
||
|
|
let err = node
|
||
|
|
.open_wallet_with_passphrase("onionwire-1", "wrong-pass")
|
||
|
|
.expect_err("the RPC refuses the wrong passphrase");
|
||
|
|
assert!(
|
||
|
|
err.contains("onionwire-1"),
|
||
|
|
"the error names the file: {err}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
err.contains("Failed to open wallet"),
|
||
|
|
"the RPC's own reason is carried through: {err}"
|
||
|
|
);
|
||
|
|
assert!(!err.contains("wrong-pass"), "no secret in an error: {err}");
|
||
|
|
let status = node.wallet_child_status();
|
||
|
|
assert!(status.needs_passphrase, "{status:?}");
|
||
|
|
assert!(!status.wallet_open, "{status:?}");
|
||
|
|
assert!(
|
||
|
|
sealed_passphrase(&node).is_empty(),
|
||
|
|
"a passphrase no daemon accepted must not be stored"
|
||
|
|
);
|
||
|
|
assert_eq!(
|
||
|
|
node.wallet_child_config().wallet_filename,
|
||
|
|
"onionwire-1",
|
||
|
|
"the child is still pointed at the wallet the user is unlocking"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The one-time path that ends the `needs passphrase` state: the passphrase
|
||
|
|
/// is verified by a live RPC, then stored, and the status flips to open. The
|
||
|
|
/// catalogue still refuses a file it does not hold.
|
||
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||
|
|
async fn open_wallet_with_passphrase_seals_what_a_daemon_verified() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||
|
|
.await
|
||
|
|
.expect("bind mock wallet");
|
||
|
|
let port = listener.local_addr().expect("mock wallet addr").port();
|
||
|
|
let requests = Arc::new(Mutex::new(Vec::new()));
|
||
|
|
tokio::spawn(serve_mock_rpc(
|
||
|
|
listener,
|
||
|
|
recording_wallet_reply(Arc::clone(&requests)),
|
||
|
|
));
|
||
|
|
let node = offline_node_with_wallet(
|
||
|
|
&dir.path().join("bob"),
|
||
|
|
Arc::new(NoDial),
|
||
|
|
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url"),
|
||
|
|
);
|
||
|
|
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
|
||
|
|
|
||
|
|
let err = node
|
||
|
|
.open_wallet_with_passphrase("onionwire-1", "")
|
||
|
|
.expect_err("no passphrase to open with");
|
||
|
|
assert!(err.contains("passphrase"), "{err}");
|
||
|
|
let err = node
|
||
|
|
.open_wallet_with_passphrase("onionwire-9", "walletfile-pass")
|
||
|
|
.expect_err("not a saved wallet");
|
||
|
|
assert!(err.contains("no saved wallet"), "{err}");
|
||
|
|
|
||
|
|
node.open_wallet_with_passphrase("onionwire-1", "walletfile-pass")
|
||
|
|
.expect("open a saved wallet");
|
||
|
|
|
||
|
|
let sent = requests.lock().unwrap().join("\n");
|
||
|
|
assert!(
|
||
|
|
sent.contains(r#""method":"open_wallet""#),
|
||
|
|
"no open_wallet request: {sent}"
|
||
|
|
);
|
||
|
|
assert!(sent.contains(r#""filename":"onionwire-1""#), "{sent}");
|
||
|
|
assert_eq!(sealed_passphrase(&node), "walletfile-pass");
|
||
|
|
let status = node.wallet_child_status();
|
||
|
|
assert!(status.wallet_open, "{status:?}");
|
||
|
|
assert!(!status.needs_passphrase, "{status:?}");
|
||
|
|
}
|
||
|
|
}
|