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