wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
use std ::path ::PathBuf ;
2026-09-10 14:37:43 -04:00
use std ::time ::Duration ;
2026-09-10 20:17:25 -04:00
use rand ::RngCore ;
2026-09-10 14:37:43 -04:00
use tokio ::io ::{ AsyncReadExt , AsyncWriteExt } ;
use tokio ::net ::TcpStream ;
2026-09-12 13:36:21 -04:00
use zeroize ::Zeroizing ;
2026-09-10 14:37:43 -04:00
pub type Result < T > = std ::result ::Result < T , Error > ;
#[ derive(Debug) ]
pub struct Error ( String ) ;
impl std ::fmt ::Display for Error {
fn fmt ( & self , f : & mut std ::fmt ::Formatter < '_ > ) -> std ::fmt ::Result {
self . 0. fmt ( f )
}
}
impl std ::error ::Error for Error { }
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// The user's choice of where the Monero daemon lives. No default remote node
/// is ever implied — every `Remote` is constructed from explicit user input.
///
/// Wallet RPC is always loopback HTTP Digest. The chain source is what the
/// *wallet child* connects to, not what the messenger dials.
#[ derive(Debug, Clone, PartialEq, Eq) ]
pub enum ChainSource {
/// Receive-only. No wallet child, no daemon, no spend.
None ,
/// Spawn a local `monerod`. Chain traffic stays on the device.
Local {
/// Path to the `monerod` binary.
monerod_bin : PathBuf ,
/// Data directory for the local daemon.
datadir : PathBuf ,
} ,
wallet: land the in-process Cuprate chain source on main
`ChainSource::InProcessCuprate { datadir }` is the fourth chain source: P2P,
consensus and RandomX run inside the OnionWire process instead of as a spawned
`monerod`. The wallet layer does not move — the daemon binds the same loopback
unrestricted RPC (`127.0.0.1:18081`) that `WalletChild::daemon_address` already
returns for a local source, so `wallet_rpc_argv`, the RPC client, the payment
frames and the receipt-verification path are untouched.
- Cargo.toml: `cuprated` (git, rev 4f8fcd1b) + `toml`, both optional, behind the
`cuprate-daemon` feature, OFF by default. `cuprated`'s own `arti` feature is
disabled (`default-features = false`): its arti-client 0.44 cannot unify with
this crate's 0.46, and the in-process daemon is clearnet-only. One Tor stack in
the process. `Cargo.lock` gains the graph; a default build's
`cargo tree --locked -e normal -i cuprated` still says "did not match any
packages", and only `arti-client v0.46.0` is in the lock.
- src/cuprate.rs (new): `CuprateNode` builds the cuprated config as TOML
(testnet, unrestricted RPC on loopback, restricted RPC disabled, inbound P2P
off), launches it on a runtime it owns, and owns the node. `launch` is
synchronous on purpose: `WalletChild::start` is sync (the TUI calls it from its
blocking thread, UniFFI calls it from an async context) and a runtime cannot be
started from inside a runtime, so the launch runs on a thread of its own and
the node + its runtime come back over a channel. Dropping the value asks the
node to shut down and `shutdown_background`s the runtime, which is the only
exit that cannot panic when the value is dropped inside another runtime.
The type exists in every build (feature off: `launch` fails with the feature
name), so the chain-source type, its stored record and its copy do not fork on
a cargo feature.
- src/wallet.rs: the variant, its label (`in-process node`), and the chain-daemon
client the wallet line carried (typed `WalletError`, de-chunked HTTP,
`get_height` over the URI endpoint, an above-the-tip height as one typed
error). Cuprate answers those three differently from monerod and the
in-process source is what makes them the *local* case.
- src/wallet_child.rs: launches/holds/stops the node, `chain_datadir` for the
free-space/ownership question, the honest `chain_copy` line, `kind =
"cuprate"` in the sealed record, and `ChildConfig::validate` for it.
- src/tui.rs: the wallet screen's chain line carries the testnet caveat when the
configured source is the in-process one. It computes the line at draw time, so
`Screen::Wallet`'s shape (which tests construct) does not change.
- docs/WALLET.md, docs/THREAT_MODEL.md, docs/cuprate-android-spike.md: the
feature flag and how to enable it, where the (fjall) chain store lives, the
**measured** +11.8 MiB delta, the pre-production/testnet caveat, and the
in-repo aarch64-linux-android proof with exit codes.
Scope deviations, stated plainly:
- `src/cuprate.rs` and its one `src/lib.rs` module line are not in the card's
allowed list; the card's own deliverable describes the module's behaviour.
- `crates/onionwire-sdk/src/lib.rs` is forbidden, but adding a variant to a
`pub enum` that the SDK matches exhaustively breaks the SDK workspace, and the
root CI `sdk` job runs on every PR. One variant plus two match arms land here
so the SDK keeps compiling (`cargo test --locked` + clippy clean); the SDK card
owns the rest — feature passthrough, the config field's semantics, the label
and its tests, and the Android check.
- `tests/wallet.rs` carries the launch test. `tests/tui_frames.rs` is untouched:
main has no `ChainChoice` to pin (the chain-source picker is the unmerged F7
work, and `docs/WALLET.md` says so rather than describing a picker that does
not exist).
Proof (all on this tree):
- Default build: `cargo test --locked --target x86_64-unknown-linux-gnu` → 345
passed / 0 failed across 33 suites, exit 0; `cargo clippy --locked
--all-targets --target x86_64-unknown-linux-gnu -- -D warnings` exit 0.
- Feature on: `cargo test --locked --features cuprate-daemon --target
x86_64-unknown-linux-gnu` → 347 passed / 0 failed, exit 0; same clippy with
`--features cuprate-daemon` exit 0. The two extra tests are the real thing:
`wallet_child::tests::in_process_source_launches_a_daemon_and_stop_shuts_it_down`
and `tests/wallet.rs::an_in_process_cuprate_node_answers_the_typed_daemon_client`
— the latter launches the node, drives `get_info` / `get_height` / `get_block`
through the typed client, checks the above-the-tip 500 maps to
`DaemonHeightOutOfRange`, checks the chain store is under the chain datadir,
and checks the listener dies with the node.
- aarch64: `cargo check --locked --release --target aarch64-linux-android
--features cuprate-daemon` exit 0 (1m 50s), and the full link exit 0
(`cargo rustc ... --bin onionwire -- <NDK C++ runtime / compiler-rt link
args>`) producing `ELF 64-bit LSB pie executable, ARM aarch64, for Android 26,
built by NDK r28c`.
- Size: stripped aarch64 release binary, 24,725,704 bytes without the feature and
37,053,472 with it — +12,327,768 bytes (≈ +11.8 MiB), the figure
`docs/WALLET.md` now quotes.
2026-09-18 13:45:59 -04:00
/// 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.
///
/// Two consequences the UI has to state: the chain is on this device, and
/// the in-process daemon is **testnet-only** in this build (Cuprate is
/// pre-production and its mainnet RPC parity is unvalidated).
InProcessCuprate {
/// Data directory for the daemon's chain database.
datadir : PathBuf ,
} ,
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// 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 ,
} ,
}
2026-09-18 09:28:11 -04:00
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 { .. } = > " local node " . to_string ( ) ,
wallet: land the in-process Cuprate chain source on main
`ChainSource::InProcessCuprate { datadir }` is the fourth chain source: P2P,
consensus and RandomX run inside the OnionWire process instead of as a spawned
`monerod`. The wallet layer does not move — the daemon binds the same loopback
unrestricted RPC (`127.0.0.1:18081`) that `WalletChild::daemon_address` already
returns for a local source, so `wallet_rpc_argv`, the RPC client, the payment
frames and the receipt-verification path are untouched.
- Cargo.toml: `cuprated` (git, rev 4f8fcd1b) + `toml`, both optional, behind the
`cuprate-daemon` feature, OFF by default. `cuprated`'s own `arti` feature is
disabled (`default-features = false`): its arti-client 0.44 cannot unify with
this crate's 0.46, and the in-process daemon is clearnet-only. One Tor stack in
the process. `Cargo.lock` gains the graph; a default build's
`cargo tree --locked -e normal -i cuprated` still says "did not match any
packages", and only `arti-client v0.46.0` is in the lock.
- src/cuprate.rs (new): `CuprateNode` builds the cuprated config as TOML
(testnet, unrestricted RPC on loopback, restricted RPC disabled, inbound P2P
off), launches it on a runtime it owns, and owns the node. `launch` is
synchronous on purpose: `WalletChild::start` is sync (the TUI calls it from its
blocking thread, UniFFI calls it from an async context) and a runtime cannot be
started from inside a runtime, so the launch runs on a thread of its own and
the node + its runtime come back over a channel. Dropping the value asks the
node to shut down and `shutdown_background`s the runtime, which is the only
exit that cannot panic when the value is dropped inside another runtime.
The type exists in every build (feature off: `launch` fails with the feature
name), so the chain-source type, its stored record and its copy do not fork on
a cargo feature.
- src/wallet.rs: the variant, its label (`in-process node`), and the chain-daemon
client the wallet line carried (typed `WalletError`, de-chunked HTTP,
`get_height` over the URI endpoint, an above-the-tip height as one typed
error). Cuprate answers those three differently from monerod and the
in-process source is what makes them the *local* case.
- src/wallet_child.rs: launches/holds/stops the node, `chain_datadir` for the
free-space/ownership question, the honest `chain_copy` line, `kind =
"cuprate"` in the sealed record, and `ChildConfig::validate` for it.
- src/tui.rs: the wallet screen's chain line carries the testnet caveat when the
configured source is the in-process one. It computes the line at draw time, so
`Screen::Wallet`'s shape (which tests construct) does not change.
- docs/WALLET.md, docs/THREAT_MODEL.md, docs/cuprate-android-spike.md: the
feature flag and how to enable it, where the (fjall) chain store lives, the
**measured** +11.8 MiB delta, the pre-production/testnet caveat, and the
in-repo aarch64-linux-android proof with exit codes.
Scope deviations, stated plainly:
- `src/cuprate.rs` and its one `src/lib.rs` module line are not in the card's
allowed list; the card's own deliverable describes the module's behaviour.
- `crates/onionwire-sdk/src/lib.rs` is forbidden, but adding a variant to a
`pub enum` that the SDK matches exhaustively breaks the SDK workspace, and the
root CI `sdk` job runs on every PR. One variant plus two match arms land here
so the SDK keeps compiling (`cargo test --locked` + clippy clean); the SDK card
owns the rest — feature passthrough, the config field's semantics, the label
and its tests, and the Android check.
- `tests/wallet.rs` carries the launch test. `tests/tui_frames.rs` is untouched:
main has no `ChainChoice` to pin (the chain-source picker is the unmerged F7
work, and `docs/WALLET.md` says so rather than describing a picker that does
not exist).
Proof (all on this tree):
- Default build: `cargo test --locked --target x86_64-unknown-linux-gnu` → 345
passed / 0 failed across 33 suites, exit 0; `cargo clippy --locked
--all-targets --target x86_64-unknown-linux-gnu -- -D warnings` exit 0.
- Feature on: `cargo test --locked --features cuprate-daemon --target
x86_64-unknown-linux-gnu` → 347 passed / 0 failed, exit 0; same clippy with
`--features cuprate-daemon` exit 0. The two extra tests are the real thing:
`wallet_child::tests::in_process_source_launches_a_daemon_and_stop_shuts_it_down`
and `tests/wallet.rs::an_in_process_cuprate_node_answers_the_typed_daemon_client`
— the latter launches the node, drives `get_info` / `get_height` / `get_block`
through the typed client, checks the above-the-tip 500 maps to
`DaemonHeightOutOfRange`, checks the chain store is under the chain datadir,
and checks the listener dies with the node.
- aarch64: `cargo check --locked --release --target aarch64-linux-android
--features cuprate-daemon` exit 0 (1m 50s), and the full link exit 0
(`cargo rustc ... --bin onionwire -- <NDK C++ runtime / compiler-rt link
args>`) producing `ELF 64-bit LSB pie executable, ARM aarch64, for Android 26,
built by NDK r28c`.
- Size: stripped aarch64 release binary, 24,725,704 bytes without the feature and
37,053,472 with it — +12,327,768 bytes (≈ +11.8 MiB), the figure
`docs/WALLET.md` now quotes.
2026-09-18 13:45:59 -04:00
ChainSource ::InProcessCuprate { .. } = > " in-process node " . to_string ( ) ,
2026-09-18 09:28:11 -04:00
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 " )
}
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
/// 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 < String > ,
/// 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 " , & " <redacted> " )
. 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 < String > ,
/// 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 < String > ,
}
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 , " <redacted> " ) ;
}
const MAX : usize = 120 ;
if out . chars ( ) . count ( ) > MAX {
out = out . chars ( ) . take ( MAX ) . collect ( ) ;
out . push ( '…' ) ;
}
out
}
2026-09-10 20:17:25 -04:00
#[ derive(Clone) ]
2026-09-10 14:37:43 -04:00
struct Endpoint {
host : String ,
port : u16 ,
path : String ,
2026-09-10 20:17:25 -04:00
user : String ,
2026-09-12 13:36:21 -04:00
pass : Zeroizing < String > ,
2026-09-10 20:17:25 -04:00
}
impl std ::fmt ::Debug for Endpoint {
fn fmt ( & self , f : & mut std ::fmt ::Formatter < '_ > ) -> std ::fmt ::Result {
f . debug_struct ( " Endpoint " )
. field ( " host " , & self . host )
. field ( " port " , & self . port )
. field ( " path " , & self . path )
. field ( " user " , & self . user )
. field ( " pass " , & " <redacted> " )
. finish ( )
}
2026-09-10 14:37:43 -04:00
}
#[ derive(Debug, Clone) ]
pub struct Wallet {
endpoint : Option < Endpoint > ,
wallet: no-spend mode + view-only detection over RPC
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.
When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.
New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 12:59:49 -04:00
no_spend : bool ,
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// Budget for loopback management calls (`get_address`, `query_key`,
/// create/import). The wallet child is on the same box, so this stays short.
timeout_local : Duration ,
/// Budget for calls that wait on the daemon (`get_info`, `get_transfers`,
/// `transfer`). A first sync or a remote daemon legitimately outlasts the
/// local budget, and treating that as "down" is what left receipts
/// permanently unverified.
timeout_chain : Duration ,
2026-09-10 14:37:43 -04:00
}
wallet: no-spend mode + view-only detection over RPC
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.
When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.
New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 12:59:49 -04:00
/// 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
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
/// 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 " ;
wallet: no-spend mode + view-only detection over RPC
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.
When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.
New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 12:59:49 -04:00
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// What a spend says while the wallet is not synced. Honest state, not a bug:
/// the caller retries once the daemon has caught up.
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
pub const NOT_SYNCED_MSG : & str =
" wallet is not synced — spend refused until the daemon reaches the chain tip " ;
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
wallet: no-spend mode + view-only detection over RPC
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.
When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.
New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 12:59:49 -04:00
/// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in monero's
/// `src/wallet/wallet_rpc_server_error_codes.h`.
const WATCH_ONLY_CODE : i64 = - 29 ;
2026-09-10 14:37:43 -04:00
#[ derive(Debug, Clone, PartialEq, Eq) ]
pub struct TransferRow {
pub txid : String ,
pub amount : String ,
pub address : String ,
}
2026-09-13 23:25:25 -04:00
/// 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. " ;
2026-09-10 14:37:43 -04:00
const RPC_TIMEOUT : Duration = Duration ::from_secs ( 5 ) ;
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// Budget for calls that wait on the daemon (`get_info`, `get_transfers`,
/// `transfer`). A first sync or a remote daemon legitimately outlasts the
/// loopback budget; a 5s cap there leaves receipts permanently unverified.
pub const CHAIN_RPC_TIMEOUT : Duration = Duration ::from_secs ( 60 ) ;
2026-09-10 14:37:43 -04:00
impl Wallet {
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// The one place the budgets are defaulted. Callers adjust them with
/// [`Wallet::with_timeouts`].
fn new ( endpoint : Option < Endpoint > , no_spend : bool ) -> Self {
wallet: no-spend mode + view-only detection over RPC
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.
When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.
New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 12:59:49 -04:00
Self {
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
endpoint ,
no_spend ,
timeout_local : RPC_TIMEOUT ,
timeout_chain : CHAIN_RPC_TIMEOUT ,
wallet: no-spend mode + view-only detection over RPC
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.
When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.
New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 12:59:49 -04:00
}
2026-09-10 14:37:43 -04:00
}
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
pub fn disabled ( ) -> Self {
Self ::new ( None , false )
}
wallet: no-spend mode + view-only detection over RPC
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.
When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.
New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 12:59:49 -04:00
/// `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.
2026-09-10 14:37:43 -04:00
pub fn from_env ( ) -> Self {
wallet: no-spend mode + view-only detection over RPC
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.
When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.
New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 12:59:49 -04:00
let no_spend = env_flag ( " ONIONWIRE_WALLET_NO_SPEND " ) ;
2026-09-10 14:37:43 -04:00
match std ::env ::var ( " ONIONWIRE_WALLET_RPC " ) {
2026-09-12 13:36:21 -04:00
// The URL can carry `user:pass@` in its userinfo: keep it in a
// wiping buffer, not a bare `String`.
2026-09-10 20:17:25 -04:00
Ok ( s ) if ! s . trim ( ) . is_empty ( ) = > {
2026-09-12 13:36:21 -04:00
let url = Zeroizing ::new ( s ) ;
2026-09-10 20:17:25 -04:00
let login = std ::env ::var ( " ONIONWIRE_WALLET_RPC_LOGIN " )
. ok ( )
2026-09-12 13:36:21 -04:00
. map ( | v | Zeroizing ::new ( v . trim ( ) . to_string ( ) ) )
2026-09-10 20:17:25 -04:00
. filter ( | v | ! v . is_empty ( ) ) ;
2026-09-12 13:36:21 -04:00
match parse_http_url ( url . trim ( ) , login . as_ref ( ) . map ( | v | v . as_str ( ) ) ) {
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
Ok ( endpoint ) = > Self ::new ( Some ( endpoint ) , no_spend ) ,
2026-09-10 20:17:25 -04:00
Err ( e ) = > {
eprintln! ( " ONIONWIRE_WALLET_RPC: {e} " ) ;
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
Self ::new ( None , no_spend )
2026-09-10 20:17:25 -04:00
}
2026-09-10 14:37:43 -04:00
}
2026-09-10 20:17:25 -04:00
}
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
_ = > Self ::new ( None , no_spend ) ,
2026-09-10 14:37:43 -04:00
}
}
pub fn from_url ( url : & str ) -> Result < Self > {
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
Ok ( Self ::new ( Some ( parse_http_url ( url , None ) ? ) , false ) )
}
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
/// 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 < Self > {
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 < WalletConfig > {
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 )
}
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// 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
2026-09-10 14:37:43 -04:00
}
wallet: no-spend mode + view-only detection over RPC
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.
When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.
New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 12:59:49 -04:00
/// 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
}
2026-09-10 14:37:43 -04:00
pub fn configured ( & self ) -> bool {
self . endpoint . is_some ( )
}
pub async fn get_address ( & self ) -> Result < String > {
let v = self
. rpc ( " get_address " , serde_json ::json! ( { " account_index " : 0 } ) )
. await ? ;
json_str ( & v , " address " )
}
pub async fn create_address ( & self ) -> Result < String > {
let v = self
. rpc ( " create_address " , serde_json ::json! ( { " account_index " : 0 } ) )
. await ? ;
json_str ( & v , " address " )
}
pub async fn transfer ( & self , address : & str , amount : u64 ) -> Result < String > {
wallet: no-spend mode + view-only detection over RPC
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.
When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.
New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 12:59:49 -04:00
if self . no_spend {
return Err ( Error ( VIEW_ONLY_MSG . into ( ) ) ) ;
}
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
// Honest gate: a wallet that has not caught up to the chain tip cannot
// build a spend, so refuse instead of letting the RPC fail opaquely.
// Fail closed — if readiness cannot be proven, the spend is refused.
if ! self . can_spend ( ) . await {
return Err ( Error ( NOT_SYNCED_MSG . into ( ) ) ) ;
}
wallet: no-spend mode + view-only detection over RPC
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.
When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.
New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 12:59:49 -04:00
let sent = self
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
. chain_rpc (
2026-09-10 14:37:43 -04:00
" transfer " ,
serde_json ::json! ( {
" destinations " : [ { " amount " : amount , " address " : address } ] ,
" account_index " : 0
} ) ,
)
wallet: no-spend mode + view-only detection over RPC
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.
When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.
New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 12:59:49 -04:00
. 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 ) ;
}
} ;
2026-09-10 14:37:43 -04:00
json_str ( & v , " tx_hash " )
}
wallet: no-spend mode + view-only detection over RPC
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.
When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.
New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 12:59:49 -04:00
/// 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
)
}
2026-09-10 14:37:43 -04:00
pub async fn get_transfers ( & self ) -> Result < Vec < TransferRow > > {
let v = self
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
. chain_rpc (
2026-09-10 14:37:43 -04:00
" 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 )
}
2026-09-12 22:53:58 -04:00
/// Monero-wallet-rpc `get_balance`, account_index 0. Returns the "balance"
/// field as a piconero string on success; the caller can format it with
/// `pay::atomic_to_xmr_str` if it wants a human-readable form.
pub async fn get_balance ( & self ) -> Result < String > {
let v = self
. rpc ( " get_balance " , serde_json ::json! ( { " account_index " : 0 } ) )
. await ? ;
json_str ( & v , " balance " )
}
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// Unlocked balance in piconero — the part a spend can actually use.
pub async fn unlocked_balance ( & self ) -> Result < u64 > {
let v = self
. rpc ( " get_balance " , serde_json ::json! ( { " account_index " : 0 } ) )
. await ? ;
json_str ( & v , " unlocked_balance " ) ?
. trim ( )
. parse ::< u64 > ( )
. map_err ( | _ | Error ( " wallet RPC returned a non-numeric unlocked_balance " . into ( ) ) )
}
/// The real readiness predicate: the daemon has reached the chain tip and
/// the wallet has scanned up to it. `synchronized` must be explicitly true —
/// a missing field is not-ready, never a silent pass.
pub async fn chain_ready ( & self ) -> Result < bool > {
let v = self . chain_rpc ( " get_info " , serde_json ::json! ( { } ) ) . await ? ;
let synced = v
. get ( " synchronized " )
. and_then ( | b | b . as_bool ( ) )
. unwrap_or ( false ) ;
let height = v . get ( " height " ) . and_then ( | h | h . as_u64 ( ) ) . unwrap_or ( 0 ) ;
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
let target = v . get ( " target_height " ) . and_then ( | h | h . as_u64 ( ) ) . unwrap_or ( 0 ) ;
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
Ok ( 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 )
}
2026-09-13 23:25:25 -04:00
/// Create a new spend-capable wallet on the RPC (`create_wallet`). The
/// user does not paste a key — the daemon generates the seed. Returns that
/// seed once (from `query_key mnemonic`) so the UI can show a backup
/// screen. Needs `--wallet-dir` on the RPC.
pub async fn create_wallet ( & self , filename : & str , password : & str ) -> Result < String > {
let filename = filename . trim ( ) ;
if filename . is_empty ( ) {
return Err ( Error ( " wallet filename required " . into ( ) ) ) ;
}
if password . is_empty ( ) {
return Err ( Error ( " wallet passphrase required " . into ( ) ) ) ;
}
self . rpc (
" create_wallet " ,
serde_json ::json! ( {
" filename " : filename ,
" password " : password ,
" language " : " English "
} ) ,
)
. await ? ;
let v = self
. rpc ( " query_key " , serde_json ::json! ( { " key_type " : " mnemonic " } ) )
. await
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
. map_err ( | e | Error ( format! ( " wallet created but seed backup unavailable: {e} " ) ) ) ? ;
2026-09-13 23:25:25 -04:00
json_str ( & v , " key " )
}
/// Import an existing wallet from its 25-word seed. This is the only path
/// that takes a user-supplied secret.
pub async fn restore_wallet ( & self , filename : & str , password : & str , seed : & str ) -> Result < ( ) > {
let filename = filename . trim ( ) ;
if filename . is_empty ( ) {
return Err ( Error ( " wallet filename required " . into ( ) ) ) ;
}
if password . is_empty ( ) {
return Err ( Error ( " wallet passphrase required " . into ( ) ) ) ;
}
let seed = seed . trim ( ) ;
if seed . is_empty ( ) {
return Err ( Error ( " seed required to import a wallet " . into ( ) ) ) ;
}
self . rpc (
" restore_deterministic_wallet " ,
serde_json ::json! ( {
" filename " : filename ,
" password " : password ,
" seed " : seed ,
" language " : " English "
} ) ,
)
. await ? ;
Ok ( ( ) )
}
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// Loopback management call: the wallet child is on the same box, so it gets
/// the short budget.
2026-09-10 14:37:43 -04:00
async fn rpc ( & self , method : & str , params : serde_json ::Value ) -> Result < serde_json ::Value > {
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
self . rpc_with ( method , params , self . timeout_local ) . await
}
/// Chain-dependent call (`get_info`, `get_transfers`, `transfer`): it waits
/// on the daemon, so it gets the longer budget.
async fn chain_rpc (
& self ,
method : & str ,
params : serde_json ::Value ,
) -> Result < serde_json ::Value > {
self . rpc_with ( method , params , self . timeout_chain ) . await
}
async fn rpc_with (
& self ,
method : & str ,
params : serde_json ::Value ,
budget : Duration ,
) -> Result < serde_json ::Value > {
2026-09-10 14:37:43 -04:00
let ep = self
. endpoint
. as_ref ( )
. ok_or_else ( | | Error ( " not configured " . into ( ) ) ) ? ;
let body = serde_json ::json! ( {
" jsonrpc " : " 2.0 " ,
" id " : " 0 " ,
" method " : method ,
" params " : params ,
} )
. to_string ( ) ;
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
let raw = post_timeout ( ep , & build_req ( ep , & body , None ) , budget ) . await ? ;
2026-09-10 20:17:25 -04:00
let status = http_status ( & raw ) . unwrap_or ( 0 ) ;
if status = = 200 {
return Err ( Error (
" wallet RPC requires digest auth (open RPC refused) " . into ( ) ,
) ) ;
}
if status ! = 401 {
return parse_json_rpc ( & raw ) ;
}
let challenge = www_authenticate ( & raw ) . ok_or_else ( | | {
Error ( " wallet RPC digest required (--rpc-login / HTTP Digest) " . into ( ) )
} ) ? ;
if ! challenge . trim ( ) . to_ascii_lowercase ( ) . starts_with ( " digest " ) {
return Err ( Error (
" wallet RPC digest required (--rpc-login / HTTP Digest) " . into ( ) ,
) ) ;
}
let auth = digest_authorization ( ep , & challenge ) ? ;
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
let raw = post_timeout ( ep , & build_req ( ep , & body , Some ( & auth ) ) , budget ) . await ? ;
2026-09-10 14:37:43 -04:00
parse_json_rpc ( & raw )
}
}
pub fn transfers_match ( rows : & [ TransferRow ] , txid : & str , amount : & str , address : & str ) -> bool {
2026-09-10 19:29:39 -04:00
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 )
2026-09-10 14:37:43 -04:00
}
2026-09-10 20:17:25 -04:00
fn credentials_required ( ) -> Error {
Error ( " wallet RPC requires credentials (user:pass in URL or ONIONWIRE_WALLET_RPC_LOGIN) " . into ( ) )
}
wallet: no-spend mode + view-only detection over RPC
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.
When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.
New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 12:59:49 -04:00
/// `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 " )
)
}
2026-09-12 13:36:21 -04:00
fn parse_login ( login : & str ) -> Result < ( String , Zeroizing < String > ) > {
2026-09-10 20:17:25 -04:00
let ( user , pass ) = login . split_once ( ':' ) . ok_or_else ( credentials_required ) ? ;
if user . is_empty ( ) | | pass . is_empty ( ) {
return Err ( credentials_required ( ) ) ;
}
2026-09-12 13:36:21 -04:00
Ok ( ( user . to_string ( ) , Zeroizing ::new ( pass . to_string ( ) ) ) )
2026-09-10 20:17:25 -04:00
}
fn parse_http_url ( url : & str , extra_login : Option < & str > ) -> Result < Endpoint > {
2026-09-10 14:37:43 -04:00
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 ( ) ) ) ;
}
2026-09-10 20:17:25 -04:00
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 ( ) ) ,
} ,
} ;
2026-09-10 14:37:43 -04:00
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 ) ? ;
2026-09-10 20:17:25 -04:00
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 ( ) ,
) ) ;
}
2026-09-10 14:37:43 -04:00
if ! allowed_host ( & host ) {
2026-09-10 20:17:25 -04:00
return Err ( Error ( " wallet RPC host must be loopback " . into ( ) ) ) ;
2026-09-10 14:37:43 -04:00
}
2026-09-10 20:17:25 -04:00
Ok ( Endpoint {
host ,
port ,
path ,
user ,
pass ,
} )
2026-09-10 14:37:43 -04:00
}
fn parse_hostport ( hostport : & str ) -> Result < ( String , u16 ) > {
if let Some ( rest ) = hostport . strip_prefix ( '[' ) {
let ( host , rest ) = rest
. split_once ( ']' )
. ok_or_else ( | | Error ( " invalid IPv6 host " . into ( ) ) ) ? ;
let port = match rest . strip_prefix ( ':' ) {
Some ( p ) if ! p . is_empty ( ) = > parse_port ( p ) ? ,
_ = > 18083 ,
} ;
if host . is_empty ( ) {
return Err ( Error ( " empty host " . into ( ) ) ) ;
}
return Ok ( ( host . to_string ( ) , port ) ) ;
}
match hostport . rsplit_once ( ':' ) {
Some ( ( h , p ) ) if ! h . is_empty ( ) & & ! p . is_empty ( ) & & p . bytes ( ) . all ( | b | b . is_ascii_digit ( ) ) = > {
Ok ( ( h . to_string ( ) , parse_port ( p ) ? ) )
}
_ if ! hostport . is_empty ( ) = > Ok ( ( hostport . to_string ( ) , 18083 ) ) ,
_ = > Err ( Error ( " empty host " . into ( ) ) ) ,
}
}
fn parse_port ( p : & str ) -> Result < u16 > {
p . parse ( )
. map_err ( | _ | Error ( " invalid wallet RPC port " . into ( ) ) )
}
fn allowed_host ( host : & str ) -> bool {
let h = host . trim ( ) ;
if h . eq_ignore_ascii_case ( " localhost " ) {
return true ;
}
h . parse ::< std ::net ::IpAddr > ( )
. map ( | ip | ip . is_loopback ( ) )
. unwrap_or ( false )
}
fn host_header ( host : & str , port : u16 ) -> String {
if host . contains ( ':' ) {
format! ( " [ {host} ]: {port} " )
} else {
format! ( " {host} : {port} " )
}
}
2026-09-10 20:17:25 -04:00
const MAX_RPC_BYTES : usize = 1024 * 1024 ;
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
async fn post_timeout ( ep : & Endpoint , req : & str , budget : Duration ) -> Result < Vec < u8 > > {
tokio ::time ::timeout ( budget , http_post ( ep , req . as_bytes ( ) ) )
2026-09-10 20:17:25 -04:00
. 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 \n Host: {host_hdr} \r \n Content-Type: application/json \r \n Content-Length: {} \r \n Connection: 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
}
2026-09-10 14:37:43 -04:00
async fn http_post ( ep : & Endpoint , req : & [ u8 ] ) -> Result < Vec < u8 > > {
let mut stream = TcpStream ::connect ( ( ep . host . as_str ( ) , ep . port ) )
. await
. map_err ( | e | Error ( format! ( " wallet connect: {e} " ) ) ) ? ;
stream
. write_all ( req )
. await
. map_err ( | e | Error ( format! ( " wallet write: {e} " ) ) ) ? ;
let mut buf = Vec ::new ( ) ;
2026-09-10 20:17:25 -04:00
let mut tmp = [ 0 u8 ; 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 ] ) ;
}
2026-09-10 14:37:43 -04:00
Ok ( buf )
}
2026-09-10 20:17:25 -04:00
fn http_status ( raw : & [ u8 ] ) -> Option < u16 > {
let text = std ::str ::from_utf8 ( raw ) . ok ( ) ? ;
let line = text . lines ( ) . next ( ) ? ;
let mut parts = line . split_whitespace ( ) ;
let _http = parts . next ( ) ? ;
parts . next ( ) ? . parse ( ) . ok ( )
}
fn www_authenticate ( raw : & [ u8 ] ) -> Option < String > {
let text = std ::str ::from_utf8 ( raw ) . ok ( ) ? ;
let ( head , _ ) = text
. split_once ( " \r \n \r \n " )
. or_else ( | | text . split_once ( " \n \n " ) ) ? ;
for line in head . lines ( ) . skip ( 1 ) {
let ( k , v ) = match line . split_once ( ':' ) {
Some ( kv ) = > kv ,
None = > continue ,
} ;
if k . eq_ignore_ascii_case ( " www-authenticate " ) {
return Some ( v . trim ( ) . to_string ( ) ) ;
}
}
None
}
fn digest_param ( challenge : & str , key : & str ) -> Option < String > {
let t = challenge . trim ( ) ;
let rest = if t . len ( ) > = 6 & & t [ .. 6 ] . eq_ignore_ascii_case ( " digest " ) {
t [ 6 .. ] . trim ( )
} else {
return None ;
} ;
for part in rest . split ( ',' ) {
let part = part . trim ( ) ;
let ( k , v ) = match part . split_once ( '=' ) {
Some ( kv ) = > kv ,
None = > continue ,
} ;
if k . eq_ignore_ascii_case ( key ) {
return Some ( v . trim ( ) . trim_matches ( '"' ) . to_string ( ) ) ;
}
}
None
}
fn md5_hex ( s : & str ) -> String {
use md5 ::{ Digest , Md5 } ;
hex_lower ( & Md5 ::digest ( s . as_bytes ( ) ) )
}
fn hex_lower ( bytes : & [ u8 ] ) -> String {
const H : & [ u8 ; 16 ] = b " 0123456789abcdef " ;
let mut out = String ::with_capacity ( bytes . len ( ) * 2 ) ;
for & b in bytes {
out . push ( H [ ( b > > 4 ) as usize ] as char ) ;
out . push ( H [ ( b & 0xf ) as usize ] as char ) ;
}
out
}
fn digest_authorization ( ep : & Endpoint , challenge : & str ) -> Result < String > {
if let Some ( alg ) = digest_param ( challenge , " algorithm " )
& & ! alg . eq_ignore_ascii_case ( " MD5 " )
{
return Err ( Error ( " wallet RPC digest algorithm not MD5 " . into ( ) ) ) ;
}
let realm = digest_param ( challenge , " realm " ) . unwrap_or_default ( ) ;
let nonce = digest_param ( challenge , " nonce " )
. ok_or_else ( | | Error ( " wallet RPC digest required (--rpc-login / HTTP Digest) " . into ( ) ) ) ? ;
let qop = digest_param ( challenge , " qop " ) ;
2026-09-12 13:36:21 -04:00
// `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 ( ) ) ;
2026-09-10 20:17:25 -04:00
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 = [ 0 u8 ; 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
) )
}
2026-09-10 14:37:43 -04:00
fn parse_json_rpc ( raw : & [ u8 ] ) -> Result < serde_json ::Value > {
let text = std ::str ::from_utf8 ( raw ) . map_err ( | _ | Error ( " wallet RPC not UTF-8 " . into ( ) ) ) ? ;
let ( head , body ) = text
. split_once ( " \r \n \r \n " )
. or_else ( | | text . split_once ( " \n \n " ) )
. ok_or_else ( | | Error ( " wallet RPC truncated " . into ( ) ) ) ? ;
let status = head . lines ( ) . next ( ) . unwrap_or ( " " ) ;
if status . contains ( " 3 " ) {
return Err ( Error ( " wallet RPC redirect refused " . into ( ) ) ) ;
}
if ! status . contains ( " 200 " ) & & ! status . ends_with ( " 200 " ) {
return Err ( Error ( format! ( " wallet RPC HTTP {status} " ) ) ) ;
}
let json : serde_json ::Value =
serde_json ::from_str ( body . trim ( ) ) . map_err ( | e | Error ( format! ( " wallet RPC json: {e} " ) ) ) ? ;
if let Some ( err ) = json . get ( " error " ) {
let msg = err
. get ( " message " )
. and_then ( | m | m . as_str ( ) )
. unwrap_or ( " rpc error " ) ;
wallet: no-spend mode + view-only detection over RPC
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.
When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.
New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 12:59:49 -04:00
// 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 ( ) ) ) ;
}
2026-09-10 14:37:43 -04:00
return Err ( Error ( msg . into ( ) ) ) ;
}
json . get ( " result " )
. cloned ( )
. ok_or_else ( | | Error ( " wallet RPC missing result " . into ( ) ) )
}
fn json_str ( v : & serde_json ::Value , key : & str ) -> Result < String > {
v . get ( key )
. and_then ( | x | x . as_str ( ) )
. map ( str ::to_string )
. ok_or_else ( | | Error ( format! ( " wallet RPC missing {key} " ) ) )
}
fn json_amount ( v : & serde_json ::Value ) -> String {
match v . get ( " amount " ) {
Some ( serde_json ::Value ::Number ( n ) ) = > n
. as_u64 ( )
. map ( | x | x . to_string ( ) )
. or_else ( | | n . as_i64 ( ) . map ( | x | x . to_string ( ) ) )
. unwrap_or_default ( ) ,
Some ( serde_json ::Value ::String ( s ) ) = > s . clone ( ) ,
_ = > String ::new ( ) ,
}
}
wallet: land the in-process Cuprate chain source on main
`ChainSource::InProcessCuprate { datadir }` is the fourth chain source: P2P,
consensus and RandomX run inside the OnionWire process instead of as a spawned
`monerod`. The wallet layer does not move — the daemon binds the same loopback
unrestricted RPC (`127.0.0.1:18081`) that `WalletChild::daemon_address` already
returns for a local source, so `wallet_rpc_argv`, the RPC client, the payment
frames and the receipt-verification path are untouched.
- Cargo.toml: `cuprated` (git, rev 4f8fcd1b) + `toml`, both optional, behind the
`cuprate-daemon` feature, OFF by default. `cuprated`'s own `arti` feature is
disabled (`default-features = false`): its arti-client 0.44 cannot unify with
this crate's 0.46, and the in-process daemon is clearnet-only. One Tor stack in
the process. `Cargo.lock` gains the graph; a default build's
`cargo tree --locked -e normal -i cuprated` still says "did not match any
packages", and only `arti-client v0.46.0` is in the lock.
- src/cuprate.rs (new): `CuprateNode` builds the cuprated config as TOML
(testnet, unrestricted RPC on loopback, restricted RPC disabled, inbound P2P
off), launches it on a runtime it owns, and owns the node. `launch` is
synchronous on purpose: `WalletChild::start` is sync (the TUI calls it from its
blocking thread, UniFFI calls it from an async context) and a runtime cannot be
started from inside a runtime, so the launch runs on a thread of its own and
the node + its runtime come back over a channel. Dropping the value asks the
node to shut down and `shutdown_background`s the runtime, which is the only
exit that cannot panic when the value is dropped inside another runtime.
The type exists in every build (feature off: `launch` fails with the feature
name), so the chain-source type, its stored record and its copy do not fork on
a cargo feature.
- src/wallet.rs: the variant, its label (`in-process node`), and the chain-daemon
client the wallet line carried (typed `WalletError`, de-chunked HTTP,
`get_height` over the URI endpoint, an above-the-tip height as one typed
error). Cuprate answers those three differently from monerod and the
in-process source is what makes them the *local* case.
- src/wallet_child.rs: launches/holds/stops the node, `chain_datadir` for the
free-space/ownership question, the honest `chain_copy` line, `kind =
"cuprate"` in the sealed record, and `ChildConfig::validate` for it.
- src/tui.rs: the wallet screen's chain line carries the testnet caveat when the
configured source is the in-process one. It computes the line at draw time, so
`Screen::Wallet`'s shape (which tests construct) does not change.
- docs/WALLET.md, docs/THREAT_MODEL.md, docs/cuprate-android-spike.md: the
feature flag and how to enable it, where the (fjall) chain store lives, the
**measured** +11.8 MiB delta, the pre-production/testnet caveat, and the
in-repo aarch64-linux-android proof with exit codes.
Scope deviations, stated plainly:
- `src/cuprate.rs` and its one `src/lib.rs` module line are not in the card's
allowed list; the card's own deliverable describes the module's behaviour.
- `crates/onionwire-sdk/src/lib.rs` is forbidden, but adding a variant to a
`pub enum` that the SDK matches exhaustively breaks the SDK workspace, and the
root CI `sdk` job runs on every PR. One variant plus two match arms land here
so the SDK keeps compiling (`cargo test --locked` + clippy clean); the SDK card
owns the rest — feature passthrough, the config field's semantics, the label
and its tests, and the Android check.
- `tests/wallet.rs` carries the launch test. `tests/tui_frames.rs` is untouched:
main has no `ChainChoice` to pin (the chain-source picker is the unmerged F7
work, and `docs/WALLET.md` says so rather than describing a picker that does
not exist).
Proof (all on this tree):
- Default build: `cargo test --locked --target x86_64-unknown-linux-gnu` → 345
passed / 0 failed across 33 suites, exit 0; `cargo clippy --locked
--all-targets --target x86_64-unknown-linux-gnu -- -D warnings` exit 0.
- Feature on: `cargo test --locked --features cuprate-daemon --target
x86_64-unknown-linux-gnu` → 347 passed / 0 failed, exit 0; same clippy with
`--features cuprate-daemon` exit 0. The two extra tests are the real thing:
`wallet_child::tests::in_process_source_launches_a_daemon_and_stop_shuts_it_down`
and `tests/wallet.rs::an_in_process_cuprate_node_answers_the_typed_daemon_client`
— the latter launches the node, drives `get_info` / `get_height` / `get_block`
through the typed client, checks the above-the-tip 500 maps to
`DaemonHeightOutOfRange`, checks the chain store is under the chain datadir,
and checks the listener dies with the node.
- aarch64: `cargo check --locked --release --target aarch64-linux-android
--features cuprate-daemon` exit 0 (1m 50s), and the full link exit 0
(`cargo rustc ... --bin onionwire -- <NDK C++ runtime / compiler-rt link
args>`) producing `ELF 64-bit LSB pie executable, ARM aarch64, for Android 26,
built by NDK r28c`.
- Size: stripped aarch64 release binary, 24,725,704 bytes without the feature and
37,053,472 with it — +12,327,768 bytes (≈ +11.8 MiB), the figure
`docs/WALLET.md` now quotes.
2026-09-18 13:45:59 -04:00
// ---------------------------------------------------------------------------
// 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 < DaemonInfo , WalletError > {
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 < u64 , WalletError > {
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 < Vec < u8 > , 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 \n Host: {addr} \r \n Content-Type: application/json \r \n Content-Length: {} \r \n Connection: 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 \n Host: {addr} \r \n Content-Type: application/json \r \n Content-Length: 0 \r \n Connection: 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 < u8 > ) , 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 = [ 0 u8 ; 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 ::< Vec < u8 > , 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 < u8 > ) > {
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 < Vec < u8 > > {
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 < usize > {
haystack . windows ( needle . len ( ) ) . position ( | w | w = = needle )
}
fn daemon_json ( body : & [ u8 ] , addr : & str ) -> std ::result ::Result < serde_json ::Value , WalletError > {
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 < Vec < u8 > > {
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 < u8 > {
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 ,
}
}