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 {} /// Is this failure "the wallet RPC is not answering yet"? That is the one class /// a retry can fix — a freshly spawned `monero-wallet-rpc` binds its port a /// moment after `spawn` returns. Everything else (a refused passphrase, a /// protocol error) is the RPC's own answer and retrying it would only repeat it. /// /// Deliberately *not* the timeout: a hung child is not a start in progress. /// /// The free function is the rule itself: a status row keeps an already /// formatted `String`, and it must apply exactly the same test to it. pub fn error_is_unreachable(msg: &str) -> bool { msg.starts_with("wallet connect:") || msg.starts_with("wallet write:") } impl Error { /// [`error_is_unreachable`], on this error's own message. pub fn is_unreachable(&self) -> bool { error_is_unreachable(self.0.as_str()) } } /// Which Monero network an on-device daemon follows. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ChainNetwork { Mainnet, Testnet, } impl ChainNetwork { /// Cuprate TOML `network = "..."` spelling (`Mainnet` / `Testnet`). pub fn cuprate_toml(self) -> &'static str { match self { Self::Mainnet => "Mainnet", Self::Testnet => "Testnet", } } /// Directory segment so mainnet and testnet stores never share a fjall dir. pub fn dir_name(self) -> &'static str { match self { Self::Mainnet => "mainnet", Self::Testnet => "testnet", } } } /// 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, /// `monerod --prune-blockchain`. Full node when false. prune: bool, }, /// A chain daemon **inside this process** (Cuprate), with its chain in /// `datadir`. Nothing is spawned; the wallet child still dials loopback /// RPC, so this is a [`ChainSource::Local`] with a different owner. /// /// Cuprate is still pre-production: mainnet RPC parity is unvalidated. /// The UI must say so. `network`/`prune` are the user's choice; old /// stored records without those keys are testnet, unpruned. InProcessCuprate { /// Data directory for the daemon's chain database. datadir: PathBuf, network: ChainNetwork, prune: bool, }, /// 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, }, } impl ChainSource { /// Does this source name a Tor onion service? Only a `.onion` daemon needs /// the SOCKS child; a loopback or clearnet host the user typed does not. pub fn is_onion(&self) -> bool { match self { ChainSource::Remote { host, .. } => is_onion_host(host), _ => false, } } /// Short label for a status line: what the wallet child is dialling. pub fn label(&self) -> String { match self { ChainSource::None => "receive-only".to_string(), ChainSource::Local { prune: true, .. } => "local pruned node".to_string(), ChainSource::Local { prune: false, .. } => "local full node".to_string(), ChainSource::InProcessCuprate { network: ChainNetwork::Mainnet, prune: true, .. } => "in-process mainnet pruned".to_string(), ChainSource::InProcessCuprate { network: ChainNetwork::Mainnet, prune: false, .. } => "in-process mainnet full".to_string(), ChainSource::InProcessCuprate { network: ChainNetwork::Testnet, .. } => "in-process testnet".to_string(), ChainSource::Remote { host, .. } if is_onion_host(host) => { "remote onion daemon".to_string() } ChainSource::Remote { .. } => "remote daemon".to_string(), } } } /// Does this host name a Tor onion service? Case-insensitive, and it needs the /// suffix — `notonion.example` is not one. pub fn is_onion_host(host: &str) -> bool { host.trim().to_ascii_lowercase().ends_with(".onion") } /// 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, /// The passphrase that opens the wallet *file* the child is pointed at /// ([`Wallet::open_wallet`]). Sealed at rest beside `rpc_login`; empty when /// this install has never been told one (a wallet that predates the field, /// or a remote-mode wallet the user runs themselves). /// /// Keeping it is deliberate: it makes the store passphrase sufficient to /// spend, and it is why the app can reopen a wallet file across a restart /// at all — `monero-wallet-rpc` holds an open file only for the life of the /// process, and re-opening it needs the passphrase. See /// `docs/THREAT_MODEL.md`. pub wallet_passphrase: Zeroizing, } 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, wallet_passphrase: Zeroizing::new(String::new()), } } /// Set the passphrase that opens the wallet file this config's child is /// pointed at. Chainable, and the only way to supply it from outside the /// crate: the field is public too, but a builder keeps a caller from /// forgetting that it is sealed beside the login. pub fn with_wallet_passphrase(mut self, passphrase: &str) -> Self { self.wallet_passphrase = Zeroizing::new(passphrase.to_string()); self } /// 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) .field( "wallet_passphrase", &if self.wallet_passphrase.is_empty() { "" } else { "" }, ) .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 && self.wallet_passphrase.as_str() == other.wallet_passphrase.as_str() } } 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() } } /// The private keys of the wallet file the RPC currently has open. /// /// `view_key` is the private view key; `spend_key` is the private spend key and /// is `None` — not an error — for a view-only wallet, which has no spend key to /// hand out. Both are secrets: never log them, never persist them, and never put /// them in an error string. pub struct WalletKeys { pub view_key: String, pub spend_key: Option, } /// Hand-written so a stray `{:?}` cannot print a private key. impl std::fmt::Debug for WalletKeys { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("WalletKeys") .field("view_key", &"") .field("spend_key", &self.spend_key.as_ref().map(|_| "")) .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, } /// The `get_info` fields one wallet-RPC probe carries: the readiness verdict and /// the numbers a status line shows. `0` height/target means the wallet RPC /// answered without a number — unknown, never "caught up", and never a percent. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ChainInfo { /// The wallet RPC said `synchronized: true`. A missing field is `false`. pub synchronized: bool, /// Blocks the wallet's daemon has, as the wallet RPC reports them. pub height: u64, /// Blocks that daemon is syncing towards; `0` when it reported none. pub target_height: u64, } impl ChainInfo { /// The readiness predicate: the daemon reached the tip and the wallet /// scanned up to it. `synchronized` must be explicitly true, and a chain /// with no height is not ready. pub fn ready(&self) -> bool { self.synchronized && self.height > 0 && (self.target_height == 0 || self.height >= self.target_height) } } /// 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, // Not known here: the passphrase is the *file's*, and this builds // the config of the RPC endpoint in use. Callers that persist a // config do a read-modify-write so the stored one survives. wallet_passphrase: Zeroizing::new(String::new()), }) } /// 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 { Ok(self.chain_info().await?.ready()) } /// One `get_info` round trip, carrying both the readiness fields and the /// numbers a status line shows — the status line and the spend gate ask the /// same question, so they ask it once. `0` height/target means the wallet /// RPC answered without a number: unknown, never "caught up". pub async fn chain_info(&self) -> Result { let v = self.chain_rpc("get_info", serde_json::json!({})).await?; Ok(ChainInfo { synchronized: v .get("synchronized") .and_then(|b| b.as_bool()) .unwrap_or(false), height: v.get("height").and_then(|h| h.as_u64()).unwrap_or(0), target_height: v.get("target_height").and_then(|h| h.as_u64()).unwrap_or(0), }) } /// 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") } /// Open a wallet *file* on the RPC (`open_wallet`). /// /// `monero-wallet-rpc` starts with no wallet open, and `create_wallet` / /// `restore_deterministic_wallet` leave theirs open for that process only: /// after a restart every read answers `-13 No wallet file` even though the /// file is on disk. This is the call that opens it, and the only way a /// wallet survives the child being restarted. /// /// The passphrase travels in the JSON-RPC body, never on the argv: `ps` is /// world-readable for the same user, and `--wallet-file`/`--password` /// would put the secret there. `filename` is a name inside the child's /// `--wallet-dir`, never a path. /// /// A wrong passphrase is the RPC's own error (the daemon does not open a /// file it cannot decrypt); it is surfaced as-is, never retried into a /// generic failure by the caller. pub async fn open_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( "open_wallet", serde_json::json!({ "filename": filename, "password": password, }), ) .await?; Ok(()) } /// Re-read the seed of the wallet file the RPC has open (`query_key /// mnemonic`). After `create_wallet` this is the **only** way to recover a /// created wallet's seed, so the UI can offer a backup action instead of /// showing it once. It needs an open, spend-capable wallet file; a /// watch-only one answers the RPC's `-29` and surfaces as the view-only /// refusal. /// /// The returned words are a spend key: never log them, never store them, /// and never put them in an error string. pub async fn mnemonic(&self) -> Result { if !self.configured() { return Err(Error(NOT_CONFIGURED_MSG.into())); } let v = self .rpc("query_key", serde_json::json!({"key_type": "mnemonic"})) .await?; json_str(&v, "key") } /// The wallet file's private keys, as the RPC reports them: `query_key` /// `view_key` and `query_key` `spend_key`. /// /// Both come from the wallet file the child currently has **open** — this is /// not a "read any saved wallet's keys" accessor, and it cannot be: the RPC /// only ever answers for its open file. /// /// A view-only wallet has no spend key: its `query_key spend_key` answers /// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (-29), which maps to /// `spend_key: None` rather than an error, matching the `-29` view-only /// detection the transfer probe already uses. Refuses locally, before any /// dial, when the wallet is not configured. /// /// The two values are spend secrets: never log them, never store them, never /// put them in an error string. [`WalletKeys`]'s `Debug` redacts both. pub async fn keys(&self) -> Result { if !self.configured() { return Err(Error(NOT_CONFIGURED_MSG.into())); } let v = self .rpc("query_key", serde_json::json!({"key_type": "view_key"})) .await?; let view_key = json_str(&v, "key")?; // Asked second and separately: on a view-only wallet this is the call // that carries the `-29`, and `None` is the honest answer there. let spend_key = match self .rpc("query_key", serde_json::json!({"key_type": "spend_key"})) .await { Ok(v) => Some(json_str(&v, "key")?), Err(e) if e.to_string() == VIEW_ONLY_MSG => None, Err(e) => return Err(e), }; Ok(WalletKeys { view_key, spend_key, }) } /// Import an existing wallet from its 25-word seed. This is the only path /// that takes a user-supplied secret. /// /// `seed_offset` is Monero's optional seed-offset passphrase: a second spend /// secret mixed into the seed at restore time, so the same words with a /// different offset open a different wallet. It is **not** the wallet-file /// `password`; it is never sealed, never stored and never written to an error /// string, and the app cannot tell a "wrong" offset from a right one — the /// RPC succeeds and the wallet is simply a different one. /// /// `None`, empty or whitespace-only leaves `seed_offset` out of the request /// entirely (never `"seed_offset":""`). Otherwise the ends are trimmed and /// the value is sent beside the seed; interior spaces are kept. pub async fn restore_wallet( &self, filename: &str, password: &str, seed: &str, seed_offset: Option<&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())); } let mut params = serde_json::json!({ "filename": filename, "password": password, "seed": seed, "language": "English" }); if let Some(offset) = seed_offset.map(str::trim).filter(|s| !s.is_empty()) { params["seed_offset"] = serde_json::Value::String(offset.to_string()); } self.rpc("restore_deterministic_wallet", params).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 (challenged, raw) = post_digest(ep, &body, budget).await?; let status = http_status(&raw).unwrap_or(0); if status == 401 { // A digest built from *this* connection's own challenge was // refused, so the login is wrong, not the flow. return Err(Error( "wallet RPC digest rejected (HTTP 401) — the login does not match the child's --rpc-login" .into(), )); } if !challenged && status == 200 { return Err(Error( "wallet RPC requires digest auth (open RPC refused)".into(), )); } 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; /// One loopback connection: ask for the digest challenge, answer it, and hand /// back `(was_challenged, final_response)`. /// /// The retry has to ride the **same socket** as the challenge. epee owns its /// digest state per connection — `http_custom_handler` holds the /// `http_server_auth`, whose session starts with an empty nonce and counter 0, /// and any request without a valid `Authorization` field makes it mint a fresh /// nonce. A retry that opens a new socket presents a nonce that connection never /// issued, so `monero-wallet-rpc` answers 401 again, permanently. That is the /// 401 the TUI and Android showed against a real wallet RPC while a canned mock /// (which replays the challenge on any socket) stayed green. async fn post_digest(ep: &Endpoint, body: &str, budget: Duration) -> Result<(bool, Vec)> { tokio::time::timeout(budget, http_digest(ep, body)) .await .map_err(|_| Error("wallet RPC timed out".into()))? } async fn http_digest(ep: &Endpoint, body: &str) -> Result<(bool, Vec)> { let mut stream = TcpStream::connect((ep.host.as_str(), ep.port)) .await .map_err(|e| Error(format!("wallet connect: {e}")))?; // No `Connection: close` on the challenge: epee closes the socket with the // 401 when the request asks for it, and the retry needs this connection. let req = build_req(ep, body, None, false); stream .write_all(req.as_bytes()) .await .map_err(|e| Error(format!("wallet write: {e}")))?; let raw = read_one_response(&mut stream).await?; let status = http_status(&raw).unwrap_or(0); if status != 401 { return Ok((false, 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 req = build_req(ep, body, Some(&auth), true); stream .write_all(req.as_bytes()) .await .map_err(|e| Error(format!("wallet write: {e}")))?; Ok((true, read_to_eof(&mut stream).await?)) } fn build_req(ep: &Endpoint, body: &str, authorization: Option<&str>, close: bool) -> 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\n", ep.path, body.len() ); if close { req.push_str("Connection: close\r\n"); } 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 } /// Read exactly one HTTP response: its head, then `Content-Length` body bytes. /// epee always emits `Content-Length`, and a keep-alive response never ends in /// EOF — reading to EOF here would hang on a healthy server. async fn read_one_response(stream: &mut TcpStream) -> Result> { let mut buf = Vec::new(); let head_end = loop { if let Some(i) = find_head_end(&buf) { break i; } if !read_more(stream, &mut buf).await? { // Closed before a full head: hand back what arrived, the status-line // parse decides what that means. return Ok(buf); } }; let head = std::str::from_utf8(&buf[..head_end]).unwrap_or_default(); // epee always sends `Content-Length`, but an open (challenge-less) RPC may // not: with no length the body ends at EOF, so keep reading — the cap below // is what stops a server that streams forever. let Some(want) = content_length(head) else { while read_more(stream, &mut buf).await? {} return Ok(buf); }; while buf.len() < head_end + 4 + want { if !read_more(stream, &mut buf).await? { break; } } Ok(buf) } async fn read_to_eof(stream: &mut TcpStream) -> Result> { let mut buf = Vec::new(); while read_more(stream, &mut buf).await? {} Ok(buf) } /// One read into `buf`. `false` means the peer closed. Enforces the shared cap. async fn read_more(stream: &mut TcpStream, buf: &mut Vec) -> Result { let mut tmp = [0u8; 8192]; let n = stream .read(&mut tmp) .await .map_err(|e| Error(format!("wallet read: {e}")))?; if n == 0 { return Ok(false); } 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(true) } fn find_head_end(buf: &[u8]) -> Option { buf.windows(4).position(|w| w == b"\r\n\r\n") } fn content_length(head: &str) -> Option { head.lines().skip(1).find_map(|line| { let (k, v) = line.split_once(':')?; k.eq_ignore_ascii_case("content-length") .then(|| v.trim().parse().ok()) .flatten() }) } 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(), } } // --------------------------------------------------------------------------- // Chain daemon client (the chain side of the RPC layer) // --------------------------------------------------------------------------- // // This is *not* the wallet child: that one is a loopback HTTP Digest RPC. This // one dials the *daemon* the wallet child scans from, and that is the connection // Cuprate changes shape on (`docs/cuprate-launch-spike.md` §Parity gaps, all // three measured by running it): // // * a height above the tip is a **bare HTTP 500 with a zero-byte body**, where // monerod answers a JSON-RPC error object (`TOO_BIG_HEIGHT`); // * `get_info` metrics are not measurements — a placeholder 5 GiB // `database_size`, an empty `version`, `free_space = u64::MAX`, and zero peers // even while blocks are arriving; // * `get_height` is a **URI endpoint**: `{"method":"get_height"}` over // `/json_rpc` is rejected with 422. // // Nothing here parses a peer count, a database size, a free-space figure or a // version string. There is no field for them to land in, so a caller cannot show // a placeholder as a measurement. // // The in-process chain source ([`ChainSource::InProcessCuprate`]) is what makes // these the *local* case rather than a remote corner: it is the daemon this app // starts itself. /// `CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT` in monero's /// `src/rpc/core_rpc_server_error_codes.h`. Cuprate answers the same request /// with a bare HTTP 500 instead, which is why both spellings map to /// [`WalletError::DaemonHeightOutOfRange`]. const TOO_BIG_HEIGHT_CODE: i64 = -2; /// Typed failures of the chain-daemon calls. The wallet-child path above keeps /// its plain string errors; this side distinguishes a *height* failure from /// every other one because that is the answer Cuprate mangles. #[derive(Debug, Clone, PartialEq, Eq)] pub enum WalletError { /// The requested height is above the daemon's tip. Cuprate: bare HTTP 500, /// empty body. monerod: HTTP 200, error code `-2`. DaemonHeightOutOfRange, /// A non-2xx status that is not the height case above. DaemonHttpStatus(u16), /// A JSON-RPC error object we do not special-case. DaemonRpc { /// The `error.code` the daemon sent. code: i64, /// The `error.message` the daemon sent. message: String, }, /// A 2xx answer with no usable body. Carries the address and the reason. DaemonNoBody(String), /// The daemon could not be reached, or the answer could not be read. DaemonTransport(String), } impl WalletError { /// Is this the "height above tip" failure? A caller that just asked for a /// block at an unverified height may retry lower; every other error is a /// different problem. pub fn is_height_out_of_range(&self) -> bool { matches!(self, Self::DaemonHeightOutOfRange) } } impl std::fmt::Display for WalletError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::DaemonHeightOutOfRange => { f.write_str("daemon: height is above its chain tip (not synced that far yet)") } Self::DaemonHttpStatus(code) => write!(f, "daemon: HTTP {code}"), Self::DaemonRpc { code, message } => write!(f, "daemon rpc error {code}: {message}"), Self::DaemonNoBody(msg) | Self::DaemonTransport(msg) => f.write_str(msg), } } } impl std::error::Error for WalletError {} /// What the chain view is allowed to know about a daemon: how far it is and how /// far it is going. Deliberately nothing else — see the section comment. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct DaemonInfo { /// Blocks the daemon has. pub height: u64, /// Blocks it is syncing towards. `0` means it reported none, which is not /// the same as "caught up". pub target_height: u64, } /// Cap on a daemon answer, in bytes. A `get_block` blob is the large case. pub const DAEMON_MAX_BYTES: usize = 8 * 1024 * 1024; /// `get_info` as the chain view needs it: height and target, nothing else. pub async fn daemon_get_info( addr: &str, budget: Duration, ) -> std::result::Result { let body = r#"{"jsonrpc":"2.0","id":"0","method":"get_info"}"#; let request = json_rpc_request(addr, "/json_rpc", body); let (status, raw) = daemon_http(addr, &request, budget).await?; daemon_ok_status(status)?; let json = daemon_json(&raw, addr)?; let result = json .get("result") .ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_info has no result")))?; let height = result .get("height") .and_then(serde_json::Value::as_u64) .ok_or_else(|| { WalletError::DaemonNoBody(format!("{addr}: get_info has no chain height")) })?; let target_height = result .get("target_height") .and_then(serde_json::Value::as_u64) .unwrap_or(0); Ok(DaemonInfo { height, target_height, }) } /// The daemon's tip, over the `get_height` URI endpoint. /// /// Cuprate rejects `{"method":"get_height"}` over `/json_rpc` with 422, and the /// URI endpoint is what monerod has always answered — one spelling works on /// both, so this is the one to use. pub async fn daemon_get_height( addr: &str, budget: Duration, ) -> std::result::Result { let request = uri_request(addr, "GET", "/get_height"); let (status, raw) = daemon_http(addr, &request, budget).await?; if is_server_error(status) { return Err(WalletError::DaemonHeightOutOfRange); } daemon_ok_status(status)?; let json = daemon_json(&raw, addr)?; // Both daemons answer a top-level `height` here; tolerate a jsonrpc // envelope too rather than betting on the shape. json.get("height") .or_else(|| json.get("result").and_then(|r| r.get("height"))) .and_then(serde_json::Value::as_u64) .ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_height has no height"))) } /// One block by height, as raw bytes (the hex `blob` field, decoded). /// /// Not called by the app yet: the wallet's block scan still lives in /// `monero-wallet-rpc`. It exists because the out-of-range answer above is the /// Cuprate behaviour such a scan has to survive, and the mapping belongs with /// the rest of the client. pub async fn daemon_get_block( addr: &str, height: u64, budget: Duration, ) -> std::result::Result, WalletError> { let body = format!( r#"{{"jsonrpc":"2.0","id":"0","method":"get_block","params":{{"height":{height}}}}}"# ); let request = json_rpc_request(addr, "/json_rpc", &body); let (status, raw) = daemon_http(addr, &request, budget).await?; if is_server_error(status) { return Err(WalletError::DaemonHeightOutOfRange); } daemon_ok_status(status)?; let json = daemon_json(&raw, addr)?; let blob = json .get("result") .and_then(|r| r.get("blob")) .and_then(|b| b.as_str()) .ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_block has no blob")))?; hex_decode(blob) .ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_block blob is not hex"))) } /// A bare 5xx is how Cuprate says "no such height" — it carries no body to /// decode, so the *call* decides what it means: height-addressed calls (the two /// above) read it as [`WalletError::DaemonHeightOutOfRange`], everything else /// reads it as a status error. fn is_server_error(status: u16) -> bool { (500..600).contains(&status) } fn daemon_ok_status(status: u16) -> std::result::Result<(), WalletError> { if (200..300).contains(&status) { return Ok(()); } Err(WalletError::DaemonHttpStatus(status)) } fn json_rpc_request(addr: &str, path: &str, body: &str) -> String { format!( "POST {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len() ) } fn uri_request(addr: &str, method: &str, path: &str) -> String { format!( "{method} {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" ) } /// One request, one answer: status code plus body. `Connection: close` and read /// to EOF, so `Content-Length` never has to be trusted. async fn daemon_http( addr: &str, request: &str, budget: Duration, ) -> std::result::Result<(u16, Vec), WalletError> { let mut stream = tokio::time::timeout(budget, TcpStream::connect(addr)) .await .map_err(|_| WalletError::DaemonTransport(format!("{addr}: connect timed out")))? .map_err(|e| WalletError::DaemonTransport(format!("{addr}: {e}")))?; let raw = tokio::time::timeout(budget, async { stream.write_all(request.as_bytes()).await?; let mut buf = Vec::new(); let mut tmp = [0u8; 8192]; loop { let n = stream.read(&mut tmp).await?; if n == 0 { break; } buf.extend_from_slice(&tmp[..n]); if buf.len() >= DAEMON_MAX_BYTES { break; } } Ok::, std::io::Error>(buf) }) .await .map_err(|_| WalletError::DaemonTransport(format!("{addr}: read timed out")))? .map_err(|e| WalletError::DaemonTransport(format!("{addr}: {e}")))?; split_http(&raw) .ok_or_else(|| WalletError::DaemonTransport(format!("{addr}: not an HTTP response"))) } /// Status code and body from a raw HTTP/1.1 response. /// /// Cuprate is axum/hyper: the body arrives `Transfer-Encoding: chunked`, so /// scanning for the outermost braces is not a parse once a blob spans more than /// one chunk. De-chunk here, once, for every call. fn split_http(raw: &[u8]) -> Option<(u16, Vec)> { let (head, body) = match find(raw, b"\r\n\r\n") { Some(at) => (&raw[..at], &raw[at + 4..]), None => { let at = find(raw, b"\n\n")?; (&raw[..at], &raw[at + 2..]) } }; let head = std::str::from_utf8(head).ok()?; let mut lines = head.lines(); let status = lines.next()?.split_whitespace().nth(1)?.parse().ok()?; let chunked = lines.any(|line| { line.split_once(':').is_some_and(|(k, v)| { k.eq_ignore_ascii_case("transfer-encoding") && v.to_ascii_lowercase().contains("chunked") }) }); let body = if chunked { dechunk(body)? } else { body.to_vec() }; Some((status, body)) } fn dechunk(body: &[u8]) -> Option> { let mut out = Vec::new(); let mut at = 0; loop { let line_end = find(&body[at..], b"\r\n")?; let size_line = std::str::from_utf8(&body[at..at + line_end]).ok()?; // `size[;chunk-extension]` let size = usize::from_str_radix(size_line.split(';').next()?.trim(), 16).ok()?; at += line_end + 2; if size == 0 { return Some(out); } if at + size > body.len() { return None; } out.extend_from_slice(&body[at..at + size]); at += size; if body[at..].starts_with(b"\r\n") { at += 2; } else if body[at..].starts_with(b"\n") { at += 1; } } } fn find(haystack: &[u8], needle: &[u8]) -> Option { haystack.windows(needle.len()).position(|w| w == needle) } fn daemon_json(body: &[u8], addr: &str) -> std::result::Result { let text = std::str::from_utf8(body) .map_err(|_| WalletError::DaemonNoBody(format!("{addr}: body is not UTF-8")))?; let json: serde_json::Value = serde_json::from_str(text.trim()) .map_err(|e| WalletError::DaemonNoBody(format!("{addr}: {e}")))?; if let Some(err) = json.get("error") { let code = err .get("code") .and_then(serde_json::Value::as_i64) .unwrap_or(0); if code == TOO_BIG_HEIGHT_CODE { return Err(WalletError::DaemonHeightOutOfRange); } let message = err .get("message") .and_then(|m| m.as_str()) .unwrap_or("rpc error") .to_string(); return Err(WalletError::DaemonRpc { code, message }); } Ok(json) } fn hex_decode(s: &str) -> Option> { let bytes = s.as_bytes(); if !bytes.len().is_multiple_of(2) { return None; } let mut out = Vec::with_capacity(bytes.len() / 2); for pair in bytes.chunks(2) { out.push((hex_val(pair[0])? << 4) | hex_val(pair[1])?); } Some(out) } fn hex_val(c: u8) -> Option { match c { b'0'..=b'9' => Some(c - b'0'), b'a'..=b'f' => Some(c - b'a' + 10), b'A'..=b'F' => Some(c - b'A' + 10), _ => None, } }