wallet: app-owned child lifecycle + user-chosen ChainSource
All checks were successful
ci / test (pull_request) Successful in 4m1s
ci / sdk (pull_request) Successful in 1m2s

The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.

- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
  port }. No default remote node; Remote is only constructed from explicit
  user input. A .onion Remote is refused without a SOCKS proxy (separate
  card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
  --rpc-bind-ip 127.0.0.1, a random free loopback port, generated
  --rpc-login, and --wallet-dir /wallet; monerod too for a
  local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
  (wallet_child table, AEAD on top of whole-db encryption), never a
  plaintext file. The Wallet client is built from the generated loopback
  URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
  height>=target_height; can_spend() and can_verify_receipts() gate on it.
  Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
  calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
  because a first sync or a remote daemon outlasts 5s and a 5s cap there
  is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
  configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.

Base: feat/wallet-create-import (PR #66). Do not rebase onto main.

Co-Authored-By: Hermes Agent <agent@local>
This commit is contained in:
agent 2026-09-14 18:55:07 -04:00
commit 8331a2dde6
No known key found for this signature in database
7 changed files with 1341 additions and 60 deletions

View file

@ -15,6 +15,7 @@ pub mod session;
mod store;
pub mod tui;
pub mod wallet;
pub mod wallet_child;
pub use store::{
Friend, FriendProfile, Message, Payment, PaymentWrite, SelfIdentity, Store,

View file

@ -1056,7 +1056,11 @@ impl Node {
.map_err(|e| e.to_string())?
};
let mut verified = false;
if self.wallet.configured() {
// 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 ready = self.wallet.configured() && self.wallet.can_verify_receipts().await;
if ready {
match self.wallet.get_transfers().await {
Ok(rows)
if wallet::transfers_match(

View file

@ -251,6 +251,14 @@ impl Store {
kdf_salt BLOB NOT NULL,
wrapped_key BLOB NOT NULL
);
-- The wallet child's RPC creds + chain-source snapshot. One row,
-- sealed with the store data key (see `save_wallet_child`): the
-- creds never touch the filesystem in the clear.
CREATE TABLE IF NOT EXISTS wallet_child (
id INTEGER PRIMARY KEY CHECK (id = 1),
sealed BLOB NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS payments (
id INTEGER PRIMARY KEY,
friend_id INTEGER NOT NULL REFERENCES friends(id),
@ -298,6 +306,43 @@ impl Store {
.map_err(Into::into)
}
/// Seal the wallet child's config (RPC creds + chain-source snapshot) into
/// the encrypted store, replacing the single row.
///
/// The creds are generated per install and grant spend authority over the
/// wallet child, so they are stored the same way message bodies are: AEAD
/// with the store data key on top of the whole-db SQLCipher layer. They are
/// never written to a plaintext file beside the wallet.
pub fn save_wallet_child(&self, json: &str) -> Result<()> {
let blob = crate::backup::aead_encrypt(&self.msg_key, json.as_bytes(), WALLET_CHILD_AAD)
.map_err(Error)?;
self.conn.execute(
"INSERT INTO wallet_child (id, sealed, updated_at) VALUES (1, ?1, ?2)
ON CONFLICT(id) DO UPDATE SET sealed = excluded.sealed, updated_at = excluded.updated_at",
params![blob, unix_now()],
)?;
Ok(())
}
/// Read back the sealed wallet-child config, or `None` before the first
/// child start. A blob that does not decrypt is an error, never a guess.
pub fn load_wallet_child(&self) -> Result<Option<String>> {
let row: Option<Vec<u8>> = self
.conn
.query_row("SELECT sealed FROM wallet_child WHERE id = 1", [], |row| {
row.get(0)
})
.optional()?;
let Some(blob) = row else {
return Ok(None);
};
let plain = crate::backup::aead_decrypt(&self.msg_key, &blob, WALLET_CHILD_AAD)
.map_err(|_| Error("wallet-child config decrypt failed".into()))?;
String::from_utf8(plain)
.map(Some)
.map_err(|_| Error("wallet-child config is not utf-8".into()))
}
pub fn replace_identity_keys(
&self,
identity_sk: &[u8],
@ -1395,6 +1440,10 @@ fn unix_now() -> i64 {
.unwrap_or(0)
}
/// AAD for the sealed wallet-child row. Domain-separates it from message and
/// outbox blobs that share the same store data key.
const WALLET_CHILD_AAD: &[u8] = b"onionwire/wallet-child/v1";
fn fingerprint(pubkey: &[u8]) -> String {
pubkey.iter().map(|b| format!("{b:02x}")).collect()
}
@ -1831,4 +1880,66 @@ mod at_rest {
);
}
}
/// The wallet-child RPC creds grant spend authority, so they are stored
/// sealed in the encrypted store — never as a plaintext file next to the
/// wallet, and never as a plaintext row.
#[test]
fn wallet_child_creds_round_trip_sealed_and_load_none_before_first_start() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open_at_with_passphrase(dir.path(), "child-pass").unwrap();
assert!(
store.load_wallet_child().unwrap().is_none(),
"a fresh store has no wallet-child config"
);
let cfg = r#"{"user":"owuser","pass":"ow-secret-pass-xyz","wallet_filename":"onionwire"}"#;
store.save_wallet_child(cfg).unwrap();
assert_eq!(store.load_wallet_child().unwrap().as_deref(), Some(cfg));
let sealed: Vec<u8> = store
.conn
.query_row("SELECT sealed FROM wallet_child WHERE id = 1", [], |r| {
r.get(0)
})
.unwrap();
assert_ne!(
sealed.as_slice(),
cfg.as_bytes(),
"row stored the creds as plaintext"
);
assert!(
!sealed
.windows(11)
.any(|w| w == b"ow-secret-p".as_slice()),
"sealed row leaked the password"
);
// Re-sealing replaces the single row instead of stacking rows.
let cfg2 = r#"{"user":"owuser","pass":"second-pass-abc","wallet_filename":"onionwire"}"#;
store.save_wallet_child(cfg2).unwrap();
assert_eq!(store.load_wallet_child().unwrap().as_deref(), Some(cfg2));
let rows: i64 = store
.conn
.query_row("SELECT count(*) FROM wallet_child", [], |r| r.get(0))
.unwrap();
assert_eq!(rows, 1, "wallet_child must hold exactly one row");
store.checkpoint_wal().unwrap();
drop(store);
for name in ["onionwire.db", "onionwire.db-wal", "onionwire.db-shm"] {
let path = dir.path().join(name);
let Ok(bytes) = std::fs::read(&path) else {
continue;
};
for needle in [
b"second-pass-abc".as_slice(),
b"ow-secret-pass-xyz".as_slice(),
] {
assert!(
!bytes.windows(needle.len()).any(|w| w == needle),
"{name} contains the wallet-child password in the clear"
);
}
}
}
}

View file

@ -1,3 +1,4 @@
use std::path::PathBuf;
use std::time::Duration;
use rand::RngCore;
@ -18,6 +19,33 @@ impl std::fmt::Display for Error {
impl std::error::Error for Error {}
/// The user's choice of where the Monero daemon lives. No default remote node
/// is ever implied — every `Remote` is constructed from explicit user input.
///
/// Wallet RPC is always loopback HTTP Digest. The chain source is what the
/// *wallet child* connects to, not what the messenger dials.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChainSource {
/// Receive-only. No wallet child, no daemon, no spend.
None,
/// Spawn a local `monerod`. Chain traffic stays on the device.
Local {
/// Path to the `monerod` binary.
monerod_bin: PathBuf,
/// Data directory for the local daemon.
datadir: PathBuf,
},
/// A daemon address the user supplied. Trust follows the address.
Remote {
/// Daemon host. May be loopback, `.onion`, or a clearnet host the user
/// typed explicitly.
host: String,
/// Daemon port. User-configurable; 18089 (restricted RPC) is common but
/// not a constant.
port: u16,
},
}
#[derive(Clone)]
struct Endpoint {
host: String,
@ -43,6 +71,14 @@ impl std::fmt::Debug for Endpoint {
pub struct Wallet {
endpoint: Option<Endpoint>,
no_spend: bool,
/// Budget for loopback management calls (`get_address`, `query_key`,
/// create/import). The wallet child is on the same box, so this stays short.
timeout_local: Duration,
/// Budget for calls that wait on the daemon (`get_info`, `get_transfers`,
/// `transfer`). A first sync or a remote daemon legitimately outlasts the
/// local budget, and treating that as "down" is what left receipts
/// permanently unverified.
timeout_chain: Duration,
}
/// What /tip says when the wallet cannot spend. Same text for the explicit
@ -50,6 +86,10 @@ pub struct Wallet {
/// RPC, so the operator never has to guess which one it was.
const VIEW_ONLY_MSG: &str = "wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work";
/// What a spend says while the wallet is not synced. Honest state, not a bug:
/// the caller retries once the daemon has caught up.
pub const NOT_SYNCED_MSG: &str = "wallet is not synced — spend refused until the daemon reaches the chain tip";
/// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in monero's
/// `src/wallet/wallet_rpc_server_error_codes.h`.
const WATCH_ONLY_CODE: i64 = -29;
@ -69,14 +109,27 @@ pub const SPEND_AUTHORITY_WARNING: &str = "this wallet file can spend. anyone wi
const RPC_TIMEOUT: Duration = Duration::from_secs(5);
/// Budget for calls that wait on the daemon (`get_info`, `get_transfers`,
/// `transfer`). A first sync or a remote daemon legitimately outlasts the
/// loopback budget; a 5s cap there leaves receipts permanently unverified.
pub const CHAIN_RPC_TIMEOUT: Duration = Duration::from_secs(60);
impl Wallet {
pub fn disabled() -> Self {
/// The one place the budgets are defaulted. Callers adjust them with
/// [`Wallet::with_timeouts`].
fn new(endpoint: Option<Endpoint>, no_spend: bool) -> Self {
Self {
endpoint: None,
no_spend: false,
endpoint,
no_spend,
timeout_local: RPC_TIMEOUT,
timeout_chain: CHAIN_RPC_TIMEOUT,
}
}
pub fn disabled() -> Self {
Self::new(None, false)
}
/// `ONIONWIRE_WALLET_NO_SPEND=1` asks for a view-only deployment: `/tip` is
/// refused locally, before any RPC dial. `/pay` and receipt verification
/// keep working.
@ -92,31 +145,28 @@ impl Wallet {
.map(|v| Zeroizing::new(v.trim().to_string()))
.filter(|v| !v.is_empty());
match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) {
Ok(endpoint) => Self {
endpoint: Some(endpoint),
no_spend,
},
Ok(endpoint) => Self::new(Some(endpoint), no_spend),
Err(e) => {
eprintln!("ONIONWIRE_WALLET_RPC: {e}");
Self {
endpoint: None,
no_spend,
}
Self::new(None, no_spend)
}
}
}
_ => Self {
endpoint: None,
no_spend,
},
_ => Self::new(None, no_spend),
}
}
pub fn from_url(url: &str) -> Result<Self> {
Ok(Self {
endpoint: Some(parse_http_url(url, None)?),
no_spend: false,
})
Ok(Self::new(Some(parse_http_url(url, None)?), false))
}
/// Set both RPC budgets. The timeout is a property of the backend, not a
/// compile-time constant: a loopback wallet child answers fast, while a
/// remote daemon or a first sync needs a longer chain-side budget.
pub fn with_timeouts(mut self, local: Duration, chain: Duration) -> Self {
self.timeout_local = local;
self.timeout_chain = chain;
self
}
/// No-spend (view-only) mode. Same switch as `ONIONWIRE_WALLET_NO_SPEND`.
@ -151,8 +201,14 @@ impl Wallet {
if self.no_spend {
return Err(Error(VIEW_ONLY_MSG.into()));
}
// Honest gate: a wallet that has not caught up to the chain tip cannot
// build a spend, so refuse instead of letting the RPC fail opaquely.
// Fail closed — if readiness cannot be proven, the spend is refused.
if !self.can_spend().await {
return Err(Error(NOT_SYNCED_MSG.into()));
}
let sent = self
.rpc(
.chain_rpc(
"transfer",
serde_json::json!({
"destinations": [{"amount": amount, "address": address}],
@ -191,7 +247,7 @@ impl Wallet {
pub async fn get_transfers(&self) -> Result<Vec<TransferRow>> {
let v = self
.rpc(
.chain_rpc(
"get_transfers",
serde_json::json!({"in": true, "pending": true}),
)
@ -221,6 +277,56 @@ impl Wallet {
json_str(&v, "balance")
}
/// Unlocked balance in piconero — the part a spend can actually use.
pub async fn unlocked_balance(&self) -> Result<u64> {
let v = self
.rpc("get_balance", serde_json::json!({"account_index": 0}))
.await?;
json_str(&v, "unlocked_balance")?
.trim()
.parse::<u64>()
.map_err(|_| Error("wallet RPC returned a non-numeric unlocked_balance".into()))
}
/// The real readiness predicate: the daemon has reached the chain tip and
/// the wallet has scanned up to it. `synchronized` must be explicitly true —
/// a missing field is not-ready, never a silent pass.
pub async fn chain_ready(&self) -> Result<bool> {
let v = self.chain_rpc("get_info", serde_json::json!({})).await?;
let synced = v
.get("synchronized")
.and_then(|b| b.as_bool())
.unwrap_or(false);
let height = v.get("height").and_then(|h| h.as_u64()).unwrap_or(0);
let target = v
.get("target_height")
.and_then(|h| h.as_u64())
.unwrap_or(0);
Ok(synced && height > 0 && (target == 0 || height >= target))
}
/// May this wallet attempt a spend? Fail closed: any readiness doubt is a
/// refusal, and a view-only/no-spend wallet never spends.
pub async fn can_spend(&self) -> bool {
!self.no_spend && self.configured() && self.chain_ready().await.unwrap_or(false)
}
/// The stricter signal for the spend UI: chain-ready *and* holding unlocked
/// funds. Zero unlocked balance is not spend-ready.
pub async fn spend_ready(&self) -> Result<bool> {
if !self.chain_ready().await? {
return Ok(false);
}
Ok(self.unlocked_balance().await? > 0)
}
/// Receipt verification is only honest on a synced wallet: `get_transfers`
/// on a wallet that has not scanned to the tip cannot see the tx, so a
/// "miss" would be a lie. Until ready, receipts stay `verified=0`.
pub async fn can_verify_receipts(&self) -> bool {
self.configured() && self.chain_ready().await.unwrap_or(false)
}
/// Create a new spend-capable wallet on the RPC (`create_wallet`). The
/// user does not paste a key — the daemon generates the seed. Returns that
/// seed once (from `query_key mnemonic`) so the UI can show a backup
@ -280,7 +386,28 @@ impl Wallet {
Ok(())
}
/// Loopback management call: the wallet child is on the same box, so it gets
/// the short budget.
async fn rpc(&self, method: &str, params: serde_json::Value) -> Result<serde_json::Value> {
self.rpc_with(method, params, self.timeout_local).await
}
/// Chain-dependent call (`get_info`, `get_transfers`, `transfer`): it waits
/// on the daemon, so it gets the longer budget.
async fn chain_rpc(
&self,
method: &str,
params: serde_json::Value,
) -> Result<serde_json::Value> {
self.rpc_with(method, params, self.timeout_chain).await
}
async fn rpc_with(
&self,
method: &str,
params: serde_json::Value,
budget: Duration,
) -> Result<serde_json::Value> {
let ep = self
.endpoint
.as_ref()
@ -292,7 +419,7 @@ impl Wallet {
"params": params,
})
.to_string();
let raw = post_timeout(ep, &build_req(ep, &body, None)).await?;
let raw = post_timeout(ep, &build_req(ep, &body, None), budget).await?;
let status = http_status(&raw).unwrap_or(0);
if status == 200 {
return Err(Error(
@ -311,7 +438,7 @@ impl Wallet {
));
}
let auth = digest_authorization(ep, &challenge)?;
let raw = post_timeout(ep, &build_req(ep, &body, Some(&auth))).await?;
let raw = post_timeout(ep, &build_req(ep, &body, Some(&auth)), budget).await?;
parse_json_rpc(&raw)
}
}
@ -440,8 +567,8 @@ fn host_header(host: &str, port: u16) -> String {
const MAX_RPC_BYTES: usize = 1024 * 1024;
async fn post_timeout(ep: &Endpoint, req: &str) -> Result<Vec<u8>> {
tokio::time::timeout(RPC_TIMEOUT, http_post(ep, req.as_bytes()))
async fn post_timeout(ep: &Endpoint, req: &str, budget: Duration) -> Result<Vec<u8>> {
tokio::time::timeout(budget, http_post(ep, req.as_bytes()))
.await
.map_err(|_| Error("wallet RPC timed out".into()))?
}

756
src/wallet_child.rs Normal file
View file

@ -0,0 +1,756 @@
//! Wallet child lifecycle: the app owns `monero-wallet-rpc` — and, when the
//! user chose a local chain source, `monerod` — instead of asking the user to
//! start them and export an env var.
//!
//! Locked shape:
//!
//! * The wallet child speaks loopback HTTP Digest only
//! (`--rpc-bind-ip 127.0.0.1`, a random free port, generated `--rpc-login`).
//! * The RPC credentials are generated once, sealed with the store data key and
//! kept in the encrypted SQLCipher store. They are never a plaintext file.
//! * The chain source is the user's explicit choice ([`ChainSource`]) — never a
//! compiled-in public node. A `.onion` daemon needs a SOCKS proxy, which is a
//! separate card: here it is refused with a clear error.
//! * `--trusted-daemon` is never passed: a remote daemon is untrusted.
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Child, Command};
use std::sync::Mutex;
use rand::RngCore;
use zeroize::Zeroizing;
use crate::store::Store;
use crate::wallet::{self, ChainSource, Wallet};
/// `monerod` RPC port for a local chain source. Unrestricted RPC default; the
/// wallet child is the only thing that dials it.
pub const DEFAULT_MONEROD_RPC_PORT: u16 = 18081;
/// Name of the `monero-wallet-rpc` binary when the caller does not point at one.
pub const DEFAULT_WALLET_RPC_BIN: &str = "monero-wallet-rpc";
/// Errors from wallet child setup and lifecycle.
#[derive(Debug)]
pub struct ChildError(String);
impl std::fmt::Display for ChildError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::error::Error for ChildError {}
type Result<T> = std::result::Result<T, ChildError>;
/// The app-owned wallet child pair (`monerod` when local, `monero-wallet-rpc`).
pub struct WalletChild {
source: ChainSource,
wallet_rpc_bin: PathBuf,
wallet_dir: PathBuf,
wallet_filename: String,
monerod: Mutex<Option<Child>>,
wallet_rpc: Mutex<Option<Child>>,
}
impl WalletChild {
/// Configure the children. Nothing is spawned until [`WalletChild::start`].
///
/// `wallet_dir` is created 0700 and holds the wallet file plus the daemon
/// state; the caller passes `$ONIONWIRE_HOME/wallet`.
pub fn new(
source: ChainSource,
wallet_dir: PathBuf,
wallet_filename: Option<String>,
) -> Result<Self> {
let wallet_filename =
wallet_filename.unwrap_or_else(|| wallet::DEFAULT_WALLET_FILENAME.to_string());
if wallet_filename.trim().is_empty() {
return Err(ChildError("wallet filename required".into()));
}
create_dir_700(&wallet_dir).map_err(|e| ChildError(format!("wallet dir: {e}")))?;
Ok(Self {
source,
wallet_rpc_bin: PathBuf::from(DEFAULT_WALLET_RPC_BIN),
wallet_dir,
wallet_filename,
monerod: Mutex::new(None),
wallet_rpc: Mutex::new(None),
})
}
/// Point at a specific `monero-wallet-rpc` binary (explicit config, tests).
pub fn with_wallet_rpc_bin(mut self, bin: PathBuf) -> Self {
self.wallet_rpc_bin = bin;
self
}
/// The user's chain-source choice. `None` is receive-only: no child at all.
pub fn chain_source(&self) -> &ChainSource {
&self.source
}
pub fn wallet_dir(&self) -> &Path {
&self.wallet_dir
}
pub fn wallet_filename(&self) -> &str {
&self.wallet_filename
}
/// Whether this configuration spawns any child.
pub fn is_enabled(&self) -> bool {
!matches!(self.source, ChainSource::None)
}
/// Is a tracked child still alive? Polls the process table; an exited child
/// is reaped here so a later `stop` is a no-op.
pub fn running(&self) -> bool {
let _ = self.reap_exited();
self.monerod.lock().map(|g| g.is_some()).unwrap_or(false)
|| self.wallet_rpc.lock().map(|g| g.is_some()).unwrap_or(false)
}
/// True when a tracked child has exited since the last poll. Watching the
/// child is polling + `try_wait`: there is no pidfd plumbing in std, and the
/// honest thing is to report what `try_wait` actually says.
pub fn child_exited(&self) -> bool {
self.reap_exited()
}
fn reap_exited(&self) -> bool {
let mut exited = false;
for slot in [&self.monerod, &self.wallet_rpc] {
let Ok(mut guard) = slot.lock() else {
continue;
};
let gone = match guard.as_mut() {
Some(child) => matches!(child.try_wait(), Ok(Some(_))),
None => false,
};
if gone {
*guard = None;
exited = true;
}
}
exited
}
/// The `--daemon-address` for each chain source. A local source is the
/// loopback daemon this struct owns; a remote one is exactly what the user
/// typed.
pub fn daemon_address(source: &ChainSource) -> Option<String> {
match source {
ChainSource::None => None,
ChainSource::Local { .. } => Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")),
ChainSource::Remote { host, port } => Some(format!("{host}:{port}")),
}
}
/// Bind a loopback port and hand it back. The listener is dropped
/// immediately; the port is only used to keep two instances from colliding.
pub fn pick_port() -> Result<u16> {
let listener = std::net::TcpListener::bind("127.0.0.1:0")
.map_err(|e| ChildError(format!("bind loopback port: {e}")))?;
let port = listener
.local_addr()
.map_err(|e| ChildError(format!("local_addr: {e}")))?
.port();
drop(listener);
Ok(port)
}
/// The exact argv used to spawn `monerod`. Single source of truth: `start`
/// spawns this and the tests assert on it.
pub fn monerod_argv(bin: &Path, datadir: &Path, rpc_port: u16) -> Vec<String> {
vec![
bin.display().to_string(),
"--non-interactive".into(),
"--data-dir".into(),
datadir.display().to_string(),
"--rpc-bind-ip".into(),
"127.0.0.1".into(),
"--rpc-bind-port".into(),
rpc_port.to_string(),
]
}
/// The exact argv used to spawn `monero-wallet-rpc`. Digest login is
/// mandatory and the bind is loopback; `--trusted-daemon` is deliberately
/// absent.
pub fn wallet_rpc_argv(
bin: &Path,
port: u16,
login: &str,
wallet_dir: &Path,
daemon_address: Option<&str>,
) -> Vec<String> {
let mut argv = vec![
bin.display().to_string(),
"--rpc-bind-ip".into(),
"127.0.0.1".into(),
"--rpc-bind-port".into(),
port.to_string(),
"--rpc-login".into(),
login.to_string(),
"--wallet-dir".into(),
wallet_dir.display().to_string(),
];
if let Some(addr) = daemon_address {
argv.push("--daemon-address".into());
argv.push(addr.to_string());
}
argv
}
/// Start the children (idempotent per source) and hand back the loopback
/// client the app should talk to.
///
/// `None` -> `Ok(None)`: receive-only, nothing is spawned.
pub fn start(&self, store: &Store) -> Result<Option<WalletClient>> {
if !self.is_enabled() {
return Ok(None);
}
if let ChainSource::Remote { host, .. } = &self.source
&& host.trim().to_ascii_lowercase().ends_with(".onion")
{
return Err(ChildError(
"remote .onion daemon needs a SOCKS proxy — configure the local/remote \
chain source instead (separate card)"
.into(),
));
}
if self.running() {
return Err(ChildError("wallet child already running".into()));
}
// Local chain source: own monerod first, so the wallet child has a
// daemon to dial.
if let ChainSource::Local {
monerod_bin,
datadir,
} = &self.source
{
ensure_parent(datadir)?;
let argv = Self::monerod_argv(monerod_bin, datadir, DEFAULT_MONEROD_RPC_PORT);
let child = spawn(&argv, "monerod")?;
let mut guard = self
.monerod
.lock()
.map_err(|e| ChildError(format!("monerod lock: {e}")))?;
*guard = Some(child);
}
let (user, pass) = self.creds(store)?;
let port = Self::pick_port()?;
let login = format!("{user}:{}", pass.as_str());
let daemon = Self::daemon_address(&self.source);
let argv = Self::wallet_rpc_argv(
&self.wallet_rpc_bin,
port,
&login,
&self.wallet_dir,
daemon.as_deref(),
);
let child = spawn(&argv, "monero-wallet-rpc")?;
{
let mut guard = self
.wallet_rpc
.lock()
.map_err(|e| ChildError(format!("wallet-rpc lock: {e}")))?;
if guard.is_some() {
return Err(ChildError("wallet child already running".into()));
}
*guard = Some(child);
}
// monero-wallet-rpc creates the wallet file 0600; make that true even if
// it already existed with looser bits.
harden_wallet_file(&self.wallet_dir.join(&self.wallet_filename));
Ok(Some(WalletClient {
url: format!("http://{user}:{}@127.0.0.1:{port}/json_rpc", pass.as_str()),
no_spend: false,
}))
}
/// Stop both children. Idempotent, and tolerant of a child that already
/// exited on its own.
pub fn stop(&self) -> Result<()> {
kill_slot(&self.wallet_rpc, "monero-wallet-rpc")?;
kill_slot(&self.monerod, "monerod")?;
Ok(())
}
/// Load the sealed creds, or generate them once and seal them in the store.
/// The store is the only place they live; `wallet_dir` never sees them.
fn creds(&self, store: &Store) -> Result<(String, Zeroizing<String>)> {
if let Some(raw) = store
.load_wallet_child()
.map_err(|e| ChildError(format!("read wallet-child creds: {e}")))?
{
let parsed: serde_json::Value = serde_json::from_str(&raw)
.map_err(|e| ChildError(format!("parse wallet-child creds: {e}")))?;
let user = parsed
.get("user")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.ok_or_else(|| ChildError("wallet-child creds missing user".into()))?;
let pass = parsed
.get("pass")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.ok_or_else(|| ChildError("wallet-child creds missing pass".into()))?;
return Ok((user.to_string(), Zeroizing::new(pass.to_string())));
}
let (user, pass) = generate_creds();
let record = serde_json::json!({
"user": user,
"pass": pass.as_str(),
"source": source_to_json(&self.source),
"wallet_filename": self.wallet_filename,
});
store
.save_wallet_child(&record.to_string())
.map_err(|e| ChildError(format!("seal wallet-child creds: {e}")))?;
Ok((user, pass))
}
}
/// The loopback client built from the generated URL — the production path when
/// the app owns the child. Never `ONIONWIRE_WALLET_RPC`, never anything but
/// numeric loopback.
#[derive(Debug, Clone)]
pub struct WalletClient {
url: String,
no_spend: bool,
}
impl WalletClient {
/// Build the [`Wallet`] this child serves. The chain-side RPC budget is the
/// wallet backend's default (see `CHAIN_RPC_TIMEOUT`), because a first sync
/// or a remote daemon legitimately outlasts a loopback round trip.
pub fn into_wallet(self) -> Wallet {
Wallet::from_url(&self.url)
.expect("wallet child URL is always valid loopback with creds")
.with_no_spend(self.no_spend)
}
/// The loopback URL. Carries the generated creds — do not log it.
pub fn url(&self) -> &str {
&self.url
}
pub fn no_spend(&self) -> bool {
self.no_spend
}
pub fn set_no_spend(&mut self, on: bool) {
self.no_spend = on;
}
}
/// Random, shell- and HTTP-safe credentials: `[a-z0-9]` only. No `:`, no quotes,
/// no whitespace — the login goes through `--rpc-login` and an HTTP Digest
/// header. The user and the password are drawn from separate randomness.
fn generate_creds() -> (String, Zeroizing<String>) {
let mut user_buf = [0u8; 16];
let mut pass_buf = [0u8; 24];
let mut rng = rand::thread_rng();
rng.fill_bytes(&mut user_buf);
rng.fill_bytes(&mut pass_buf);
(rand_token(&user_buf), Zeroizing::new(rand_token(&pass_buf)))
}
fn rand_token(buf: &[u8]) -> String {
const ALPH: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";
let mut out = String::with_capacity(buf.len());
for b in buf {
out.push(ALPH[(*b as usize) % ALPH.len()] as char);
}
out
}
/// Snapshot of the user's chain-source choice, stored beside the creds so the
/// UI can show what the child was started against.
fn source_to_json(source: &ChainSource) -> serde_json::Value {
match source {
ChainSource::None => serde_json::json!({"kind": "none"}),
ChainSource::Local {
monerod_bin,
datadir,
} => serde_json::json!({
"kind": "local",
"monerod_bin": monerod_bin.display().to_string(),
"datadir": datadir.display().to_string(),
}),
ChainSource::Remote { host, port } => serde_json::json!({
"kind": "remote",
"host": host,
"port": port,
}),
}
}
fn spawn(argv: &[String], what: &str) -> Result<Child> {
let (bin, args) = argv
.split_first()
.ok_or_else(|| ChildError(format!("empty argv for {what}")))?;
Command::new(bin)
.args(args)
.spawn()
.map_err(|e| ChildError(format!("spawn {what}: {e}")))
}
fn kill_slot(slot: &Mutex<Option<Child>>, what: &str) -> Result<()> {
let mut guard = slot
.lock()
.map_err(|e| ChildError(format!("{what} lock: {e}")))?;
if let Some(child) = guard.as_mut() {
// An already-exited child (reaped or not) makes kill() an error: check
// first so `stop` stays idempotent.
if !matches!(child.try_wait(), Ok(Some(_))) {
let _ = child.kill();
let _ = child.wait();
}
}
*guard = None;
Ok(())
}
fn create_dir_700(path: &Path) -> std::io::Result<()> {
fs::create_dir_all(path)?;
let mut perms = fs::metadata(path)?.permissions();
perms.set_mode(0o700);
fs::set_permissions(path, perms)
}
fn ensure_parent(path: &Path) -> Result<()> {
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
{
create_dir_700(parent).map_err(|e| ChildError(format!("datadir parent: {e}")))?;
}
Ok(())
}
/// The wallet file is a spend authority: keep it 0600.
fn harden_wallet_file(path: &Path) {
let Ok(meta) = fs::metadata(path) else {
return;
};
let mut perms = meta.permissions();
perms.set_mode(0o600);
let _ = fs::set_permissions(path, perms);
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn tmp_dir(tag: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("onionwire-child-{tag}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
dir
}
fn open_store(dir: &Path) -> Store {
Store::open_at_with_passphrase(dir, "child-test-pass").expect("open store")
}
/// A stand-in for monerod / monero-wallet-rpc: records its argv, then parks.
fn fake_bin(dir: &Path, name: &str, log: &Path) -> PathBuf {
let path = dir.join(name);
let mut f = fs::File::create(&path).unwrap();
writeln!(f, "#!/bin/sh").unwrap();
writeln!(f, ": > '{}'", log.display()).unwrap();
writeln!(
f,
"for a in \"$@\"; do printf '%s\\n' \"$a\" >> '{}'; done",
log.display()
)
.unwrap();
writeln!(f, "sleep 30").unwrap();
drop(f);
let mut perms = fs::metadata(&path).unwrap().permissions();
perms.set_mode(0o700);
fs::set_permissions(&path, perms).unwrap();
path
}
fn argv_from(log: &Path) -> Vec<String> {
fs::read_to_string(log)
.unwrap_or_default()
.lines()
.map(str::to_string)
.collect()
}
/// The fake child writes its argv after exec: poll instead of racing it.
fn wait_for_argv(log: &Path) -> Vec<String> {
for _ in 0..60 {
let argv = argv_from(log);
if !argv.is_empty() {
return argv;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
argv_from(log)
}
fn local_source(dir: &Path, monerod: PathBuf) -> ChainSource {
ChainSource::Local {
monerod_bin: monerod,
datadir: dir.join("monerod-data"),
}
}
#[test]
fn none_source_is_disabled_and_starts_nothing() {
let dir = tmp_dir("none");
let store = open_store(&dir);
let child = WalletChild::new(ChainSource::None, dir.join("wallet"), None).unwrap();
assert!(!child.is_enabled());
assert!(child.start(&store).unwrap().is_none());
assert!(!child.running());
}
#[test]
fn onion_remote_daemon_is_refused_without_a_socks_proxy() {
let dir = tmp_dir("onion");
let store = open_store(&dir);
let child = WalletChild::new(
ChainSource::Remote {
host: "abcdefghijklmnop.onion".into(),
port: 18081,
},
dir.join("wallet"),
None,
)
.unwrap();
let err = child.start(&store).unwrap_err().to_string();
assert!(err.contains("SOCKS"), "got {err}");
}
#[test]
fn daemon_address_matches_each_chain_source() {
assert_eq!(WalletChild::daemon_address(&ChainSource::None), None);
assert_eq!(
WalletChild::daemon_address(&local_source(
Path::new("/tmp"),
PathBuf::from("/usr/bin/monerod")
)),
Some("127.0.0.1:18081".into())
);
assert_eq!(
WalletChild::daemon_address(&ChainSource::Remote {
host: "node.example.com".into(),
port: 18089
}),
Some("node.example.com:18089".into())
);
}
#[test]
fn wallet_rpc_argv_carries_the_locked_flags() {
let dir = tmp_dir("argv");
let bin = PathBuf::from("/opt/monero/monero-wallet-rpc");
let argv = WalletChild::wallet_rpc_argv(
&bin,
39127,
"owuser:owpass",
&dir,
Some("127.0.0.1:18081"),
);
let pairs: Vec<(&str, &str)> = argv
.windows(2)
.map(|w| (w[0].as_str(), w[1].as_str()))
.collect();
assert!(pairs.contains(&("--rpc-bind-ip", "127.0.0.1")), "{argv:?}");
assert!(pairs.contains(&("--rpc-bind-port", "39127")), "{argv:?}");
assert!(
pairs.contains(&("--rpc-login", "owuser:owpass")),
"{argv:?}"
);
assert!(
pairs.contains(&("--wallet-dir", dir.to_str().unwrap())),
"{argv:?}"
);
assert!(
pairs.contains(&("--daemon-address", "127.0.0.1:18081")),
"{argv:?}"
);
assert_eq!(argv[0], bin.display().to_string());
assert!(
!argv.iter().any(|a| a == "--trusted-daemon"),
"a remote daemon is untrusted: {argv:?}"
);
}
#[test]
fn monerod_argv_binds_loopback_and_uses_the_datadir() {
let dir = tmp_dir("monerod-argv");
let datadir = dir.join("chain");
let argv = WalletChild::monerod_argv(
&PathBuf::from("/usr/bin/monerod"),
&datadir,
DEFAULT_MONEROD_RPC_PORT,
);
let pairs: Vec<(&str, &str)> = argv
.windows(2)
.map(|w| (w[0].as_str(), w[1].as_str()))
.collect();
assert!(
pairs.contains(&("--data-dir", datadir.to_str().unwrap())),
"{argv:?}"
);
assert!(pairs.contains(&("--rpc-bind-ip", "127.0.0.1")), "{argv:?}");
assert!(pairs.contains(&("--rpc-bind-port", "18081")), "{argv:?}");
}
/// The real spawn path: a local chain source starts monerod, then
/// monero-wallet-rpc, with exactly the argv the builders produce — and the
/// creds come out of the encrypted store, not a file in the wallet dir.
#[test]
fn start_spawns_both_children_with_the_built_argv() {
let dir = tmp_dir("start");
let store = open_store(&dir);
let monerod_log = dir.join("monerod.argv");
let rpc_log = dir.join("wallet-rpc.argv");
let datadir = dir.join("monerod-data");
let child = WalletChild::new(
local_source(&dir, fake_bin(&dir, "monerod", &monerod_log)),
dir.join("wallet"),
None,
)
.unwrap()
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
let client = child.start(&store).unwrap().expect("enabled child");
assert!(child.running(), "children must be tracked");
let monerod_argv = wait_for_argv(&monerod_log);
assert!(
monerod_argv
.windows(2)
.any(|w| w[0] == "--data-dir" && w[1] == datadir.display().to_string()),
"{monerod_argv:?}"
);
let rpc_argv = wait_for_argv(&rpc_log);
assert!(
rpc_argv.iter().any(|a| a == "--rpc-bind-ip"),
"{rpc_argv:?}"
);
assert!(rpc_argv.iter().any(|a| a == "127.0.0.1"), "{rpc_argv:?}");
assert!(rpc_argv.iter().any(|a| a == "--rpc-login"), "{rpc_argv:?}");
assert!(rpc_argv.iter().any(|a| a == "--wallet-dir"), "{rpc_argv:?}");
assert!(
rpc_argv.windows(2).any(|w| w[0] == "--daemon-address"),
"{rpc_argv:?}"
);
assert!(
!rpc_argv.iter().any(|a| a == "--trusted-daemon"),
"{rpc_argv:?}"
);
// The wallet client is the generated loopback URL, and it carries the
// same login the child was spawned with.
let url = client.url().to_string();
assert!(url.starts_with("http://"), "{url}");
assert!(url.contains("@127.0.0.1:"), "{url}");
let login_arg = rpc_argv
.iter()
.position(|a| a == "--rpc-login")
.map(|i| rpc_argv[i + 1].clone())
.expect("login");
let (user, pass) = login_arg.split_once(':').expect("user:pass");
assert_ne!(user, pass, "user and password must be independent");
assert!(
url.contains(user) && url.contains(pass),
"{url} vs {login_arg}"
);
// Creds live sealed in the store, and nothing in the wallet dir holds
// them in the clear.
let sealed = store.load_wallet_child().unwrap().expect("sealed creds");
assert!(sealed.contains(user));
for entry in fs::read_dir(child.wallet_dir()).unwrap() {
let path = entry.unwrap().path();
let body = fs::read(&path).unwrap_or_default();
assert!(
!body.windows(pass.len()).any(|w| w == pass.as_bytes()),
"{} holds the RPC password in the clear",
path.display()
);
}
child.stop().unwrap();
assert!(!child.running(), "stop must kill both children");
child.stop().unwrap(); // idempotent
assert!(child.start(&store).is_ok(), "restart after stop");
child.stop().unwrap();
}
#[test]
fn creds_are_stable_across_restarts_and_never_regenerated() {
let dir = tmp_dir("creds");
let store = open_store(&dir);
let rpc_log = dir.join("wallet-rpc.argv");
let child = WalletChild::new(
ChainSource::Remote {
host: "node.example.com".into(),
port: 18089,
},
dir.join("wallet"),
None,
)
.unwrap()
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
let first = child.start(&store).unwrap().unwrap().url().to_string();
child.stop().unwrap();
let second = child.start(&store).unwrap().unwrap().url().to_string();
child.stop().unwrap();
// Same login, different random port: the creds persist in the store
// instead of being regenerated per launch.
assert_eq!(login_of(&first), login_of(&second), "creds must persist");
assert!(first.contains("127.0.0.1"), "{first}");
}
/// `http://user:[email protected]:port/json_rpc` -> `user:pass`.
fn login_of(url: &str) -> String {
let rest = url.strip_prefix("http://").expect("http url");
rest.split('@').next().expect("userinfo").to_string()
}
#[test]
fn pick_port_is_free_loopback_and_bindable() {
let port = WalletChild::pick_port().unwrap();
assert!(port > 0);
let listener = std::net::TcpListener::bind(format!("127.0.0.1:{port}")).unwrap();
drop(listener);
}
#[test]
fn stop_without_start_is_a_noop() {
let dir = tmp_dir("stop");
let child = WalletChild::new(ChainSource::None, dir.join("wallet"), None).unwrap();
child.stop().unwrap();
assert!(!child.running());
assert!(!child.child_exited());
}
#[test]
fn wallet_dir_is_created_0700() {
let dir = tmp_dir("perm");
let wallet_dir = dir.join("wallet");
let _ = WalletChild::new(ChainSource::None, wallet_dir.clone(), None).unwrap();
let mode = fs::metadata(&wallet_dir).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o700, "wallet dir must be 0700");
}
}