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 = std::result::Result; #[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 {} /// 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, }, } /// Remote-mode wallet config: the `monero-wallet-rpc` the user already runs /// themselves (F7 sets it, the store keeps it, env is the migration path). /// /// `rpc_url` never carries `user:pass` — that is `rpc_login`, which stays in a /// wiping buffer and is sealed at rest. This is the same three fields /// `ONIONWIRE_WALLET_RPC` / `ONIONWIRE_WALLET_RPC_LOGIN` / /// `ONIONWIRE_WALLET_NO_SPEND` describe. #[derive(Clone)] pub struct WalletConfig { /// `http://host:port[/path]`. Loopback-only enforcement stays in /// [`parse_http_url`]. pub rpc_url: String, /// `user:pass`. Never logged, never in a status line, never on disk in the /// clear. pub rpc_login: Zeroizing, /// View-only deployment: `/tip` is refused locally, before any dial. pub no_spend: bool, } impl WalletConfig { pub fn new(rpc_url: &str, rpc_login: &str, no_spend: bool) -> Self { Self { rpc_url: rpc_url.trim().to_string(), rpc_login: Zeroizing::new(rpc_login.trim().to_string()), no_spend, } } /// The password half of `user:pass` (the whole string when there is no /// colon), for redaction. Never rendered anywhere. pub fn secret(&self) -> &str { match self.rpc_login.split_once(':') { Some((_, pass)) => pass, None => self.rpc_login.as_str(), } } } /// Redacted on purpose: a `Debug` that prints the login turns any `{:?}` — /// a log line, a panic message, an assert — into a credential leak. impl std::fmt::Debug for WalletConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("WalletConfig") .field("rpc_url", &self.rpc_url) .field("rpc_login", &"") .field("no_spend", &self.no_spend) .finish() } } impl PartialEq for WalletConfig { fn eq(&self, other: &Self) -> bool { self.rpc_url == other.rpc_url && self.rpc_login.as_str() == other.rpc_login.as_str() && self.no_spend == other.no_spend } } impl Eq for WalletConfig {} impl Default for WalletConfig { fn default() -> Self { Self::new("", "", false) } } /// The snapshot the TUI draws (main-screen indicator + config-screen status /// line). No dialing, no secrets: `last_error` is already sanitized and short. #[derive(Debug, Clone, PartialEq, Eq)] pub struct WalletStatus { /// A stored or env config resolved to a usable `Wallet`. pub configured: bool, /// The last probe succeeded. **Never** set from config-existence: config is /// not reachability. pub connected: bool, /// The most recent failure, sanitized for display. Cleared on success. pub last_error: Option, /// Human-readable balance, e.g. `123456 piconero`, or `—`. pub balance_line: String, /// The address `/pay` invoices would hand out, or `—`. pub receive_address: String, } /// The `—` the TUI shows for a readout that has no honest value yet. pub const NOT_SET: &str = "—"; impl WalletStatus { /// Configured, never probed: the state right after boot or a save. pub fn idle(configured: bool) -> Self { Self { configured, connected: false, last_error: None, balance_line: NOT_SET.to_string(), receive_address: NOT_SET.to_string(), } } pub fn configured(&self) -> bool { self.configured } pub fn connected(&self) -> bool { self.connected } } /// The config screen's Test-connection result. `status` is the success copy; /// `error` is a short sanitized reason, and it never carries the login. #[derive(Debug, Clone, PartialEq, Eq)] pub struct PingResult { pub ok: bool, /// Short human status, e.g. `connected`, or `not connected` on failure. pub status: String, /// Short sanitized reason on failure, or `None`. pub error: Option, } impl PingResult { /// The TUI's status line: one string, never a secret. pub fn line(&self) -> String { match &self.error { Some(e) => format!("{} · {e}", self.status), None => self.status.clone(), } } } /// Refusal copy for the pay/tip guard. Deterministic: the TUI asserts these /// exact strings. pub const NOT_CONFIGURED_MSG: &str = "wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC"; pub const NOT_CONNECTED_MSG: &str = "wallet not connected — check endpoint, login, daemon"; /// The pay/tip pre-check answer, in the order the guard evaluates it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Readiness { /// Configured, reachable, and (for `/tip`) spend-capable. Ready, /// No stored and no env config. NotConfigured, /// Configured but the probe failed (or there was none). NotConnected, /// `/tip` on a view-only/no-spend wallet. Never a dial. NoSpend, } impl Readiness { /// The refusal copy when the guard rejects, `None` when ready. pub fn refusal(self) -> Option<&'static str> { match self { Readiness::Ready => None, Readiness::NotConfigured => Some(NOT_CONFIGURED_MSG), Readiness::NotConnected => Some(NOT_CONNECTED_MSG), Readiness::NoSpend => Some(VIEW_ONLY_MSG), } } pub fn is_ready(self) -> bool { matches!(self, Readiness::Ready) } } /// The guard's state table, and the only place its order is decided: /// /// 1. not configured — the copy names the fix (F7, or the env var); /// 2. `/tip` on a no-spend wallet — it can never spend, so it is refused /// before any dial, reachable or not (same rule as `transfer`); /// 3. configured but not connected — check endpoint, login, daemon; /// 4. otherwise ready. `/pay` is fine on a view-only wallet. pub fn readiness(configured: bool, connected: bool, no_spend: bool, is_tip: bool) -> Readiness { if !configured { return Readiness::NotConfigured; } if is_tip && no_spend { return Readiness::NoSpend; } if !connected { return Readiness::NotConnected; } Readiness::Ready } /// Display copy, not a log line: drop the secret if some lower layer put it in /// the message, and keep it short enough for a status line. pub(crate) fn redact(msg: &str, secret: &str) -> String { let mut out = msg.trim().to_string(); if !secret.is_empty() { out = out.replace(secret, ""); } const MAX: usize = 120; if out.chars().count() > MAX { out = out.chars().take(MAX).collect(); out.push('…'); } out } #[derive(Clone)] struct Endpoint { host: String, port: u16, path: String, user: String, pass: Zeroizing, } 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", &"") .finish() } } #[derive(Debug, Clone)] pub struct Wallet { endpoint: Option, 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 /// `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. The TUI's /// pay/tip guard returns this exact string (see [`Readiness::refusal`]). pub 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; #[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); /// 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 { /// The one place the budgets are defaulted. Callers adjust them with /// [`Wallet::with_timeouts`]. fn new(endpoint: Option, no_spend: bool) -> Self { Self { 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. 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())) { Ok(endpoint) => Self::new(Some(endpoint), no_spend), Err(e) => { eprintln!("ONIONWIRE_WALLET_RPC: {e}"); Self::new(None, no_spend) } } } _ => Self::new(None, no_spend), } } pub fn from_url(url: &str) -> Result { Ok(Self::new(Some(parse_http_url(url, None)?), false)) } /// Build the wallet from stored config. `rpc_url` must be a usable loopback /// `http://` endpoint; the login is required and never echoed in an error. pub fn from_config(cfg: &WalletConfig) -> Result { if cfg.rpc_url.trim().is_empty() { return Err(Error("wallet RPC endpoint required".into())); } let ep = parse_http_url(cfg.rpc_url.trim(), Some(cfg.rpc_login.as_str())) .map_err(|e| Error(redact(&e.to_string(), cfg.secret())))?; Ok(Self::new(Some(ep), cfg.no_spend)) } /// Boot path: stored config wins, env is the migration/fallback path, and /// nothing at all means a disabled wallet (chat still works). /// /// A stored config that cannot be used does not silently dial anything: it /// falls back to env/env-less, so a typo cannot point a spend at a host the /// user did not mean. pub fn for_boot(stored: Option<&WalletConfig>) -> Self { if let Some(cfg) = stored { match Self::from_config(cfg) { Ok(w) => return w, Err(e) => eprintln!("wallet config: {e}"), } } Self::from_env() } /// The config in use, for the F7 screen's prefill. `None` when the wallet /// has no endpoint. The URL is rebuilt without userinfo; the login is the /// secret half. pub fn config(&self) -> Option { let ep = self.endpoint.as_ref()?; Some(WalletConfig { rpc_url: format!("http://{}{}", host_header(&ep.host, ep.port), ep.path), rpc_login: Zeroizing::new(format!("{}:{}", ep.user, ep.pass.as_str())), no_spend: self.no_spend, }) } /// One probe, folded into the snapshot the TUI draws: `get_address` (the /// cheapest call that also proves the RPC has a wallet open) then /// `get_balance` for the readout. /// /// This is the freshness rule: `connected` is whatever the *last* probe /// said, never "config exists". A successful probe clears `last_error`; a /// failure sets `connected=false` and keeps `configured=true`. pub async fn status(&self) -> WalletStatus { if !self.configured() { return WalletStatus::idle(false); } match self.get_address().await { Ok(addr) => { let balance = match self.get_balance().await { Ok(b) if !b.trim().is_empty() => format!("{} piconero", b.trim()), _ => NOT_SET.to_string(), }; WalletStatus { configured: true, connected: true, last_error: None, balance_line: balance, receive_address: if addr.trim().is_empty() { NOT_SET.to_string() } else { addr }, } } Err(e) => WalletStatus { configured: true, connected: false, last_error: Some(self.sanitize(&e.to_string())), balance_line: NOT_SET.to_string(), receive_address: NOT_SET.to_string(), }, } } /// One-shot Test-connection probe against an endpoint the user is *typing* /// (not necessarily the stored one). Same rules as every other call: /// loopback only, digest required, no password in the result. pub async fn ping(rpc_url: &str, rpc_login: &str) -> PingResult { let cfg = WalletConfig::new(rpc_url, rpc_login, false); let wallet = match Self::from_config(&cfg) { Ok(w) => w, Err(e) => { return PingResult { ok: false, status: "not connected".into(), error: Some(redact(&e.to_string(), cfg.secret())), }; } }; let st = wallet.status().await; if st.connected { PingResult { ok: true, status: "connected".into(), error: None, } } else { PingResult { ok: false, status: "not connected".into(), error: st.last_error, } } } /// Display-safe copy of an error: no RPC password, short enough for a line. fn sanitize(&self, msg: &str) -> String { let pass = self .endpoint .as_ref() .map(|e| e.pass.as_str()) .unwrap_or(""); redact(msg, pass) } /// 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 { let v = self .rpc("get_address", serde_json::json!({"account_index": 0})) .await?; json_str(&v, "address") } pub async fn create_address(&self) -> Result { 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 { 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 .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> { let v = self .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 { let v = self .rpc("get_balance", serde_json::json!({"account_index": 0})) .await?; json_str(&v, "balance") } /// Unlocked balance in piconero — the part a spend can actually use. pub async fn unlocked_balance(&self) -> Result { let v = self .rpc("get_balance", serde_json::json!({"account_index": 0})) .await?; json_str(&v, "unlocked_balance")? .trim() .parse::() .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 { 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 { 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 { 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(()) } /// 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 { 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 { self.rpc_with(method, params, self.timeout_chain).await } async fn rpc_with( &self, method: &str, params: serde_json::Value, budget: Duration, ) -> Result { 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(); 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)?; 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)> { 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 { 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 { 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::() .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; async fn post_timeout(ep: &Endpoint, req: &str, budget: Duration) -> Result> { 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> { 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 { 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 { 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 { 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 { 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 { 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 { 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(), } }