onionwire/src/wallet.rs

764 lines
26 KiB
Rust
Raw Normal View History

wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
use std::path::PathBuf;
use std::time::Duration;
use rand::RngCore;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use zeroize::Zeroizing;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub struct Error(String);
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::error::Error for Error {}
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// 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,
port: u16,
path: String,
user: String,
pass: Zeroizing<String>,
}
impl std::fmt::Debug for Endpoint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Endpoint")
.field("host", &self.host)
.field("port", &self.port)
.field("path", &self.path)
.field("user", &self.user)
.field("pass", &"<redacted>")
.finish()
}
}
#[derive(Debug, Clone)]
pub struct Wallet {
endpoint: Option<Endpoint>,
no_spend: bool,
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// 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
/// `ONIONWIRE_WALLET_NO_SPEND=1` switch and for a view-only wallet detected over
/// RPC, so the operator never has to guess which one it was.
const VIEW_ONLY_MSG: &str = "wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work";
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// What a 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;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransferRow {
pub txid: String,
pub amount: String,
pub address: String,
}
/// Wallet file name used for in-app create/import (`--wallet-dir` on the RPC).
pub const DEFAULT_WALLET_FILENAME: &str = "onionwire";
/// Shown before a spend-capable create. Not a tooltip — the user must confirm.
pub const SPEND_AUTHORITY_WARNING: &str = "this wallet file can spend. anyone with its passphrase or the RPC creds can move the balance. write down the seed. do not leave it on a box you do not trust.";
const RPC_TIMEOUT: Duration = Duration::from_secs(5);
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// 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 {
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// The one place the budgets are defaulted. Callers adjust them with
/// [`Wallet::with_timeouts`].
fn new(endpoint: Option<Endpoint>, no_spend: bool) -> Self {
Self {
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
endpoint,
no_spend,
timeout_local: RPC_TIMEOUT,
timeout_chain: CHAIN_RPC_TIMEOUT,
}
}
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
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.
pub fn from_env() -> Self {
let no_spend = env_flag("ONIONWIRE_WALLET_NO_SPEND");
match std::env::var("ONIONWIRE_WALLET_RPC") {
// The URL can carry `user:pass@` in its userinfo: keep it in a
// wiping buffer, not a bare `String`.
Ok(s) if !s.trim().is_empty() => {
let url = Zeroizing::new(s);
let login = std::env::var("ONIONWIRE_WALLET_RPC_LOGIN")
.ok()
.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())) {
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
Ok(endpoint) => Self::new(Some(endpoint), no_spend),
Err(e) => {
eprintln!("ONIONWIRE_WALLET_RPC: {e}");
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
Self::new(None, no_spend)
}
}
}
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
_ => Self::new(None, no_spend),
}
}
pub fn from_url(url: &str) -> Result<Self> {
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
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`.
pub fn with_no_spend(mut self, on: bool) -> Self {
self.no_spend = on;
self
}
pub fn no_spend(&self) -> bool {
self.no_spend
}
pub fn configured(&self) -> bool {
self.endpoint.is_some()
}
pub async fn get_address(&self) -> Result<String> {
let v = self
.rpc("get_address", serde_json::json!({"account_index": 0}))
.await?;
json_str(&v, "address")
}
pub async fn create_address(&self) -> Result<String> {
let v = self
.rpc("create_address", serde_json::json!({"account_index": 0}))
.await?;
json_str(&v, "address")
}
pub async fn transfer(&self, address: &str, amount: u64) -> Result<String> {
if self.no_spend {
return Err(Error(VIEW_ONLY_MSG.into()));
}
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
// 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
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
.chain_rpc(
"transfer",
serde_json::json!({
"destinations": [{"amount": amount, "address": address}],
"account_index": 0
}),
)
.await;
let v = match sent {
Ok(v) => v,
// The wallet's own refusal is opaque, so ask the documented
// pre-transfer signal before surfacing it. Fail closed: if the
// probe cannot answer, the original error stands.
Err(e) => {
if self.view_only().await {
return Err(Error(VIEW_ONLY_MSG.into()));
}
return Err(e);
}
};
json_str(&v, "tx_hash")
}
/// View-only detection over RPC: `query_key` with `key_type=spend_key` is
/// the signal monero actually exposes for a wallet with no spend key.
/// A view-only wallet answers `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (-29)
/// ("Cannot retrieve spend key"); a spend-capable wallet returns the key,
/// which this discards.
/// Source: `src/wallet/wallet_rpc_server.cpp` `on_query_key`.
async fn view_only(&self) -> bool {
matches!(
self.rpc("query_key", serde_json::json!({"key_type": "spend_key"}))
.await,
Err(e) if e.to_string() == VIEW_ONLY_MSG
)
}
pub async fn get_transfers(&self) -> Result<Vec<TransferRow>> {
let v = self
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
.chain_rpc(
"get_transfers",
serde_json::json!({"in": true, "pending": true}),
)
.await?;
let mut out = Vec::new();
for key in ["in", "pending"] {
if let Some(arr) = v.get(key).and_then(|x| x.as_array()) {
for item in arr {
out.push(TransferRow {
txid: json_str(item, "txid").unwrap_or_default(),
amount: json_amount(item),
address: json_str(item, "address").unwrap_or_default(),
});
}
}
}
Ok(out)
}
/// Monero-wallet-rpc `get_balance`, account_index 0. Returns the "balance"
/// field as a piconero string on success; the caller can format it with
/// `pay::atomic_to_xmr_str` if it wants a human-readable form.
pub async fn get_balance(&self) -> Result<String> {
let v = self
.rpc("get_balance", serde_json::json!({"account_index": 0}))
.await?;
json_str(&v, "balance")
}
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// 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
/// screen. Needs `--wallet-dir` on the RPC.
pub async fn create_wallet(&self, filename: &str, password: &str) -> Result<String> {
let filename = filename.trim();
if filename.is_empty() {
return Err(Error("wallet filename required".into()));
}
if password.is_empty() {
return Err(Error("wallet passphrase required".into()));
}
self.rpc(
"create_wallet",
serde_json::json!({
"filename": filename,
"password": password,
"language": "English"
}),
)
.await?;
let v = self
.rpc("query_key", serde_json::json!({"key_type": "mnemonic"}))
.await
.map_err(|e| {
Error(format!(
"wallet created but seed backup unavailable: {e}"
))
})?;
json_str(&v, "key")
}
/// Import an existing wallet from its 25-word seed. This is the only path
/// that takes a user-supplied secret.
pub async fn restore_wallet(&self, filename: &str, password: &str, seed: &str) -> Result<()> {
let filename = filename.trim();
if filename.is_empty() {
return Err(Error("wallet filename required".into()));
}
if password.is_empty() {
return Err(Error("wallet passphrase required".into()));
}
let seed = seed.trim();
if seed.is_empty() {
return Err(Error("seed required to import a wallet".into()));
}
self.rpc(
"restore_deterministic_wallet",
serde_json::json!({
"filename": filename,
"password": password,
"seed": seed,
"language": "English"
}),
)
.await?;
Ok(())
}
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// 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> {
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
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()
.ok_or_else(|| Error("not configured".into()))?;
let body = serde_json::json!({
"jsonrpc": "2.0",
"id": "0",
"method": method,
"params": params,
})
.to_string();
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
let 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(
"wallet RPC requires digest auth (open RPC refused)".into(),
));
}
if status != 401 {
return parse_json_rpc(&raw);
}
let challenge = www_authenticate(&raw).ok_or_else(|| {
Error("wallet RPC digest required (--rpc-login / HTTP Digest)".into())
})?;
if !challenge.trim().to_ascii_lowercase().starts_with("digest") {
return Err(Error(
"wallet RPC digest required (--rpc-login / HTTP Digest)".into(),
));
}
let auth = digest_authorization(ep, &challenge)?;
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
let raw = post_timeout(ep, &build_req(ep, &body, Some(&auth)), budget).await?;
parse_json_rpc(&raw)
}
}
pub fn transfers_match(rows: &[TransferRow], txid: &str, amount: &str, address: &str) -> bool {
if txid.is_empty() || amount.is_empty() || address.is_empty() {
return false;
}
rows.iter()
.any(|r| r.txid == txid && r.amount == amount && r.address == address)
}
fn credentials_required() -> Error {
Error("wallet RPC requires credentials (user:pass in URL or ONIONWIRE_WALLET_RPC_LOGIN)".into())
}
/// `1` / `true` / `yes` / `on` (case-insensitive) mean set; anything else (or
/// unset) means off.
fn env_flag(name: &str) -> bool {
matches!(
std::env::var(name)
.map(|v| v.trim().to_ascii_lowercase())
.as_deref(),
Ok("1" | "true" | "yes" | "on")
)
}
fn parse_login(login: &str) -> Result<(String, Zeroizing<String>)> {
let (user, pass) = login.split_once(':').ok_or_else(credentials_required)?;
if user.is_empty() || pass.is_empty() {
return Err(credentials_required());
}
Ok((user.to_string(), Zeroizing::new(pass.to_string())))
}
fn parse_http_url(url: &str, extra_login: Option<&str>) -> Result<Endpoint> {
let rest = url
.strip_prefix("http://")
.ok_or_else(|| Error("wallet RPC must be http:// (no TLS)".into()))?;
if rest.contains("://") {
return Err(Error("wallet RPC must be http:// (no TLS)".into()));
}
let (userinfo, rest) = match rest.rsplit_once('@') {
Some((ui, hostpart)) => (Some(ui), hostpart),
None => (None, rest),
};
let (user, pass) = match userinfo {
Some(ui) => parse_login(ui)?,
None => match extra_login {
Some(login) => parse_login(login)?,
None => return Err(credentials_required()),
},
};
let (hostport, path) = match rest.split_once('/') {
Some((hp, p)) => (hp, format!("/{p}")),
None => (rest, "/json_rpc".into()),
};
let path = if path == "/" {
"/json_rpc".into()
} else {
path
};
let (host, port) = parse_hostport(hostport)?;
if host.trim().to_ascii_lowercase().ends_with(".onion") {
return Err(Error(
"wallet RPC over .onion is not supported (loopback only; no Arti dial)".into(),
));
}
if !allowed_host(&host) {
return Err(Error("wallet RPC host must be loopback".into()));
}
Ok(Endpoint {
host,
port,
path,
user,
pass,
})
}
fn parse_hostport(hostport: &str) -> Result<(String, u16)> {
if let Some(rest) = hostport.strip_prefix('[') {
let (host, rest) = rest
.split_once(']')
.ok_or_else(|| Error("invalid IPv6 host".into()))?;
let port = match rest.strip_prefix(':') {
Some(p) if !p.is_empty() => parse_port(p)?,
_ => 18083,
};
if host.is_empty() {
return Err(Error("empty host".into()));
}
return Ok((host.to_string(), port));
}
match hostport.rsplit_once(':') {
Some((h, p)) if !h.is_empty() && !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) => {
Ok((h.to_string(), parse_port(p)?))
}
_ if !hostport.is_empty() => Ok((hostport.to_string(), 18083)),
_ => Err(Error("empty host".into())),
}
}
fn parse_port(p: &str) -> Result<u16> {
p.parse()
.map_err(|_| Error("invalid wallet RPC port".into()))
}
fn allowed_host(host: &str) -> bool {
let h = host.trim();
if h.eq_ignore_ascii_case("localhost") {
return true;
}
h.parse::<std::net::IpAddr>()
.map(|ip| ip.is_loopback())
.unwrap_or(false)
}
fn host_header(host: &str, port: u16) -> String {
if host.contains(':') {
format!("[{host}]:{port}")
} else {
format!("{host}:{port}")
}
}
const MAX_RPC_BYTES: usize = 1024 * 1024;
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
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()))?
}
fn build_req(ep: &Endpoint, body: &str, authorization: Option<&str>) -> String {
let host_hdr = host_header(&ep.host, ep.port);
let mut req = format!(
"POST {} HTTP/1.1\r\nHost: {host_hdr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n",
ep.path,
body.len()
);
if let Some(auth) = authorization {
req.push_str("Authorization: ");
req.push_str(auth);
req.push_str("\r\n");
}
req.push_str("\r\n");
req.push_str(body);
req
}
async fn http_post(ep: &Endpoint, req: &[u8]) -> Result<Vec<u8>> {
let mut stream = TcpStream::connect((ep.host.as_str(), ep.port))
.await
.map_err(|e| Error(format!("wallet connect: {e}")))?;
stream
.write_all(req)
.await
.map_err(|e| Error(format!("wallet write: {e}")))?;
let mut buf = Vec::new();
let mut tmp = [0u8; 8192];
loop {
let n = stream
.read(&mut tmp)
.await
.map_err(|e| Error(format!("wallet read: {e}")))?;
if n == 0 {
break;
}
if buf.len().saturating_add(n) > MAX_RPC_BYTES {
return Err(Error("wallet RPC response too large".into()));
}
buf.extend_from_slice(&tmp[..n]);
}
Ok(buf)
}
fn http_status(raw: &[u8]) -> Option<u16> {
let text = std::str::from_utf8(raw).ok()?;
let line = text.lines().next()?;
let mut parts = line.split_whitespace();
let _http = parts.next()?;
parts.next()?.parse().ok()
}
fn www_authenticate(raw: &[u8]) -> Option<String> {
let text = std::str::from_utf8(raw).ok()?;
let (head, _) = text
.split_once("\r\n\r\n")
.or_else(|| text.split_once("\n\n"))?;
for line in head.lines().skip(1) {
let (k, v) = match line.split_once(':') {
Some(kv) => kv,
None => continue,
};
if k.eq_ignore_ascii_case("www-authenticate") {
return Some(v.trim().to_string());
}
}
None
}
fn digest_param(challenge: &str, key: &str) -> Option<String> {
let t = challenge.trim();
let rest = if t.len() >= 6 && t[..6].eq_ignore_ascii_case("digest") {
t[6..].trim()
} else {
return None;
};
for part in rest.split(',') {
let part = part.trim();
let (k, v) = match part.split_once('=') {
Some(kv) => kv,
None => continue,
};
if k.eq_ignore_ascii_case(key) {
return Some(v.trim().trim_matches('"').to_string());
}
}
None
}
fn md5_hex(s: &str) -> String {
use md5::{Digest, Md5};
hex_lower(&Md5::digest(s.as_bytes()))
}
fn hex_lower(bytes: &[u8]) -> String {
const H: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for &b in bytes {
out.push(H[(b >> 4) as usize] as char);
out.push(H[(b & 0xf) as usize] as char);
}
out
}
fn digest_authorization(ep: &Endpoint, challenge: &str) -> Result<String> {
if let Some(alg) = digest_param(challenge, "algorithm")
&& !alg.eq_ignore_ascii_case("MD5")
{
return Err(Error("wallet RPC digest algorithm not MD5".into()));
}
let realm = digest_param(challenge, "realm").unwrap_or_default();
let nonce = digest_param(challenge, "nonce")
.ok_or_else(|| Error("wallet RPC digest required (--rpc-login / HTTP Digest)".into()))?;
let qop = digest_param(challenge, "qop");
// `user:realm:password` never leaves a bare `String` behind.
let pw_input = Zeroizing::new(format!("{}:{realm}:{}", ep.user, ep.pass.as_str()));
let ha1 = md5_hex(pw_input.as_str());
let ha2 = md5_hex(&format!("POST:{}", ep.path));
let (qop_part, resp) = if qop
.as_deref()
.is_some_and(|q| q.split(',').any(|x| x.trim() == "auth"))
{
let mut cnonce_bytes = [0u8; 8];
rand::thread_rng().fill_bytes(&mut cnonce_bytes);
let cnonce = hex_lower(&cnonce_bytes);
let nc = "00000001";
let response = md5_hex(&format!("{ha1}:{nonce}:{nc}:{cnonce}:auth:{ha2}"));
(
format!(", qop=auth, nc={nc}, cnonce=\"{cnonce}\""),
response,
)
} else {
(String::new(), md5_hex(&format!("{ha1}:{nonce}:{ha2}")))
};
Ok(format!(
"Digest username=\"{}\", realm=\"{realm}\", nonce=\"{nonce}\", uri=\"{}\", algorithm=MD5, response=\"{resp}\"{qop_part}",
ep.user, ep.path
))
}
fn parse_json_rpc(raw: &[u8]) -> Result<serde_json::Value> {
let text = std::str::from_utf8(raw).map_err(|_| Error("wallet RPC not UTF-8".into()))?;
let (head, body) = text
.split_once("\r\n\r\n")
.or_else(|| text.split_once("\n\n"))
.ok_or_else(|| Error("wallet RPC truncated".into()))?;
let status = head.lines().next().unwrap_or("");
if status.contains(" 3") {
return Err(Error("wallet RPC redirect refused".into()));
}
if !status.contains(" 200 ") && !status.ends_with(" 200") {
return Err(Error(format!("wallet RPC HTTP {status}")));
}
let json: serde_json::Value =
serde_json::from_str(body.trim()).map_err(|e| Error(format!("wallet RPC json: {e}")))?;
if let Some(err) = json.get("error") {
let msg = err
.get("message")
.and_then(|m| m.as_str())
.unwrap_or("rpc error");
// The one RPC-level error we translate: a view-only wallet has no
// spend key (monero `WALLET_RPC_ERROR_CODE_WATCH_ONLY`).
if err.get("code").and_then(|c| c.as_i64()) == Some(WATCH_ONLY_CODE) {
return Err(Error(VIEW_ONLY_MSG.into()));
}
return Err(Error(msg.into()));
}
json.get("result")
.cloned()
.ok_or_else(|| Error("wallet RPC missing result".into()))
}
fn json_str(v: &serde_json::Value, key: &str) -> Result<String> {
v.get(key)
.and_then(|x| x.as_str())
.map(str::to_string)
.ok_or_else(|| Error(format!("wallet RPC missing {key}")))
}
fn json_amount(v: &serde_json::Value) -> String {
match v.get("amount") {
Some(serde_json::Value::Number(n)) => n
.as_u64()
.map(|x| x.to_string())
.or_else(|| n.as_i64().map(|x| x.to_string()))
.unwrap_or_default(),
Some(serde_json::Value::String(s)) => s.clone(),
_ => String::new(),
}
}