onionwire/src/wallet.rs

1777 lines
65 KiB
Rust
Raw Normal View History

wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
use std::path::PathBuf;
use std::time::Duration;
use rand::RngCore;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use zeroize::Zeroizing;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub struct Error(String);
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::error::Error for Error {}
wallet: actually open the wallet file, and remember its passphrase `monero-wallet-rpc` starts with no wallet open and keeps one only for the life of its process, so a restart, a Lock/unlock or a wallet re-point left a live child answering `-13 No wallet file` to every read while the file sat on disk. The app now opens the configured catalogue file itself (`Wallet::open_wallet`, over RPC — never `--wallet-file`/`--password` on argv, which `ps` exposes) after the child is up, and keeps the passphrase that does it, sealed with the store data key beside the RPC creds under its own AAD. - core: `Wallet::open_wallet`, `WalletConfig::wallet_passphrase` (+ `with_wallet_passphrase`, redacted Debug, kept out of the endpoint config), `Error::is_unreachable` for the one retryable class (the port binds a moment after spawn; a timeout is not a start in progress). - store: `wallet_config.sealed_passphrase` column (additive, AAD `onionwire-store-v1:wallet-passphrase`), read-modify-written so the endpoint/login survive; `wallet_save_config` keeps the stored one. - node: `start_wallet_child` opens the file, `open_wallet_with_passphrase` opens a file with a passphrase the user just typed and seals it only once a live daemon accepted it, `wallet_status` grows `wallet_open` and `needs_passphrase`. A child the RPC refuses is stopped rather than left inert; an install with no stored passphrase still starts, and says so. - tui: one-shot prompt (`WalletSetup::UnlockPass`) on a wallet that needs it, reachable from the saved-wallet picker and from `s`. - sdk: `openWalletWithPassphrase`, the two status fields, README flow. - docs: WALLET/THREAT_MODEL/README — the passphrase is kept, and the consequence (the store passphrase is sufficient to spend) is stated rather than implied. Tests: 4 new node tests drive a real child lifecycle against a loopback wallet RPC (open on restart, no open without a passphrase, refused passphrase, sealed-on-success), a `tests/wallet.rs` test asserts the bytes sent (`open_wallet` + filename + password), and `tests/store.rs` covers the sealed column and the plaintext->encrypted upgrade with it set. Mutation-checked: stubbing the two open paths fails all four.
2026-09-22 12:52:08 -04:00
impl Error {
/// Is this failure "the wallet RPC is not answering yet"? That is the one
/// class a retry can fix — a freshly spawned `monero-wallet-rpc` binds its
/// port a moment after `spawn` returns. Everything else (a refused
/// passphrase, a protocol error) is the RPC's own answer and retrying it
/// would only repeat it.
///
/// Deliberately *not* the timeout: a hung child is not a start in progress.
pub fn is_unreachable(&self) -> bool {
let msg = self.0.as_str();
msg.starts_with("wallet connect:") || msg.starts_with("wallet write:")
}
}
/// Which Monero network an on-device daemon follows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChainNetwork {
Mainnet,
Testnet,
}
impl ChainNetwork {
/// Cuprate TOML `network = "..."` spelling (`Mainnet` / `Testnet`).
pub fn cuprate_toml(self) -> &'static str {
match self {
Self::Mainnet => "Mainnet",
Self::Testnet => "Testnet",
}
}
/// Directory segment so mainnet and testnet stores never share a fjall dir.
pub fn dir_name(self) -> &'static str {
match self {
Self::Mainnet => "mainnet",
Self::Testnet => "testnet",
}
}
}
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,
/// `monerod --prune-blockchain`. Full node when false.
prune: 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
},
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.
///
/// Cuprate is still pre-production: mainnet RPC parity is unvalidated.
/// The UI must say so. `network`/`prune` are the user's choice; old
/// stored records without those keys are testnet, unpruned.
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
InProcessCuprate {
/// Data directory for the daemon's chain database.
datadir: PathBuf,
network: ChainNetwork,
prune: bool,
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
},
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,
},
}
impl ChainSource {
/// Does this source name a Tor onion service? Only a `.onion` daemon needs
/// the SOCKS child; a loopback or clearnet host the user typed does not.
pub fn is_onion(&self) -> bool {
match self {
ChainSource::Remote { host, .. } => is_onion_host(host),
_ => false,
}
}
/// Short label for a status line: what the wallet child is dialling.
pub fn label(&self) -> String {
match self {
ChainSource::None => "receive-only".to_string(),
ChainSource::Local { prune: true, .. } => "local pruned node".to_string(),
ChainSource::Local { prune: false, .. } => "local full node".to_string(),
ChainSource::InProcessCuprate {
network: ChainNetwork::Mainnet,
prune: true,
..
} => "in-process mainnet pruned".to_string(),
ChainSource::InProcessCuprate {
network: ChainNetwork::Mainnet,
prune: false,
..
} => "in-process mainnet full".to_string(),
ChainSource::InProcessCuprate {
network: ChainNetwork::Testnet,
..
} => "in-process testnet".to_string(),
ChainSource::Remote { host, .. } if is_onion_host(host) => {
"remote onion daemon".to_string()
}
ChainSource::Remote { .. } => "remote daemon".to_string(),
}
}
}
/// Does this host name a Tor onion service? Case-insensitive, and it needs the
/// suffix — `notonion.example` is not one.
pub fn is_onion_host(host: &str) -> bool {
host.trim().to_ascii_lowercase().ends_with(".onion")
}
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,
wallet: actually open the wallet file, and remember its passphrase `monero-wallet-rpc` starts with no wallet open and keeps one only for the life of its process, so a restart, a Lock/unlock or a wallet re-point left a live child answering `-13 No wallet file` to every read while the file sat on disk. The app now opens the configured catalogue file itself (`Wallet::open_wallet`, over RPC — never `--wallet-file`/`--password` on argv, which `ps` exposes) after the child is up, and keeps the passphrase that does it, sealed with the store data key beside the RPC creds under its own AAD. - core: `Wallet::open_wallet`, `WalletConfig::wallet_passphrase` (+ `with_wallet_passphrase`, redacted Debug, kept out of the endpoint config), `Error::is_unreachable` for the one retryable class (the port binds a moment after spawn; a timeout is not a start in progress). - store: `wallet_config.sealed_passphrase` column (additive, AAD `onionwire-store-v1:wallet-passphrase`), read-modify-written so the endpoint/login survive; `wallet_save_config` keeps the stored one. - node: `start_wallet_child` opens the file, `open_wallet_with_passphrase` opens a file with a passphrase the user just typed and seals it only once a live daemon accepted it, `wallet_status` grows `wallet_open` and `needs_passphrase`. A child the RPC refuses is stopped rather than left inert; an install with no stored passphrase still starts, and says so. - tui: one-shot prompt (`WalletSetup::UnlockPass`) on a wallet that needs it, reachable from the saved-wallet picker and from `s`. - sdk: `openWalletWithPassphrase`, the two status fields, README flow. - docs: WALLET/THREAT_MODEL/README — the passphrase is kept, and the consequence (the store passphrase is sufficient to spend) is stated rather than implied. Tests: 4 new node tests drive a real child lifecycle against a loopback wallet RPC (open on restart, no open without a passphrase, refused passphrase, sealed-on-success), a `tests/wallet.rs` test asserts the bytes sent (`open_wallet` + filename + password), and `tests/store.rs` covers the sealed column and the plaintext->encrypted upgrade with it set. Mutation-checked: stubbing the two open paths fails all four.
2026-09-22 12:52:08 -04:00
/// The passphrase that opens the wallet *file* the child is pointed at
/// ([`Wallet::open_wallet`]). Sealed at rest beside `rpc_login`; empty when
/// this install has never been told one (a wallet that predates the field,
/// or a remote-mode wallet the user runs themselves).
///
/// Keeping it is deliberate: it makes the store passphrase sufficient to
/// spend, and it is why the app can reopen a wallet file across a restart
/// at all — `monero-wallet-rpc` holds an open file only for the life of the
/// process, and re-opening it needs the passphrase. See
/// `docs/THREAT_MODEL.md`.
pub wallet_passphrase: Zeroizing<String>,
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
}
impl WalletConfig {
pub fn new(rpc_url: &str, rpc_login: &str, no_spend: bool) -> Self {
Self {
rpc_url: rpc_url.trim().to_string(),
rpc_login: Zeroizing::new(rpc_login.trim().to_string()),
no_spend,
wallet: actually open the wallet file, and remember its passphrase `monero-wallet-rpc` starts with no wallet open and keeps one only for the life of its process, so a restart, a Lock/unlock or a wallet re-point left a live child answering `-13 No wallet file` to every read while the file sat on disk. The app now opens the configured catalogue file itself (`Wallet::open_wallet`, over RPC — never `--wallet-file`/`--password` on argv, which `ps` exposes) after the child is up, and keeps the passphrase that does it, sealed with the store data key beside the RPC creds under its own AAD. - core: `Wallet::open_wallet`, `WalletConfig::wallet_passphrase` (+ `with_wallet_passphrase`, redacted Debug, kept out of the endpoint config), `Error::is_unreachable` for the one retryable class (the port binds a moment after spawn; a timeout is not a start in progress). - store: `wallet_config.sealed_passphrase` column (additive, AAD `onionwire-store-v1:wallet-passphrase`), read-modify-written so the endpoint/login survive; `wallet_save_config` keeps the stored one. - node: `start_wallet_child` opens the file, `open_wallet_with_passphrase` opens a file with a passphrase the user just typed and seals it only once a live daemon accepted it, `wallet_status` grows `wallet_open` and `needs_passphrase`. A child the RPC refuses is stopped rather than left inert; an install with no stored passphrase still starts, and says so. - tui: one-shot prompt (`WalletSetup::UnlockPass`) on a wallet that needs it, reachable from the saved-wallet picker and from `s`. - sdk: `openWalletWithPassphrase`, the two status fields, README flow. - docs: WALLET/THREAT_MODEL/README — the passphrase is kept, and the consequence (the store passphrase is sufficient to spend) is stated rather than implied. Tests: 4 new node tests drive a real child lifecycle against a loopback wallet RPC (open on restart, no open without a passphrase, refused passphrase, sealed-on-success), a `tests/wallet.rs` test asserts the bytes sent (`open_wallet` + filename + password), and `tests/store.rs` covers the sealed column and the plaintext->encrypted upgrade with it set. Mutation-checked: stubbing the two open paths fails all four.
2026-09-22 12:52:08 -04:00
wallet_passphrase: Zeroizing::new(String::new()),
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
}
}
wallet: actually open the wallet file, and remember its passphrase `monero-wallet-rpc` starts with no wallet open and keeps one only for the life of its process, so a restart, a Lock/unlock or a wallet re-point left a live child answering `-13 No wallet file` to every read while the file sat on disk. The app now opens the configured catalogue file itself (`Wallet::open_wallet`, over RPC — never `--wallet-file`/`--password` on argv, which `ps` exposes) after the child is up, and keeps the passphrase that does it, sealed with the store data key beside the RPC creds under its own AAD. - core: `Wallet::open_wallet`, `WalletConfig::wallet_passphrase` (+ `with_wallet_passphrase`, redacted Debug, kept out of the endpoint config), `Error::is_unreachable` for the one retryable class (the port binds a moment after spawn; a timeout is not a start in progress). - store: `wallet_config.sealed_passphrase` column (additive, AAD `onionwire-store-v1:wallet-passphrase`), read-modify-written so the endpoint/login survive; `wallet_save_config` keeps the stored one. - node: `start_wallet_child` opens the file, `open_wallet_with_passphrase` opens a file with a passphrase the user just typed and seals it only once a live daemon accepted it, `wallet_status` grows `wallet_open` and `needs_passphrase`. A child the RPC refuses is stopped rather than left inert; an install with no stored passphrase still starts, and says so. - tui: one-shot prompt (`WalletSetup::UnlockPass`) on a wallet that needs it, reachable from the saved-wallet picker and from `s`. - sdk: `openWalletWithPassphrase`, the two status fields, README flow. - docs: WALLET/THREAT_MODEL/README — the passphrase is kept, and the consequence (the store passphrase is sufficient to spend) is stated rather than implied. Tests: 4 new node tests drive a real child lifecycle against a loopback wallet RPC (open on restart, no open without a passphrase, refused passphrase, sealed-on-success), a `tests/wallet.rs` test asserts the bytes sent (`open_wallet` + filename + password), and `tests/store.rs` covers the sealed column and the plaintext->encrypted upgrade with it set. Mutation-checked: stubbing the two open paths fails all four.
2026-09-22 12:52:08 -04:00
/// Set the passphrase that opens the wallet file this config's child is
/// pointed at. Chainable, and the only way to supply it from outside the
/// crate: the field is public too, but a builder keeps a caller from
/// forgetting that it is sealed beside the login.
pub fn with_wallet_passphrase(mut self, passphrase: &str) -> Self {
self.wallet_passphrase = Zeroizing::new(passphrase.to_string());
self
}
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
/// 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)
wallet: actually open the wallet file, and remember its passphrase `monero-wallet-rpc` starts with no wallet open and keeps one only for the life of its process, so a restart, a Lock/unlock or a wallet re-point left a live child answering `-13 No wallet file` to every read while the file sat on disk. The app now opens the configured catalogue file itself (`Wallet::open_wallet`, over RPC — never `--wallet-file`/`--password` on argv, which `ps` exposes) after the child is up, and keeps the passphrase that does it, sealed with the store data key beside the RPC creds under its own AAD. - core: `Wallet::open_wallet`, `WalletConfig::wallet_passphrase` (+ `with_wallet_passphrase`, redacted Debug, kept out of the endpoint config), `Error::is_unreachable` for the one retryable class (the port binds a moment after spawn; a timeout is not a start in progress). - store: `wallet_config.sealed_passphrase` column (additive, AAD `onionwire-store-v1:wallet-passphrase`), read-modify-written so the endpoint/login survive; `wallet_save_config` keeps the stored one. - node: `start_wallet_child` opens the file, `open_wallet_with_passphrase` opens a file with a passphrase the user just typed and seals it only once a live daemon accepted it, `wallet_status` grows `wallet_open` and `needs_passphrase`. A child the RPC refuses is stopped rather than left inert; an install with no stored passphrase still starts, and says so. - tui: one-shot prompt (`WalletSetup::UnlockPass`) on a wallet that needs it, reachable from the saved-wallet picker and from `s`. - sdk: `openWalletWithPassphrase`, the two status fields, README flow. - docs: WALLET/THREAT_MODEL/README — the passphrase is kept, and the consequence (the store passphrase is sufficient to spend) is stated rather than implied. Tests: 4 new node tests drive a real child lifecycle against a loopback wallet RPC (open on restart, no open without a passphrase, refused passphrase, sealed-on-success), a `tests/wallet.rs` test asserts the bytes sent (`open_wallet` + filename + password), and `tests/store.rs` covers the sealed column and the plaintext->encrypted upgrade with it set. Mutation-checked: stubbing the two open paths fails all four.
2026-09-22 12:52:08 -04:00
.field(
"wallet_passphrase",
&if self.wallet_passphrase.is_empty() {
"<none>"
} else {
"<redacted>"
},
)
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
.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
wallet: actually open the wallet file, and remember its passphrase `monero-wallet-rpc` starts with no wallet open and keeps one only for the life of its process, so a restart, a Lock/unlock or a wallet re-point left a live child answering `-13 No wallet file` to every read while the file sat on disk. The app now opens the configured catalogue file itself (`Wallet::open_wallet`, over RPC — never `--wallet-file`/`--password` on argv, which `ps` exposes) after the child is up, and keeps the passphrase that does it, sealed with the store data key beside the RPC creds under its own AAD. - core: `Wallet::open_wallet`, `WalletConfig::wallet_passphrase` (+ `with_wallet_passphrase`, redacted Debug, kept out of the endpoint config), `Error::is_unreachable` for the one retryable class (the port binds a moment after spawn; a timeout is not a start in progress). - store: `wallet_config.sealed_passphrase` column (additive, AAD `onionwire-store-v1:wallet-passphrase`), read-modify-written so the endpoint/login survive; `wallet_save_config` keeps the stored one. - node: `start_wallet_child` opens the file, `open_wallet_with_passphrase` opens a file with a passphrase the user just typed and seals it only once a live daemon accepted it, `wallet_status` grows `wallet_open` and `needs_passphrase`. A child the RPC refuses is stopped rather than left inert; an install with no stored passphrase still starts, and says so. - tui: one-shot prompt (`WalletSetup::UnlockPass`) on a wallet that needs it, reachable from the saved-wallet picker and from `s`. - sdk: `openWalletWithPassphrase`, the two status fields, README flow. - docs: WALLET/THREAT_MODEL/README — the passphrase is kept, and the consequence (the store passphrase is sufficient to spend) is stated rather than implied. Tests: 4 new node tests drive a real child lifecycle against a loopback wallet RPC (open on restart, no open without a passphrase, refused passphrase, sealed-on-success), a `tests/wallet.rs` test asserts the bytes sent (`open_wallet` + filename + password), and `tests/store.rs` covers the sealed column and the plaintext->encrypted upgrade with it set. Mutation-checked: stubbing the two open paths fails all four.
2026-09-22 12:52:08 -04:00
&& self.wallet_passphrase.as_str() == other.wallet_passphrase.as_str()
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
}
}
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
}
#[derive(Clone)]
struct Endpoint {
host: String,
port: u16,
path: String,
user: String,
pass: Zeroizing<String>,
}
impl std::fmt::Debug for Endpoint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Endpoint")
.field("host", &self.host)
.field("port", &self.port)
.field("path", &self.path)
.field("user", &self.user)
.field("pass", &"<redacted>")
.finish()
}
}
/// The private keys of the wallet file the RPC currently has open.
///
/// `view_key` is the private view key; `spend_key` is the private spend key and
/// is `None` — not an error — for a view-only wallet, which has no spend key to
/// hand out. Both are secrets: never log them, never persist them, and never put
/// them in an error string.
pub struct WalletKeys {
pub view_key: String,
pub spend_key: Option<String>,
}
/// Hand-written so a stray `{:?}` cannot print a private key.
impl std::fmt::Debug for WalletKeys {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WalletKeys")
.field("view_key", &"<redacted>")
.field("spend_key", &self.spend_key.as_ref().map(|_| "<redacted>"))
.finish()
}
}
#[derive(Debug, Clone)]
pub struct Wallet {
endpoint: Option<Endpoint>,
no_spend: bool,
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// Budget for loopback management calls (`get_address`, `query_key`,
/// create/import). The wallet child is on the same box, so this stays short.
timeout_local: Duration,
/// Budget for calls that wait on the daemon (`get_info`, `get_transfers`,
/// `transfer`). A first sync or a remote daemon legitimately outlasts the
/// local budget, and treating that as "down" is what left receipts
/// permanently unverified.
timeout_chain: Duration,
}
/// The `get_info` fields one wallet-RPC probe carries: the readiness verdict and
/// the numbers a status line shows. `0` height/target means the wallet RPC
/// answered without a number — unknown, never "caught up", and never a percent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChainInfo {
/// The wallet RPC said `synchronized: true`. A missing field is `false`.
pub synchronized: bool,
/// Blocks the wallet's daemon has, as the wallet RPC reports them.
pub height: u64,
/// Blocks that daemon is syncing towards; `0` when it reported none.
pub target_height: u64,
}
impl ChainInfo {
/// The readiness predicate: the daemon reached the tip and the wallet
/// scanned up to it. `synchronized` must be explicitly true, and a chain
/// with no height is not ready.
pub fn ready(&self) -> bool {
self.synchronized
&& self.height > 0
&& (self.target_height == 0 || self.height >= self.target_height)
}
}
/// What /tip says when the wallet cannot spend. Same text for the explicit
/// `ONIONWIRE_WALLET_NO_SPEND=1` switch and for a view-only wallet detected over
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: 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_RPC_ERROR_CODE_WATCH_ONLY` in monero's
/// `src/wallet/wallet_rpc_server_error_codes.h`.
const WATCH_ONLY_CODE: i64 = -29;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransferRow {
pub txid: String,
pub amount: String,
pub address: String,
}
/// Wallet file name used for in-app create/import (`--wallet-dir` on the RPC).
pub const DEFAULT_WALLET_FILENAME: &str = "onionwire";
/// Shown before a spend-capable create. Not a tooltip — the user must confirm.
pub const SPEND_AUTHORITY_WARNING: &str = "this wallet file can spend. anyone with its passphrase or the RPC creds can move the balance. write down the seed. do not leave it on a box you do not trust.";
const RPC_TIMEOUT: Duration = Duration::from_secs(5);
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// Budget for calls that wait on the daemon (`get_info`, `get_transfers`,
/// `transfer`). A first sync or a remote daemon legitimately outlasts the
/// loopback budget; a 5s cap there leaves receipts permanently unverified.
pub const CHAIN_RPC_TIMEOUT: Duration = Duration::from_secs(60);
impl Wallet {
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// The one place the budgets are defaulted. Callers adjust them with
/// [`Wallet::with_timeouts`].
fn new(endpoint: Option<Endpoint>, no_spend: bool) -> Self {
Self {
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
endpoint,
no_spend,
timeout_local: RPC_TIMEOUT,
timeout_chain: CHAIN_RPC_TIMEOUT,
}
}
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
pub fn disabled() -> Self {
Self::new(None, false)
}
/// `ONIONWIRE_WALLET_NO_SPEND=1` asks for a view-only deployment: `/tip` is
/// refused locally, before any RPC dial. `/pay` and receipt verification
/// keep working.
pub fn from_env() -> Self {
let no_spend = env_flag("ONIONWIRE_WALLET_NO_SPEND");
match std::env::var("ONIONWIRE_WALLET_RPC") {
// The URL can carry `user:pass@` in its userinfo: keep it in a
// wiping buffer, not a bare `String`.
Ok(s) if !s.trim().is_empty() => {
let url = Zeroizing::new(s);
let login = std::env::var("ONIONWIRE_WALLET_RPC_LOGIN")
.ok()
.map(|v| Zeroizing::new(v.trim().to_string()))
.filter(|v| !v.is_empty());
match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) {
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
Ok(endpoint) => Self::new(Some(endpoint), no_spend),
Err(e) => {
eprintln!("ONIONWIRE_WALLET_RPC: {e}");
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
Self::new(None, no_spend)
}
}
}
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
_ => Self::new(None, no_spend),
}
}
pub fn from_url(url: &str) -> Result<Self> {
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
Ok(Self::new(Some(parse_http_url(url, None)?), false))
}
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,
wallet: actually open the wallet file, and remember its passphrase `monero-wallet-rpc` starts with no wallet open and keeps one only for the life of its process, so a restart, a Lock/unlock or a wallet re-point left a live child answering `-13 No wallet file` to every read while the file sat on disk. The app now opens the configured catalogue file itself (`Wallet::open_wallet`, over RPC — never `--wallet-file`/`--password` on argv, which `ps` exposes) after the child is up, and keeps the passphrase that does it, sealed with the store data key beside the RPC creds under its own AAD. - core: `Wallet::open_wallet`, `WalletConfig::wallet_passphrase` (+ `with_wallet_passphrase`, redacted Debug, kept out of the endpoint config), `Error::is_unreachable` for the one retryable class (the port binds a moment after spawn; a timeout is not a start in progress). - store: `wallet_config.sealed_passphrase` column (additive, AAD `onionwire-store-v1:wallet-passphrase`), read-modify-written so the endpoint/login survive; `wallet_save_config` keeps the stored one. - node: `start_wallet_child` opens the file, `open_wallet_with_passphrase` opens a file with a passphrase the user just typed and seals it only once a live daemon accepted it, `wallet_status` grows `wallet_open` and `needs_passphrase`. A child the RPC refuses is stopped rather than left inert; an install with no stored passphrase still starts, and says so. - tui: one-shot prompt (`WalletSetup::UnlockPass`) on a wallet that needs it, reachable from the saved-wallet picker and from `s`. - sdk: `openWalletWithPassphrase`, the two status fields, README flow. - docs: WALLET/THREAT_MODEL/README — the passphrase is kept, and the consequence (the store passphrase is sufficient to spend) is stated rather than implied. Tests: 4 new node tests drive a real child lifecycle against a loopback wallet RPC (open on restart, no open without a passphrase, refused passphrase, sealed-on-success), a `tests/wallet.rs` test asserts the bytes sent (`open_wallet` + filename + password), and `tests/store.rs` covers the sealed column and the plaintext->encrypted upgrade with it set. Mutation-checked: stubbing the two open paths fails all four.
2026-09-22 12:52:08 -04:00
// Not known here: the passphrase is the *file's*, and this builds
// the config of the RPC endpoint in use. Callers that persist a
// config do a read-modify-write so the stored one survives.
wallet_passphrase: Zeroizing::new(String::new()),
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
})
}
/// 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
}
/// No-spend (view-only) mode. Same switch as `ONIONWIRE_WALLET_NO_SPEND`.
pub fn with_no_spend(mut self, on: bool) -> Self {
self.no_spend = on;
self
}
pub fn no_spend(&self) -> bool {
self.no_spend
}
pub fn configured(&self) -> bool {
self.endpoint.is_some()
}
pub async fn get_address(&self) -> Result<String> {
let v = self
.rpc("get_address", serde_json::json!({"account_index": 0}))
.await?;
json_str(&v, "address")
}
pub async fn create_address(&self) -> Result<String> {
let v = self
.rpc("create_address", serde_json::json!({"account_index": 0}))
.await?;
json_str(&v, "address")
}
pub async fn transfer(&self, address: &str, amount: u64) -> Result<String> {
if self.no_spend {
return Err(Error(VIEW_ONLY_MSG.into()));
}
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
// Honest gate: a wallet that has not caught up to the chain tip cannot
// build a spend, so refuse instead of letting the RPC fail opaquely.
// Fail closed — if readiness cannot be proven, the spend is refused.
if !self.can_spend().await {
return Err(Error(NOT_SYNCED_MSG.into()));
}
let sent = self
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
.chain_rpc(
"transfer",
serde_json::json!({
"destinations": [{"amount": amount, "address": address}],
"account_index": 0
}),
)
.await;
let v = match sent {
Ok(v) => v,
// The wallet's own refusal is opaque, so ask the documented
// pre-transfer signal before surfacing it. Fail closed: if the
// probe cannot answer, the original error stands.
Err(e) => {
if self.view_only().await {
return Err(Error(VIEW_ONLY_MSG.into()));
}
return Err(e);
}
};
json_str(&v, "tx_hash")
}
/// View-only detection over RPC: `query_key` with `key_type=spend_key` is
/// the signal monero actually exposes for a wallet with no spend key.
/// A view-only wallet answers `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (-29)
/// ("Cannot retrieve spend key"); a spend-capable wallet returns the key,
/// which this discards.
/// Source: `src/wallet/wallet_rpc_server.cpp` `on_query_key`.
async fn view_only(&self) -> bool {
matches!(
self.rpc("query_key", serde_json::json!({"key_type": "spend_key"}))
.await,
Err(e) if e.to_string() == VIEW_ONLY_MSG
)
}
pub async fn get_transfers(&self) -> Result<Vec<TransferRow>> {
let v = self
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
.chain_rpc(
"get_transfers",
serde_json::json!({"in": true, "pending": true}),
)
.await?;
let mut out = Vec::new();
for key in ["in", "pending"] {
if let Some(arr) = v.get(key).and_then(|x| x.as_array()) {
for item in arr {
out.push(TransferRow {
txid: json_str(item, "txid").unwrap_or_default(),
amount: json_amount(item),
address: json_str(item, "address").unwrap_or_default(),
});
}
}
}
Ok(out)
}
/// Monero-wallet-rpc `get_balance`, account_index 0. Returns the "balance"
/// field as a piconero string on success; the caller can format it with
/// `pay::atomic_to_xmr_str` if it wants a human-readable form.
pub async fn get_balance(&self) -> Result<String> {
let v = self
.rpc("get_balance", serde_json::json!({"account_index": 0}))
.await?;
json_str(&v, "balance")
}
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// Unlocked balance in piconero — the part a spend can actually use.
pub async fn unlocked_balance(&self) -> Result<u64> {
let v = self
.rpc("get_balance", serde_json::json!({"account_index": 0}))
.await?;
json_str(&v, "unlocked_balance")?
.trim()
.parse::<u64>()
.map_err(|_| Error("wallet RPC returned a non-numeric unlocked_balance".into()))
}
/// The real readiness predicate: the daemon has reached the chain tip and
/// the wallet has scanned up to it. `synchronized` must be explicitly true —
/// a missing field is not-ready, never a silent pass.
pub async fn chain_ready(&self) -> Result<bool> {
Ok(self.chain_info().await?.ready())
}
/// One `get_info` round trip, carrying both the readiness fields and the
/// numbers a status line shows — the status line and the spend gate ask the
/// same question, so they ask it once. `0` height/target means the wallet
/// RPC answered without a number: unknown, never "caught up".
pub async fn chain_info(&self) -> Result<ChainInfo> {
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 v = self.chain_rpc("get_info", serde_json::json!({})).await?;
Ok(ChainInfo {
synchronized: v
.get("synchronized")
.and_then(|b| b.as_bool())
.unwrap_or(false),
height: v.get("height").and_then(|h| h.as_u64()).unwrap_or(0),
target_height: v.get("target_height").and_then(|h| h.as_u64()).unwrap_or(0),
})
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
}
/// May this wallet attempt a spend? Fail closed: any readiness doubt is a
/// refusal, and a view-only/no-spend wallet never spends.
pub async fn can_spend(&self) -> bool {
!self.no_spend && self.configured() && self.chain_ready().await.unwrap_or(false)
}
/// The stricter signal for the spend UI: chain-ready *and* holding unlocked
/// funds. Zero unlocked balance is not spend-ready.
pub async fn spend_ready(&self) -> Result<bool> {
if !self.chain_ready().await? {
return Ok(false);
}
Ok(self.unlocked_balance().await? > 0)
}
/// Receipt verification is only honest on a synced wallet: `get_transfers`
/// on a wallet that has not scanned to the tip cannot see the tx, so a
/// "miss" would be a lie. Until ready, receipts stay `verified=0`.
pub async fn can_verify_receipts(&self) -> bool {
self.configured() && self.chain_ready().await.unwrap_or(false)
}
/// Create a new spend-capable wallet on the RPC (`create_wallet`). The
/// user does not paste a key — the daemon generates the seed. Returns that
/// seed once (from `query_key mnemonic`) so the UI can show a backup
/// screen. Needs `--wallet-dir` on the RPC.
pub async fn create_wallet(&self, filename: &str, password: &str) -> Result<String> {
let filename = filename.trim();
if filename.is_empty() {
return Err(Error("wallet filename required".into()));
}
if password.is_empty() {
return Err(Error("wallet passphrase required".into()));
}
self.rpc(
"create_wallet",
serde_json::json!({
"filename": filename,
"password": password,
"language": "English"
}),
)
.await?;
let v = self
.rpc("query_key", serde_json::json!({"key_type": "mnemonic"}))
.await
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}")))?;
json_str(&v, "key")
}
wallet: actually open the wallet file, and remember its passphrase `monero-wallet-rpc` starts with no wallet open and keeps one only for the life of its process, so a restart, a Lock/unlock or a wallet re-point left a live child answering `-13 No wallet file` to every read while the file sat on disk. The app now opens the configured catalogue file itself (`Wallet::open_wallet`, over RPC — never `--wallet-file`/`--password` on argv, which `ps` exposes) after the child is up, and keeps the passphrase that does it, sealed with the store data key beside the RPC creds under its own AAD. - core: `Wallet::open_wallet`, `WalletConfig::wallet_passphrase` (+ `with_wallet_passphrase`, redacted Debug, kept out of the endpoint config), `Error::is_unreachable` for the one retryable class (the port binds a moment after spawn; a timeout is not a start in progress). - store: `wallet_config.sealed_passphrase` column (additive, AAD `onionwire-store-v1:wallet-passphrase`), read-modify-written so the endpoint/login survive; `wallet_save_config` keeps the stored one. - node: `start_wallet_child` opens the file, `open_wallet_with_passphrase` opens a file with a passphrase the user just typed and seals it only once a live daemon accepted it, `wallet_status` grows `wallet_open` and `needs_passphrase`. A child the RPC refuses is stopped rather than left inert; an install with no stored passphrase still starts, and says so. - tui: one-shot prompt (`WalletSetup::UnlockPass`) on a wallet that needs it, reachable from the saved-wallet picker and from `s`. - sdk: `openWalletWithPassphrase`, the two status fields, README flow. - docs: WALLET/THREAT_MODEL/README — the passphrase is kept, and the consequence (the store passphrase is sufficient to spend) is stated rather than implied. Tests: 4 new node tests drive a real child lifecycle against a loopback wallet RPC (open on restart, no open without a passphrase, refused passphrase, sealed-on-success), a `tests/wallet.rs` test asserts the bytes sent (`open_wallet` + filename + password), and `tests/store.rs` covers the sealed column and the plaintext->encrypted upgrade with it set. Mutation-checked: stubbing the two open paths fails all four.
2026-09-22 12:52:08 -04:00
/// Open a wallet *file* on the RPC (`open_wallet`).
///
/// `monero-wallet-rpc` starts with no wallet open, and `create_wallet` /
/// `restore_deterministic_wallet` leave theirs open for that process only:
/// after a restart every read answers `-13 No wallet file` even though the
/// file is on disk. This is the call that opens it, and the only way a
/// wallet survives the child being restarted.
///
/// The passphrase travels in the JSON-RPC body, never on the argv: `ps` is
/// world-readable for the same user, and `--wallet-file`/`--password`
/// would put the secret there. `filename` is a name inside the child's
/// `--wallet-dir`, never a path.
///
/// A wrong passphrase is the RPC's own error (the daemon does not open a
/// file it cannot decrypt); it is surfaced as-is, never retried into a
/// generic failure by the caller.
pub async fn open_wallet(&self, filename: &str, password: &str) -> Result<()> {
let filename = filename.trim();
if filename.is_empty() {
return Err(Error("wallet filename required".into()));
}
if password.is_empty() {
return Err(Error("wallet passphrase required".into()));
}
self.rpc(
"open_wallet",
serde_json::json!({
"filename": filename,
"password": password,
}),
)
.await?;
Ok(())
}
/// Re-read the seed of the wallet file the RPC has open (`query_key
/// mnemonic`). After `create_wallet` this is the **only** way to recover a
/// created wallet's seed, so the UI can offer a backup action instead of
/// showing it once. It needs an open, spend-capable wallet file; a
/// watch-only one answers the RPC's `-29` and surfaces as the view-only
/// refusal.
///
/// The returned words are a spend key: never log them, never store them,
/// and never put them in an error string.
pub async fn mnemonic(&self) -> Result<String> {
if !self.configured() {
return Err(Error(NOT_CONFIGURED_MSG.into()));
}
let v = self
.rpc("query_key", serde_json::json!({"key_type": "mnemonic"}))
.await?;
json_str(&v, "key")
}
/// The wallet file's private keys, as the RPC reports them: `query_key`
/// `view_key` and `query_key` `spend_key`.
///
/// Both come from the wallet file the child currently has **open** — this is
/// not a "read any saved wallet's keys" accessor, and it cannot be: the RPC
/// only ever answers for its open file.
///
/// A view-only wallet has no spend key: its `query_key spend_key` answers
/// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (-29), which maps to
/// `spend_key: None` rather than an error, matching the `-29` view-only
/// detection the transfer probe already uses. Refuses locally, before any
/// dial, when the wallet is not configured.
///
/// The two values are spend secrets: never log them, never store them, never
/// put them in an error string. [`WalletKeys`]'s `Debug` redacts both.
pub async fn keys(&self) -> Result<WalletKeys> {
if !self.configured() {
return Err(Error(NOT_CONFIGURED_MSG.into()));
}
let v = self
.rpc("query_key", serde_json::json!({"key_type": "view_key"}))
.await?;
let view_key = json_str(&v, "key")?;
// Asked second and separately: on a view-only wallet this is the call
// that carries the `-29`, and `None` is the honest answer there.
let spend_key = match self
.rpc("query_key", serde_json::json!({"key_type": "spend_key"}))
.await
{
Ok(v) => Some(json_str(&v, "key")?),
Err(e) if e.to_string() == VIEW_ONLY_MSG => None,
Err(e) => return Err(e),
};
Ok(WalletKeys {
view_key,
spend_key,
})
}
/// Import an existing wallet from its 25-word seed. This is the only path
/// that takes a user-supplied secret.
pub async fn restore_wallet(&self, filename: &str, password: &str, seed: &str) -> Result<()> {
let filename = filename.trim();
if filename.is_empty() {
return Err(Error("wallet filename required".into()));
}
if password.is_empty() {
return Err(Error("wallet passphrase required".into()));
}
let seed = seed.trim();
if seed.is_empty() {
return Err(Error("seed required to import a wallet".into()));
}
self.rpc(
"restore_deterministic_wallet",
serde_json::json!({
"filename": filename,
"password": password,
"seed": seed,
"language": "English"
}),
)
.await?;
Ok(())
}
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
/// Loopback management call: the wallet child is on the same box, so it gets
/// the short budget.
async fn rpc(&self, method: &str, params: serde_json::Value) -> Result<serde_json::Value> {
wallet: app-owned child lifecycle + user-chosen ChainSource The app now owns monero-wallet-rpc (and monerod when the chain source is local) instead of requiring the user to start them and export ONIONWIRE_WALLET_RPC. - ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host, port }. No default remote node; Remote is only constructed from explicit user input. A .onion Remote is refused without a SOCKS proxy (separate card). - WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with --rpc-bind-ip 127.0.0.1, a random free loopback port, generated --rpc-login, and --wallet-dir /wallet; monerod too for a local source. --trusted-daemon is never passed. - Generated RPC creds are sealed in the encrypted SQLCipher store (wallet_child table, AEAD on top of whole-db encryption), never a plaintext file. The Wallet client is built from the generated loopback URL, not from_env. - Readiness predicate: chain_ready() requires synchronized==true, height>0, height>=target_height; can_spend() and can_verify_receipts() gate on it. Unsynced -> receipts stay verified=0, spend refused with a clear message. - Backend-aware timeouts: local management calls keep 5s; chain-dependent calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT), because a first sync or a remote daemon outlasts 5s and a 5s cap there is what left receipts permanently unverified. - node.rs ingest_receipt gates on can_verify_receipts() instead of configured() alone. - docs/WALLET.md rewritten for the child lifecycle + chain source. Base: feat/wallet-create-import (PR #66). Do not rebase onto main. Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
self.rpc_with(method, params, self.timeout_local).await
}
/// Chain-dependent call (`get_info`, `get_transfers`, `transfer`): it waits
/// on the daemon, so it gets the longer budget.
async fn chain_rpc(
&self,
method: &str,
params: serde_json::Value,
) -> Result<serde_json::Value> {
self.rpc_with(method, params, self.timeout_chain).await
}
async fn rpc_with(
&self,
method: &str,
params: serde_json::Value,
budget: Duration,
) -> Result<serde_json::Value> {
let ep = self
.endpoint
.as_ref()
.ok_or_else(|| Error("not configured".into()))?;
let body = serde_json::json!({
"jsonrpc": "2.0",
"id": "0",
"method": method,
"params": params,
})
.to_string();
wallet: answer the Digest challenge on the connection that issued it monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the `http_server_auth` lives inside `http_custom_handler`, which is created per connection, so its nonce starts empty and any request without a valid `Authorization` field mints a fresh one. The client opened a *second* connection for the authenticated retry, presenting a nonce that socket never issued — so a real wallet RPC answered 401 forever, however correct the login was. That is the `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the canned mocks replayed the challenge on any socket, so they stayed green. - `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry, no `Connection: close` on the challenge (epee closes the socket with the 401 when the request asks for it), `read_one_response` honouring `Content-Length` (a keep-alive response never ends in EOF; with no length the body ends at EOF, which is what keeps the 1 MiB cap meaningful for an open RPC). - A 401 after our *own* challenge now reads: the login does not match the child's `--rpc-login`. - Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce: `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one connection, and a nonce presented on another connection is refused. - `docs/WALLET.md`: what a 401 means and why it is not the flow. Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`, `--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401 Unauthorized`; fixed tree → `connected: true` with the wallet's real address.
2026-09-20 09:17:05 -04:00
let (challenged, raw) = post_digest(ep, &body, budget).await?;
let status = http_status(&raw).unwrap_or(0);
wallet: answer the Digest challenge on the connection that issued it monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the `http_server_auth` lives inside `http_custom_handler`, which is created per connection, so its nonce starts empty and any request without a valid `Authorization` field mints a fresh one. The client opened a *second* connection for the authenticated retry, presenting a nonce that socket never issued — so a real wallet RPC answered 401 forever, however correct the login was. That is the `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the canned mocks replayed the challenge on any socket, so they stayed green. - `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry, no `Connection: close` on the challenge (epee closes the socket with the 401 when the request asks for it), `read_one_response` honouring `Content-Length` (a keep-alive response never ends in EOF; with no length the body ends at EOF, which is what keeps the 1 MiB cap meaningful for an open RPC). - A 401 after our *own* challenge now reads: the login does not match the child's `--rpc-login`. - Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce: `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one connection, and a nonce presented on another connection is refused. - `docs/WALLET.md`: what a 401 means and why it is not the flow. Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`, `--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401 Unauthorized`; fixed tree → `connected: true` with the wallet's real address.
2026-09-20 09:17:05 -04:00
if status == 401 {
// A digest built from *this* connection's own challenge was
// refused, so the login is wrong, not the flow.
return Err(Error(
wallet: answer the Digest challenge on the connection that issued it monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the `http_server_auth` lives inside `http_custom_handler`, which is created per connection, so its nonce starts empty and any request without a valid `Authorization` field mints a fresh one. The client opened a *second* connection for the authenticated retry, presenting a nonce that socket never issued — so a real wallet RPC answered 401 forever, however correct the login was. That is the `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the canned mocks replayed the challenge on any socket, so they stayed green. - `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry, no `Connection: close` on the challenge (epee closes the socket with the 401 when the request asks for it), `read_one_response` honouring `Content-Length` (a keep-alive response never ends in EOF; with no length the body ends at EOF, which is what keeps the 1 MiB cap meaningful for an open RPC). - A 401 after our *own* challenge now reads: the login does not match the child's `--rpc-login`. - Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce: `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one connection, and a nonce presented on another connection is refused. - `docs/WALLET.md`: what a 401 means and why it is not the flow. Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`, `--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401 Unauthorized`; fixed tree → `connected: true` with the wallet's real address.
2026-09-20 09:17:05 -04:00
"wallet RPC digest rejected (HTTP 401) — the login does not match the child's --rpc-login"
.into(),
));
}
wallet: answer the Digest challenge on the connection that issued it monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the `http_server_auth` lives inside `http_custom_handler`, which is created per connection, so its nonce starts empty and any request without a valid `Authorization` field mints a fresh one. The client opened a *second* connection for the authenticated retry, presenting a nonce that socket never issued — so a real wallet RPC answered 401 forever, however correct the login was. That is the `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the canned mocks replayed the challenge on any socket, so they stayed green. - `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry, no `Connection: close` on the challenge (epee closes the socket with the 401 when the request asks for it), `read_one_response` honouring `Content-Length` (a keep-alive response never ends in EOF; with no length the body ends at EOF, which is what keeps the 1 MiB cap meaningful for an open RPC). - A 401 after our *own* challenge now reads: the login does not match the child's `--rpc-login`. - Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce: `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one connection, and a nonce presented on another connection is refused. - `docs/WALLET.md`: what a 401 means and why it is not the flow. Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`, `--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401 Unauthorized`; fixed tree → `connected: true` with the wallet's real address.
2026-09-20 09:17:05 -04:00
if !challenged && status == 200 {
return Err(Error(
wallet: answer the Digest challenge on the connection that issued it monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the `http_server_auth` lives inside `http_custom_handler`, which is created per connection, so its nonce starts empty and any request without a valid `Authorization` field mints a fresh one. The client opened a *second* connection for the authenticated retry, presenting a nonce that socket never issued — so a real wallet RPC answered 401 forever, however correct the login was. That is the `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the canned mocks replayed the challenge on any socket, so they stayed green. - `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry, no `Connection: close` on the challenge (epee closes the socket with the 401 when the request asks for it), `read_one_response` honouring `Content-Length` (a keep-alive response never ends in EOF; with no length the body ends at EOF, which is what keeps the 1 MiB cap meaningful for an open RPC). - A 401 after our *own* challenge now reads: the login does not match the child's `--rpc-login`. - Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce: `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one connection, and a nonce presented on another connection is refused. - `docs/WALLET.md`: what a 401 means and why it is not the flow. Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`, `--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401 Unauthorized`; fixed tree → `connected: true` with the wallet's real address.
2026-09-20 09:17:05 -04:00
"wallet RPC requires digest auth (open RPC refused)".into(),
));
}
parse_json_rpc(&raw)
}
}
pub fn transfers_match(rows: &[TransferRow], txid: &str, amount: &str, address: &str) -> bool {
if txid.is_empty() || amount.is_empty() || address.is_empty() {
return false;
}
rows.iter()
.any(|r| r.txid == txid && r.amount == amount && r.address == address)
}
fn credentials_required() -> Error {
Error("wallet RPC requires credentials (user:pass in URL or ONIONWIRE_WALLET_RPC_LOGIN)".into())
}
/// `1` / `true` / `yes` / `on` (case-insensitive) mean set; anything else (or
/// unset) means off.
fn env_flag(name: &str) -> bool {
matches!(
std::env::var(name)
.map(|v| v.trim().to_ascii_lowercase())
.as_deref(),
Ok("1" | "true" | "yes" | "on")
)
}
fn parse_login(login: &str) -> Result<(String, Zeroizing<String>)> {
let (user, pass) = login.split_once(':').ok_or_else(credentials_required)?;
if user.is_empty() || pass.is_empty() {
return Err(credentials_required());
}
Ok((user.to_string(), Zeroizing::new(pass.to_string())))
}
fn parse_http_url(url: &str, extra_login: Option<&str>) -> Result<Endpoint> {
let rest = url
.strip_prefix("http://")
.ok_or_else(|| Error("wallet RPC must be http:// (no TLS)".into()))?;
if rest.contains("://") {
return Err(Error("wallet RPC must be http:// (no TLS)".into()));
}
let (userinfo, rest) = match rest.rsplit_once('@') {
Some((ui, hostpart)) => (Some(ui), hostpart),
None => (None, rest),
};
let (user, pass) = match userinfo {
Some(ui) => parse_login(ui)?,
None => match extra_login {
Some(login) => parse_login(login)?,
None => return Err(credentials_required()),
},
};
let (hostport, path) = match rest.split_once('/') {
Some((hp, p)) => (hp, format!("/{p}")),
None => (rest, "/json_rpc".into()),
};
let path = if path == "/" {
"/json_rpc".into()
} else {
path
};
let (host, port) = parse_hostport(hostport)?;
if host.trim().to_ascii_lowercase().ends_with(".onion") {
return Err(Error(
"wallet RPC over .onion is not supported (loopback only; no Arti dial)".into(),
));
}
if !allowed_host(&host) {
return Err(Error("wallet RPC host must be loopback".into()));
}
Ok(Endpoint {
host,
port,
path,
user,
pass,
})
}
fn parse_hostport(hostport: &str) -> Result<(String, u16)> {
if let Some(rest) = hostport.strip_prefix('[') {
let (host, rest) = rest
.split_once(']')
.ok_or_else(|| Error("invalid IPv6 host".into()))?;
let port = match rest.strip_prefix(':') {
Some(p) if !p.is_empty() => parse_port(p)?,
_ => 18083,
};
if host.is_empty() {
return Err(Error("empty host".into()));
}
return Ok((host.to_string(), port));
}
match hostport.rsplit_once(':') {
Some((h, p)) if !h.is_empty() && !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) => {
Ok((h.to_string(), parse_port(p)?))
}
_ if !hostport.is_empty() => Ok((hostport.to_string(), 18083)),
_ => Err(Error("empty host".into())),
}
}
fn parse_port(p: &str) -> Result<u16> {
p.parse()
.map_err(|_| Error("invalid wallet RPC port".into()))
}
fn allowed_host(host: &str) -> bool {
let h = host.trim();
if h.eq_ignore_ascii_case("localhost") {
return true;
}
h.parse::<std::net::IpAddr>()
.map(|ip| ip.is_loopback())
.unwrap_or(false)
}
fn host_header(host: &str, port: u16) -> String {
if host.contains(':') {
format!("[{host}]:{port}")
} else {
format!("{host}:{port}")
}
}
const MAX_RPC_BYTES: usize = 1024 * 1024;
wallet: answer the Digest challenge on the connection that issued it monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the `http_server_auth` lives inside `http_custom_handler`, which is created per connection, so its nonce starts empty and any request without a valid `Authorization` field mints a fresh one. The client opened a *second* connection for the authenticated retry, presenting a nonce that socket never issued — so a real wallet RPC answered 401 forever, however correct the login was. That is the `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the canned mocks replayed the challenge on any socket, so they stayed green. - `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry, no `Connection: close` on the challenge (epee closes the socket with the 401 when the request asks for it), `read_one_response` honouring `Content-Length` (a keep-alive response never ends in EOF; with no length the body ends at EOF, which is what keeps the 1 MiB cap meaningful for an open RPC). - A 401 after our *own* challenge now reads: the login does not match the child's `--rpc-login`. - Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce: `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one connection, and a nonce presented on another connection is refused. - `docs/WALLET.md`: what a 401 means and why it is not the flow. Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`, `--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401 Unauthorized`; fixed tree → `connected: true` with the wallet's real address.
2026-09-20 09:17:05 -04:00
/// One loopback connection: ask for the digest challenge, answer it, and hand
/// back `(was_challenged, final_response)`.
///
/// The retry has to ride the **same socket** as the challenge. epee owns its
/// digest state per connection — `http_custom_handler` holds the
/// `http_server_auth`, whose session starts with an empty nonce and counter 0,
/// and any request without a valid `Authorization` field makes it mint a fresh
/// nonce. A retry that opens a new socket presents a nonce that connection never
/// issued, so `monero-wallet-rpc` answers 401 again, permanently. That is the
/// 401 the TUI and Android showed against a real wallet RPC while a canned mock
/// (which replays the challenge on any socket) stayed green.
async fn post_digest(ep: &Endpoint, body: &str, budget: Duration) -> Result<(bool, Vec<u8>)> {
tokio::time::timeout(budget, http_digest(ep, body))
.await
.map_err(|_| Error("wallet RPC timed out".into()))?
}
wallet: answer the Digest challenge on the connection that issued it monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the `http_server_auth` lives inside `http_custom_handler`, which is created per connection, so its nonce starts empty and any request without a valid `Authorization` field mints a fresh one. The client opened a *second* connection for the authenticated retry, presenting a nonce that socket never issued — so a real wallet RPC answered 401 forever, however correct the login was. That is the `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the canned mocks replayed the challenge on any socket, so they stayed green. - `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry, no `Connection: close` on the challenge (epee closes the socket with the 401 when the request asks for it), `read_one_response` honouring `Content-Length` (a keep-alive response never ends in EOF; with no length the body ends at EOF, which is what keeps the 1 MiB cap meaningful for an open RPC). - A 401 after our *own* challenge now reads: the login does not match the child's `--rpc-login`. - Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce: `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one connection, and a nonce presented on another connection is refused. - `docs/WALLET.md`: what a 401 means and why it is not the flow. Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`, `--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401 Unauthorized`; fixed tree → `connected: true` with the wallet's real address.
2026-09-20 09:17:05 -04:00
async fn http_digest(ep: &Endpoint, body: &str) -> Result<(bool, Vec<u8>)> {
let mut stream = TcpStream::connect((ep.host.as_str(), ep.port))
.await
.map_err(|e| Error(format!("wallet connect: {e}")))?;
// No `Connection: close` on the challenge: epee closes the socket with the
// 401 when the request asks for it, and the retry needs this connection.
let req = build_req(ep, body, None, false);
stream
.write_all(req.as_bytes())
.await
.map_err(|e| Error(format!("wallet write: {e}")))?;
let raw = read_one_response(&mut stream).await?;
let status = http_status(&raw).unwrap_or(0);
if status != 401 {
return Ok((false, raw));
}
let challenge = www_authenticate(&raw)
.ok_or_else(|| Error("wallet RPC digest required (--rpc-login / HTTP Digest)".into()))?;
if !challenge.trim().to_ascii_lowercase().starts_with("digest") {
return Err(Error(
"wallet RPC digest required (--rpc-login / HTTP Digest)".into(),
));
}
let auth = digest_authorization(ep, &challenge)?;
let req = build_req(ep, body, Some(&auth), true);
stream
.write_all(req.as_bytes())
.await
.map_err(|e| Error(format!("wallet write: {e}")))?;
Ok((true, read_to_eof(&mut stream).await?))
}
fn build_req(ep: &Endpoint, body: &str, authorization: Option<&str>, close: bool) -> String {
let host_hdr = host_header(&ep.host, ep.port);
let mut req = format!(
wallet: answer the Digest challenge on the connection that issued it monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the `http_server_auth` lives inside `http_custom_handler`, which is created per connection, so its nonce starts empty and any request without a valid `Authorization` field mints a fresh one. The client opened a *second* connection for the authenticated retry, presenting a nonce that socket never issued — so a real wallet RPC answered 401 forever, however correct the login was. That is the `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the canned mocks replayed the challenge on any socket, so they stayed green. - `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry, no `Connection: close` on the challenge (epee closes the socket with the 401 when the request asks for it), `read_one_response` honouring `Content-Length` (a keep-alive response never ends in EOF; with no length the body ends at EOF, which is what keeps the 1 MiB cap meaningful for an open RPC). - A 401 after our *own* challenge now reads: the login does not match the child's `--rpc-login`. - Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce: `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one connection, and a nonce presented on another connection is refused. - `docs/WALLET.md`: what a 401 means and why it is not the flow. Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`, `--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401 Unauthorized`; fixed tree → `connected: true` with the wallet's real address.
2026-09-20 09:17:05 -04:00
"POST {} HTTP/1.1\r\nHost: {host_hdr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n",
ep.path,
body.len()
);
wallet: answer the Digest challenge on the connection that issued it monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the `http_server_auth` lives inside `http_custom_handler`, which is created per connection, so its nonce starts empty and any request without a valid `Authorization` field mints a fresh one. The client opened a *second* connection for the authenticated retry, presenting a nonce that socket never issued — so a real wallet RPC answered 401 forever, however correct the login was. That is the `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the canned mocks replayed the challenge on any socket, so they stayed green. - `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry, no `Connection: close` on the challenge (epee closes the socket with the 401 when the request asks for it), `read_one_response` honouring `Content-Length` (a keep-alive response never ends in EOF; with no length the body ends at EOF, which is what keeps the 1 MiB cap meaningful for an open RPC). - A 401 after our *own* challenge now reads: the login does not match the child's `--rpc-login`. - Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce: `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one connection, and a nonce presented on another connection is refused. - `docs/WALLET.md`: what a 401 means and why it is not the flow. Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`, `--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401 Unauthorized`; fixed tree → `connected: true` with the wallet's real address.
2026-09-20 09:17:05 -04:00
if close {
req.push_str("Connection: close\r\n");
}
if let Some(auth) = authorization {
req.push_str("Authorization: ");
req.push_str(auth);
req.push_str("\r\n");
}
req.push_str("\r\n");
req.push_str(body);
req
}
wallet: answer the Digest challenge on the connection that issued it monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the `http_server_auth` lives inside `http_custom_handler`, which is created per connection, so its nonce starts empty and any request without a valid `Authorization` field mints a fresh one. The client opened a *second* connection for the authenticated retry, presenting a nonce that socket never issued — so a real wallet RPC answered 401 forever, however correct the login was. That is the `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the canned mocks replayed the challenge on any socket, so they stayed green. - `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry, no `Connection: close` on the challenge (epee closes the socket with the 401 when the request asks for it), `read_one_response` honouring `Content-Length` (a keep-alive response never ends in EOF; with no length the body ends at EOF, which is what keeps the 1 MiB cap meaningful for an open RPC). - A 401 after our *own* challenge now reads: the login does not match the child's `--rpc-login`. - Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce: `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one connection, and a nonce presented on another connection is refused. - `docs/WALLET.md`: what a 401 means and why it is not the flow. Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`, `--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401 Unauthorized`; fixed tree → `connected: true` with the wallet's real address.
2026-09-20 09:17:05 -04:00
/// Read exactly one HTTP response: its head, then `Content-Length` body bytes.
/// epee always emits `Content-Length`, and a keep-alive response never ends in
/// EOF — reading to EOF here would hang on a healthy server.
async fn read_one_response(stream: &mut TcpStream) -> Result<Vec<u8>> {
let mut buf = Vec::new();
wallet: answer the Digest challenge on the connection that issued it monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the `http_server_auth` lives inside `http_custom_handler`, which is created per connection, so its nonce starts empty and any request without a valid `Authorization` field mints a fresh one. The client opened a *second* connection for the authenticated retry, presenting a nonce that socket never issued — so a real wallet RPC answered 401 forever, however correct the login was. That is the `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the canned mocks replayed the challenge on any socket, so they stayed green. - `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry, no `Connection: close` on the challenge (epee closes the socket with the 401 when the request asks for it), `read_one_response` honouring `Content-Length` (a keep-alive response never ends in EOF; with no length the body ends at EOF, which is what keeps the 1 MiB cap meaningful for an open RPC). - A 401 after our *own* challenge now reads: the login does not match the child's `--rpc-login`. - Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce: `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one connection, and a nonce presented on another connection is refused. - `docs/WALLET.md`: what a 401 means and why it is not the flow. Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`, `--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401 Unauthorized`; fixed tree → `connected: true` with the wallet's real address.
2026-09-20 09:17:05 -04:00
let head_end = loop {
if let Some(i) = find_head_end(&buf) {
break i;
}
if !read_more(stream, &mut buf).await? {
// Closed before a full head: hand back what arrived, the status-line
// parse decides what that means.
return Ok(buf);
}
wallet: answer the Digest challenge on the connection that issued it monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the `http_server_auth` lives inside `http_custom_handler`, which is created per connection, so its nonce starts empty and any request without a valid `Authorization` field mints a fresh one. The client opened a *second* connection for the authenticated retry, presenting a nonce that socket never issued — so a real wallet RPC answered 401 forever, however correct the login was. That is the `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the canned mocks replayed the challenge on any socket, so they stayed green. - `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry, no `Connection: close` on the challenge (epee closes the socket with the 401 when the request asks for it), `read_one_response` honouring `Content-Length` (a keep-alive response never ends in EOF; with no length the body ends at EOF, which is what keeps the 1 MiB cap meaningful for an open RPC). - A 401 after our *own* challenge now reads: the login does not match the child's `--rpc-login`. - Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce: `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one connection, and a nonce presented on another connection is refused. - `docs/WALLET.md`: what a 401 means and why it is not the flow. Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`, `--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401 Unauthorized`; fixed tree → `connected: true` with the wallet's real address.
2026-09-20 09:17:05 -04:00
};
let head = std::str::from_utf8(&buf[..head_end]).unwrap_or_default();
// epee always sends `Content-Length`, but an open (challenge-less) RPC may
// not: with no length the body ends at EOF, so keep reading — the cap below
// is what stops a server that streams forever.
let Some(want) = content_length(head) else {
while read_more(stream, &mut buf).await? {}
return Ok(buf);
};
while buf.len() < head_end + 4 + want {
if !read_more(stream, &mut buf).await? {
break;
}
}
Ok(buf)
}
wallet: answer the Digest challenge on the connection that issued it monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the `http_server_auth` lives inside `http_custom_handler`, which is created per connection, so its nonce starts empty and any request without a valid `Authorization` field mints a fresh one. The client opened a *second* connection for the authenticated retry, presenting a nonce that socket never issued — so a real wallet RPC answered 401 forever, however correct the login was. That is the `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the canned mocks replayed the challenge on any socket, so they stayed green. - `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry, no `Connection: close` on the challenge (epee closes the socket with the 401 when the request asks for it), `read_one_response` honouring `Content-Length` (a keep-alive response never ends in EOF; with no length the body ends at EOF, which is what keeps the 1 MiB cap meaningful for an open RPC). - A 401 after our *own* challenge now reads: the login does not match the child's `--rpc-login`. - Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce: `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one connection, and a nonce presented on another connection is refused. - `docs/WALLET.md`: what a 401 means and why it is not the flow. Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`, `--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401 Unauthorized`; fixed tree → `connected: true` with the wallet's real address.
2026-09-20 09:17:05 -04:00
async fn read_to_eof(stream: &mut TcpStream) -> Result<Vec<u8>> {
let mut buf = Vec::new();
while read_more(stream, &mut buf).await? {}
Ok(buf)
}
/// One read into `buf`. `false` means the peer closed. Enforces the shared cap.
async fn read_more(stream: &mut TcpStream, buf: &mut Vec<u8>) -> Result<bool> {
let mut tmp = [0u8; 8192];
let n = stream
.read(&mut tmp)
.await
.map_err(|e| Error(format!("wallet read: {e}")))?;
if n == 0 {
return Ok(false);
}
if buf.len().saturating_add(n) > MAX_RPC_BYTES {
return Err(Error("wallet RPC response too large".into()));
}
buf.extend_from_slice(&tmp[..n]);
Ok(true)
}
fn find_head_end(buf: &[u8]) -> Option<usize> {
buf.windows(4).position(|w| w == b"\r\n\r\n")
}
fn content_length(head: &str) -> Option<usize> {
head.lines().skip(1).find_map(|line| {
let (k, v) = line.split_once(':')?;
k.eq_ignore_ascii_case("content-length")
.then(|| v.trim().parse().ok())
.flatten()
})
}
fn http_status(raw: &[u8]) -> Option<u16> {
let text = std::str::from_utf8(raw).ok()?;
let line = text.lines().next()?;
let mut parts = line.split_whitespace();
let _http = parts.next()?;
parts.next()?.parse().ok()
}
fn www_authenticate(raw: &[u8]) -> Option<String> {
let text = std::str::from_utf8(raw).ok()?;
let (head, _) = text
.split_once("\r\n\r\n")
.or_else(|| text.split_once("\n\n"))?;
for line in head.lines().skip(1) {
let (k, v) = match line.split_once(':') {
Some(kv) => kv,
None => continue,
};
if k.eq_ignore_ascii_case("www-authenticate") {
return Some(v.trim().to_string());
}
}
None
}
fn digest_param(challenge: &str, key: &str) -> Option<String> {
let t = challenge.trim();
let rest = if t.len() >= 6 && t[..6].eq_ignore_ascii_case("digest") {
t[6..].trim()
} else {
return None;
};
for part in rest.split(',') {
let part = part.trim();
let (k, v) = match part.split_once('=') {
Some(kv) => kv,
None => continue,
};
if k.eq_ignore_ascii_case(key) {
return Some(v.trim().trim_matches('"').to_string());
}
}
None
}
fn md5_hex(s: &str) -> String {
use md5::{Digest, Md5};
hex_lower(&Md5::digest(s.as_bytes()))
}
fn hex_lower(bytes: &[u8]) -> String {
const H: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for &b in bytes {
out.push(H[(b >> 4) as usize] as char);
out.push(H[(b & 0xf) as usize] as char);
}
out
}
fn digest_authorization(ep: &Endpoint, challenge: &str) -> Result<String> {
if let Some(alg) = digest_param(challenge, "algorithm")
&& !alg.eq_ignore_ascii_case("MD5")
{
return Err(Error("wallet RPC digest algorithm not MD5".into()));
}
let realm = digest_param(challenge, "realm").unwrap_or_default();
let nonce = digest_param(challenge, "nonce")
.ok_or_else(|| Error("wallet RPC digest required (--rpc-login / HTTP Digest)".into()))?;
let qop = digest_param(challenge, "qop");
// `user:realm:password` never leaves a bare `String` behind.
let pw_input = Zeroizing::new(format!("{}:{realm}:{}", ep.user, ep.pass.as_str()));
let ha1 = md5_hex(pw_input.as_str());
let ha2 = md5_hex(&format!("POST:{}", ep.path));
let (qop_part, resp) = if qop
.as_deref()
.is_some_and(|q| q.split(',').any(|x| x.trim() == "auth"))
{
let mut cnonce_bytes = [0u8; 8];
rand::thread_rng().fill_bytes(&mut cnonce_bytes);
let cnonce = hex_lower(&cnonce_bytes);
let nc = "00000001";
let response = md5_hex(&format!("{ha1}:{nonce}:{nc}:{cnonce}:auth:{ha2}"));
(
format!(", qop=auth, nc={nc}, cnonce=\"{cnonce}\""),
response,
)
} else {
(String::new(), md5_hex(&format!("{ha1}:{nonce}:{ha2}")))
};
Ok(format!(
"Digest username=\"{}\", realm=\"{realm}\", nonce=\"{nonce}\", uri=\"{}\", algorithm=MD5, response=\"{resp}\"{qop_part}",
ep.user, ep.path
))
}
fn parse_json_rpc(raw: &[u8]) -> Result<serde_json::Value> {
let text = std::str::from_utf8(raw).map_err(|_| Error("wallet RPC not UTF-8".into()))?;
let (head, body) = text
.split_once("\r\n\r\n")
.or_else(|| text.split_once("\n\n"))
.ok_or_else(|| Error("wallet RPC truncated".into()))?;
let status = head.lines().next().unwrap_or("");
if status.contains(" 3") {
return Err(Error("wallet RPC redirect refused".into()));
}
if !status.contains(" 200 ") && !status.ends_with(" 200") {
return Err(Error(format!("wallet RPC HTTP {status}")));
}
let json: serde_json::Value =
serde_json::from_str(body.trim()).map_err(|e| Error(format!("wallet RPC json: {e}")))?;
if let Some(err) = json.get("error") {
let msg = err
.get("message")
.and_then(|m| m.as_str())
.unwrap_or("rpc error");
// The one RPC-level error we translate: a view-only wallet has no
// spend key (monero `WALLET_RPC_ERROR_CODE_WATCH_ONLY`).
if err.get("code").and_then(|c| c.as_i64()) == Some(WATCH_ONLY_CODE) {
return Err(Error(VIEW_ONLY_MSG.into()));
}
return Err(Error(msg.into()));
}
json.get("result")
.cloned()
.ok_or_else(|| Error("wallet RPC missing result".into()))
}
fn json_str(v: &serde_json::Value, key: &str) -> Result<String> {
v.get(key)
.and_then(|x| x.as_str())
.map(str::to_string)
.ok_or_else(|| Error(format!("wallet RPC missing {key}")))
}
fn json_amount(v: &serde_json::Value) -> String {
match v.get("amount") {
Some(serde_json::Value::Number(n)) => n
.as_u64()
.map(|x| x.to_string())
.or_else(|| n.as_i64().map(|x| x.to_string()))
.unwrap_or_default(),
Some(serde_json::Value::String(s)) => s.clone(),
_ => String::new(),
}
}
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\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
}
fn uri_request(addr: &str, method: &str, path: &str) -> String {
format!(
"{method} {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
)
}
/// One request, one answer: status code plus body. `Connection: close` and read
/// to EOF, so `Content-Length` never has to be trusted.
async fn daemon_http(
addr: &str,
request: &str,
budget: Duration,
) -> std::result::Result<(u16, Vec<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 = [0u8; 8192];
loop {
let n = stream.read(&mut tmp).await?;
if n == 0 {
break;
}
buf.extend_from_slice(&tmp[..n]);
if buf.len() >= DAEMON_MAX_BYTES {
break;
}
}
Ok::<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,
}
}