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.
This commit is contained in:
parent
bcf7ec31c1
commit
db208be05c
5 changed files with 961 additions and 100 deletions
180
src/node.rs
180
src/node.rs
|
|
@ -29,7 +29,7 @@ use crate::ratelimit::TokenBucket;
|
|||
use crate::sanitize;
|
||||
use crate::session::{self, Keys};
|
||||
use crate::store::{Friend, FriendProfile, Message, PaymentWrite, Store};
|
||||
use crate::wallet::{self, Wallet};
|
||||
use crate::wallet::{self, Readiness, Wallet, WalletConfig, WalletStatus};
|
||||
|
||||
pub struct RotateResult {
|
||||
pub notified: usize,
|
||||
|
|
@ -82,7 +82,12 @@ pub struct Node {
|
|||
hs: Mutex<Option<HsHandle>>,
|
||||
onion: Mutex<String>,
|
||||
keys: Mutex<Keys>,
|
||||
wallet: Wallet,
|
||||
/// Behind a lock because the F7 screen can re-point it at a saved config
|
||||
/// without a restart. Clone it out (`wallet_snapshot`) before awaiting: a
|
||||
/// `std::sync::Mutex` guard must not live across an `.await`.
|
||||
wallet: Mutex<Wallet>,
|
||||
/// Last probe result, for the draw path. Cheap to read, never dials.
|
||||
wallet_status: Mutex<WalletStatus>,
|
||||
incoming_limit: Mutex<TokenBucket>,
|
||||
inbox: Mutex<file::Inbox>,
|
||||
outbox: Arc<Outbox>,
|
||||
|
|
@ -116,6 +121,10 @@ impl Node {
|
|||
passphrase: &str,
|
||||
) -> Result<Arc<Self>, String> {
|
||||
let store = Store::open_at_with_passphrase(&home, passphrase).map_err(|e| e.to_string())?;
|
||||
// Stored config first (the F7 screen's), env as the migration path.
|
||||
let stored_wallet = store.load_wallet_config().map_err(|e| e.to_string())?;
|
||||
let wallet = Wallet::for_boot(stored_wallet.as_ref());
|
||||
let wallet_status = WalletStatus::idle(wallet.configured());
|
||||
let me = store.self_identity().map_err(|e| e.to_string())?;
|
||||
let keys = Keys::from_self(&me).map_err(|e| e.to_string())?;
|
||||
let nickname = store.hs_nickname().map_err(|e| e.to_string())?;
|
||||
|
|
@ -144,7 +153,8 @@ impl Node {
|
|||
hs: Mutex::new(None),
|
||||
onion: Mutex::new(onion.clone()),
|
||||
keys: Mutex::new(keys),
|
||||
wallet: Wallet::from_env(),
|
||||
wallet: Mutex::new(wallet),
|
||||
wallet_status: Mutex::new(wallet_status),
|
||||
incoming_limit: Mutex::new(TokenBucket::default()),
|
||||
inbox: Mutex::new(inbox),
|
||||
outbox: Arc::clone(&outbox),
|
||||
|
|
@ -256,7 +266,8 @@ impl Node {
|
|||
/// `sending`; `Outbox::reset_stale` requeues those on the next unlock, the
|
||||
/// same recovery the parent uses for a process that died mid-attempt.
|
||||
async fn drain(&self, budget: Duration) -> Result<FlushOutcome, String> {
|
||||
let attempted = match tokio::time::timeout(budget, self.outbox.flush_all(unix_now())).await {
|
||||
let attempted = match tokio::time::timeout(budget, self.outbox.flush_all(unix_now())).await
|
||||
{
|
||||
Ok(Ok(rows)) => Some(rows),
|
||||
Ok(Err(e)) => return Err(e),
|
||||
Err(_) => {
|
||||
|
|
@ -463,19 +474,113 @@ impl Node {
|
|||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The live wallet, cloned out of its lock. Every wallet call goes through
|
||||
/// this so a `std::sync::Mutex` guard never lives across an `.await`, and so
|
||||
/// the F7 screen can re-point the wallet mid-session.
|
||||
fn wallet_snapshot(&self) -> Wallet {
|
||||
self.wallet
|
||||
.lock()
|
||||
.map(|w| w.clone())
|
||||
.unwrap_or_else(|_| Wallet::disabled())
|
||||
}
|
||||
|
||||
/// The snapshot the TUI draws. Cheap: no dial, no lock on the RPC. It says
|
||||
/// "configured, not probed" (`connected == false`) until a probe has run.
|
||||
pub fn wallet_status(&self) -> WalletStatus {
|
||||
self.wallet_status
|
||||
.lock()
|
||||
.map(|s| s.clone())
|
||||
.unwrap_or_else(|_| WalletStatus::idle(self.wallet_snapshot().configured()))
|
||||
}
|
||||
|
||||
/// Probe the configured endpoint once and fold the result into the snapshot.
|
||||
/// This is the only thing that can flip `connected` to true.
|
||||
pub async fn wallet_refresh(&self) -> WalletStatus {
|
||||
let w = self.wallet_snapshot();
|
||||
let status = w.status().await;
|
||||
if let Ok(mut slot) = self.wallet_status.lock() {
|
||||
*slot = status.clone();
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
/// The pay/tip readiness guard. Blocking-friendly: the TUI calls this from
|
||||
/// its key handler with `rt.block_on`, like `send_pay`/`send_tip` do.
|
||||
///
|
||||
/// It never dials Tor. It also never dials the wallet when the answer is
|
||||
/// already known locally — an unconfigured wallet and a `/tip` on a
|
||||
/// view-only wallet are refused before any socket is opened.
|
||||
pub async fn wallet_readiness(&self, is_tip: bool) -> Readiness {
|
||||
let w = self.wallet_snapshot();
|
||||
if !w.configured() {
|
||||
return Readiness::NotConfigured;
|
||||
}
|
||||
if is_tip && w.no_spend() {
|
||||
return Readiness::NoSpend;
|
||||
}
|
||||
let status = self.wallet_refresh().await;
|
||||
wallet::readiness(status.configured, status.connected, w.no_spend(), is_tip)
|
||||
}
|
||||
|
||||
/// The config screen's Test-connection button: one shot against the endpoint
|
||||
/// the user is typing. It does not touch the live wallet or the snapshot —
|
||||
/// a test of an untyped endpoint is not the wallet we are running.
|
||||
pub async fn wallet_test_connection(
|
||||
&self,
|
||||
rpc_url: &str,
|
||||
rpc_login: &str,
|
||||
) -> wallet::PingResult {
|
||||
Wallet::ping(rpc_url, rpc_login).await
|
||||
}
|
||||
|
||||
/// The config the F7 screen should show: the stored one, or the env-derived
|
||||
/// one when only env set the wallet (the migration path).
|
||||
pub fn wallet_config(&self) -> Option<WalletConfig> {
|
||||
if let Ok(store) = self.store.lock()
|
||||
&& let Ok(Some(cfg)) = store.load_wallet_config()
|
||||
{
|
||||
return Some(cfg);
|
||||
}
|
||||
self.wallet_snapshot().config()
|
||||
}
|
||||
|
||||
/// Persist the config screen's Save and re-read it: the live wallet and the
|
||||
/// snapshot both follow, so "saved · not connected" is visible without a
|
||||
/// restart. Validation happens before anything is written, so a rejected
|
||||
/// config leaves the running wallet exactly as it was.
|
||||
pub fn wallet_save_config(&self, cfg: &WalletConfig) -> Result<(), String> {
|
||||
Wallet::from_config(cfg).map_err(|e| wallet::redact(&e.to_string(), cfg.secret()))?;
|
||||
{
|
||||
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||||
store.save_wallet_config(cfg).map_err(|e| e.to_string())?;
|
||||
}
|
||||
// Re-read from the store rather than trusting the caller's copy.
|
||||
let stored = self
|
||||
.store
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
.load_wallet_config()
|
||||
.map_err(|e| e.to_string())?;
|
||||
let wallet = Wallet::for_boot(stored.as_ref());
|
||||
let configured = wallet.configured();
|
||||
*self.wallet.lock().map_err(|e| e.to_string())? = wallet;
|
||||
*self.wallet_status.lock().map_err(|e| e.to_string())? = WalletStatus::idle(configured);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Current wallet balance as a human-readable XMR string, or `off` when the
|
||||
/// wallet is not configured.
|
||||
pub async fn wallet_balance(&self) -> String {
|
||||
if !self.wallet.configured() {
|
||||
let w = self.wallet_snapshot();
|
||||
if !w.configured() {
|
||||
return "off".into();
|
||||
}
|
||||
match self.wallet.get_balance().await {
|
||||
match w.get_balance().await {
|
||||
Ok(b) => crate::pay::atomic_to_xmr_str(&b),
|
||||
Err(_) => "err".into(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub fn wipe_messages(&self) -> Result<(), String> {
|
||||
self.store
|
||||
.lock()
|
||||
|
|
@ -625,8 +730,9 @@ impl Node {
|
|||
|
||||
/// Pay selected friend via wallet RPC, then signed receipt.
|
||||
pub async fn tip(&self, friend_pk: &[u8], atomic: &str, memo: &str) -> Result<(), String> {
|
||||
if !self.wallet.configured() {
|
||||
return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into());
|
||||
let w = self.wallet_snapshot();
|
||||
if !w.configured() {
|
||||
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
||||
}
|
||||
let address = self
|
||||
.friend_profile(friend_pk)?
|
||||
|
|
@ -639,8 +745,7 @@ impl Node {
|
|||
let amount: u64 = atomic
|
||||
.parse()
|
||||
.map_err(|_| "amount too large for wallet RPC".to_string())?;
|
||||
let txid = self
|
||||
.wallet
|
||||
let txid = w
|
||||
.transfer(&address, amount)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
|
@ -689,8 +794,9 @@ impl Node {
|
|||
}
|
||||
|
||||
async fn invoice_address(&self) -> Result<String, String> {
|
||||
if self.wallet.configured()
|
||||
&& let Ok(addr) = self.wallet.create_address().await
|
||||
let w = self.wallet_snapshot();
|
||||
if w.configured()
|
||||
&& let Ok(addr) = w.create_address().await
|
||||
&& pay::check_address(&addr).is_ok()
|
||||
{
|
||||
return Ok(addr);
|
||||
|
|
@ -709,10 +815,9 @@ impl Node {
|
|||
/// how to wrap it.
|
||||
pub async fn wallet_receive_address(&self) -> Result<String, String> {
|
||||
let profile_addr = self.self_profile()?.xmr_addr;
|
||||
if self
|
||||
.wallet
|
||||
.configured()
|
||||
&& let Ok(addr) = self.wallet.get_address().await
|
||||
let w = self.wallet_snapshot();
|
||||
if w.configured()
|
||||
&& let Ok(addr) = w.get_address().await
|
||||
&& pay::check_address(&addr).is_ok()
|
||||
{
|
||||
return Ok(addr);
|
||||
|
|
@ -728,8 +833,9 @@ impl Node {
|
|||
/// configured. Calls `pay::atomic_to_xmr_str` so the UI never parses
|
||||
/// piconero itself.
|
||||
pub async fn wallet_balance_line(&self) -> String {
|
||||
if self.wallet.configured() {
|
||||
match self.wallet.get_balance().await {
|
||||
let w = self.wallet_snapshot();
|
||||
if w.configured() {
|
||||
match w.get_balance().await {
|
||||
Ok(b) if !b.is_empty() => {
|
||||
let xmr = pay::atomic_to_xmr_str(&b);
|
||||
if xmr == "0" {
|
||||
|
|
@ -749,11 +855,15 @@ impl Node {
|
|||
/// Recent in/out transfers for the wallet screen, newest first, capped to a
|
||||
/// small window. Returns the same `TransferRow` shape the existing tests
|
||||
/// already cover.
|
||||
pub async fn wallet_recent_transfers(&self, cap: usize) -> Result<Vec<wallet::TransferRow>, String> {
|
||||
if !self.wallet.configured() {
|
||||
pub async fn wallet_recent_transfers(
|
||||
&self,
|
||||
cap: usize,
|
||||
) -> Result<Vec<wallet::TransferRow>, String> {
|
||||
let w = self.wallet_snapshot();
|
||||
if !w.configured() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let rows = self.wallet.get_transfers().await.map_err(|e| e.to_string())?;
|
||||
let rows = w.get_transfers().await.map_err(|e| e.to_string())?;
|
||||
let mut rows = rows;
|
||||
rows.sort_by(|a, b| b.txid.cmp(&a.txid));
|
||||
Ok(rows.into_iter().take(cap).collect())
|
||||
|
|
@ -762,11 +872,11 @@ impl Node {
|
|||
/// Create a new spend-capable wallet. Returns the seed once for backup.
|
||||
/// The user never pastes a key on this path.
|
||||
pub async fn wallet_create(&self, password: &str) -> Result<String, String> {
|
||||
if !self.wallet.configured() {
|
||||
return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into());
|
||||
let w = self.wallet_snapshot();
|
||||
if !w.configured() {
|
||||
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
||||
}
|
||||
self.wallet
|
||||
.create_wallet(wallet::DEFAULT_WALLET_FILENAME, password)
|
||||
w.create_wallet(wallet::DEFAULT_WALLET_FILENAME, password)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
|
@ -774,11 +884,11 @@ impl Node {
|
|||
/// Import a wallet from an existing 25-word seed. This is the only path
|
||||
/// that takes a user-supplied secret.
|
||||
pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<(), String> {
|
||||
if !self.wallet.configured() {
|
||||
return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into());
|
||||
let w = self.wallet_snapshot();
|
||||
if !w.configured() {
|
||||
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
||||
}
|
||||
self.wallet
|
||||
.restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed)
|
||||
w.restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
|
@ -949,7 +1059,10 @@ impl Node {
|
|||
|
||||
/// Pending and failed outbox rows for a friend, for UI surfacing.
|
||||
/// Delivered rows are dropped, so a message absent here was sent.
|
||||
pub fn outbox_pending(&self, friend_pk: &[u8]) -> Result<Vec<crate::store::OutboxEntry>, String> {
|
||||
pub fn outbox_pending(
|
||||
&self,
|
||||
friend_pk: &[u8],
|
||||
) -> Result<Vec<crate::store::OutboxEntry>, String> {
|
||||
self.outbox.pending(friend_pk)
|
||||
}
|
||||
|
||||
|
|
@ -1182,9 +1295,10 @@ impl Node {
|
|||
// Honest prerequisite: an unsynced wallet cannot see the tx, so a
|
||||
// get_transfers "miss" would be a lie. Until the chain is ready the
|
||||
// receipt stays verified=0 — that is the correct state, not an error.
|
||||
let ready = self.wallet.configured() && self.wallet.can_verify_receipts().await;
|
||||
let w = self.wallet_snapshot();
|
||||
let ready = w.configured() && w.can_verify_receipts().await;
|
||||
if ready {
|
||||
match self.wallet.get_transfers().await {
|
||||
match w.get_transfers().await {
|
||||
Ok(rows)
|
||||
if wallet::transfers_match(
|
||||
&rows,
|
||||
|
|
|
|||
114
src/store.rs
114
src/store.rs
|
|
@ -265,6 +265,16 @@ impl Store {
|
|||
sealed BLOB NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
-- Remote-mode wallet config the user set in-app (F7): the endpoint,
|
||||
-- the login, and the view-only flag. One row; the login is sealed
|
||||
-- with the store data key (see `save_wallet_config`).
|
||||
CREATE TABLE IF NOT EXISTS wallet_config (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
rpc_url TEXT NOT NULL,
|
||||
sealed_login BLOB NOT NULL,
|
||||
no_spend INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS payments (
|
||||
id INTEGER PRIMARY KEY,
|
||||
friend_id INTEGER NOT NULL REFERENCES friends(id),
|
||||
|
|
@ -355,6 +365,59 @@ impl Store {
|
|||
.map_err(|_| Error("wallet-child config is not utf-8".into()))
|
||||
}
|
||||
|
||||
/// Persist the remote-mode wallet config the F7 screen saved. One row,
|
||||
/// replaced in place; an empty `rpc_url` clears it (that is how a user
|
||||
/// turns the stored wallet off again).
|
||||
///
|
||||
/// The login is `user:pass` for a wallet that can spend, so it is sealed
|
||||
/// with the store data key on top of the whole-db SQLCipher layer — the
|
||||
/// same discipline as the wallet-child creds.
|
||||
pub fn save_wallet_config(&self, cfg: &crate::wallet::WalletConfig) -> Result<()> {
|
||||
if cfg.rpc_url.trim().is_empty() {
|
||||
self.conn.execute("DELETE FROM wallet_config", [])?;
|
||||
return Ok(());
|
||||
}
|
||||
let sealed =
|
||||
crate::backup::aead_encrypt(&self.msg_key, cfg.rpc_login.as_bytes(), WALLET_CONFIG_AAD)
|
||||
.map_err(Error)?;
|
||||
self.conn.execute(
|
||||
"INSERT INTO wallet_config (id, rpc_url, sealed_login, no_spend, updated_at)
|
||||
VALUES (1, ?1, ?2, ?3, ?4)
|
||||
ON CONFLICT(id) DO UPDATE SET rpc_url = excluded.rpc_url,
|
||||
sealed_login = excluded.sealed_login, no_spend = excluded.no_spend,
|
||||
updated_at = excluded.updated_at",
|
||||
params![cfg.rpc_url.trim(), sealed, cfg.no_spend as i64, unix_now()],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read the stored remote-mode config, or `None` when none was ever saved.
|
||||
/// A blob that does not decrypt is an error, never a guess.
|
||||
pub fn load_wallet_config(&self) -> Result<Option<crate::wallet::WalletConfig>> {
|
||||
let row: Option<(String, Vec<u8>, i64)> = self
|
||||
.conn
|
||||
.query_row(
|
||||
"SELECT rpc_url, sealed_login, no_spend FROM wallet_config WHERE id = 1",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let Some((rpc_url, sealed, no_spend)) = row else {
|
||||
return Ok(None);
|
||||
};
|
||||
let login = crate::backup::aead_decrypt(&self.msg_key, &sealed, WALLET_CONFIG_AAD)
|
||||
.map_err(|_| Error("wallet config decrypt failed".into()))?;
|
||||
// The login is a secret: it must not survive in a bare `String`.
|
||||
let login = Zeroizing::new(
|
||||
String::from_utf8(login).map_err(|_| Error("wallet config is not utf-8".into()))?,
|
||||
);
|
||||
Ok(Some(crate::wallet::WalletConfig {
|
||||
rpc_url,
|
||||
rpc_login: login,
|
||||
no_spend: no_spend != 0,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn replace_identity_keys(
|
||||
&self,
|
||||
identity_sk: &[u8],
|
||||
|
|
@ -912,17 +975,13 @@ impl Store {
|
|||
}
|
||||
|
||||
pub fn append_message(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<()> {
|
||||
self.append_message_id(friend_pk, dir, plaintext).map(|_| ())
|
||||
self.append_message_id(friend_pk, dir, plaintext)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
/// Same as `append_message`, returning the row id so an outbox row can
|
||||
/// point at the body instead of storing a second copy.
|
||||
pub fn append_message_id(
|
||||
&self,
|
||||
friend_pk: &[u8],
|
||||
dir: &str,
|
||||
plaintext: &[u8],
|
||||
) -> Result<i64> {
|
||||
pub fn append_message_id(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<i64> {
|
||||
if dir != "in" && dir != "out" {
|
||||
return Err(Error("dir must be in or out".into()));
|
||||
}
|
||||
|
|
@ -971,11 +1030,7 @@ impl Store {
|
|||
let aad = message_aad(friend_id, &dir, id);
|
||||
let plaintext = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad)
|
||||
.map_err(|_| Error("message decrypt failed".into()))?;
|
||||
out.push(Message {
|
||||
id,
|
||||
dir,
|
||||
plaintext,
|
||||
});
|
||||
out.push(Message { id, dir, plaintext });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
|
@ -1338,7 +1393,10 @@ fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Friend> {
|
|||
fn gen_prekey() -> (Zeroizing<Vec<u8>>, Vec<u8>) {
|
||||
let sk = StaticSecret::random_from_rng(OsRng);
|
||||
let pk = X25519Public::from(&sk);
|
||||
(Zeroizing::new(sk.to_bytes().to_vec()), pk.to_bytes().to_vec())
|
||||
(
|
||||
Zeroizing::new(sk.to_bytes().to_vec()),
|
||||
pk.to_bytes().to_vec(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Per-install KDF salt for the whole-database key. Not secret (a salt never
|
||||
|
|
@ -1597,6 +1655,10 @@ fn unix_now() -> i64 {
|
|||
/// outbox blobs that share the same store data key.
|
||||
const WALLET_CHILD_AAD: &[u8] = b"onionwire/wallet-child/v1";
|
||||
|
||||
/// AAD for the sealed remote-mode wallet config row. Same reasoning as the
|
||||
/// wallet-child AAD: one store key, many domains.
|
||||
const WALLET_CONFIG_AAD: &[u8] = b"onionwire/wallet-config/v1";
|
||||
|
||||
fn fingerprint(pubkey: &[u8]) -> String {
|
||||
pubkey.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
|
@ -1892,22 +1954,16 @@ mod at_rest {
|
|||
params![salt.as_slice(), wrapped],
|
||||
)
|
||||
.unwrap();
|
||||
for (dir, body) in [
|
||||
("in", "legacy-body-xyz"),
|
||||
("out", "legacy-reply-xyz"),
|
||||
] {
|
||||
for (dir, body) in [("in", "legacy-body-xyz"), ("out", "legacy-reply-xyz")] {
|
||||
conn.execute(
|
||||
"INSERT INTO messages (friend_id, dir, plaintext, created_at) VALUES (1, ?1, x'', 7)",
|
||||
params![dir],
|
||||
)
|
||||
.unwrap();
|
||||
let id = conn.last_insert_rowid();
|
||||
let blob = crate::backup::aead_encrypt(
|
||||
&data_key,
|
||||
body.as_bytes(),
|
||||
&message_aad(1, dir, id),
|
||||
)
|
||||
.unwrap();
|
||||
let blob =
|
||||
crate::backup::aead_encrypt(&data_key, body.as_bytes(), &message_aad(1, dir, id))
|
||||
.unwrap();
|
||||
conn.execute(
|
||||
"UPDATE messages SET plaintext = ?1 WHERE id = ?2",
|
||||
params![blob, id],
|
||||
|
|
@ -1935,7 +1991,8 @@ mod at_rest {
|
|||
"fixture must be a plaintext sqlite file"
|
||||
);
|
||||
|
||||
let store = Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("open+upgrade");
|
||||
let store =
|
||||
Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("open+upgrade");
|
||||
assert_eq!(
|
||||
store.self_identity().unwrap().identity_sk[..],
|
||||
LEGACY_IDENTITY_SK[..]
|
||||
|
|
@ -1957,7 +2014,10 @@ mod at_rest {
|
|||
);
|
||||
for (needle, what) in [
|
||||
(b"legacy-body-xyz".to_vec(), "message body"),
|
||||
(fingerprint(&LEGACY_FRIEND_PK).into_bytes(), "friend pubkey hex"),
|
||||
(
|
||||
fingerprint(&LEGACY_FRIEND_PK).into_bytes(),
|
||||
"friend pubkey hex",
|
||||
),
|
||||
(LEGACY_IDENTITY_SK.to_vec(), "identity secret"),
|
||||
(b"legacy-friend.onion".to_vec(), "locator"),
|
||||
] {
|
||||
|
|
@ -2216,9 +2276,7 @@ mod at_rest {
|
|||
"row stored the creds as plaintext"
|
||||
);
|
||||
assert!(
|
||||
!sealed
|
||||
.windows(11)
|
||||
.any(|w| w == b"ow-secret-p".as_slice()),
|
||||
!sealed.windows(11).any(|w| w == b"ow-secret-p".as_slice()),
|
||||
"sealed row leaked the password"
|
||||
);
|
||||
|
||||
|
|
|
|||
336
src/wallet.rs
336
src/wallet.rs
|
|
@ -46,6 +46,204 @@ pub enum ChainSource {
|
|||
},
|
||||
}
|
||||
|
||||
/// Remote-mode wallet config: the `monero-wallet-rpc` the user already runs
|
||||
/// themselves (F7 sets it, the store keeps it, env is the migration path).
|
||||
///
|
||||
/// `rpc_url` never carries `user:pass` — that is `rpc_login`, which stays in a
|
||||
/// wiping buffer and is sealed at rest. This is the same three fields
|
||||
/// `ONIONWIRE_WALLET_RPC` / `ONIONWIRE_WALLET_RPC_LOGIN` /
|
||||
/// `ONIONWIRE_WALLET_NO_SPEND` describe.
|
||||
#[derive(Clone)]
|
||||
pub struct WalletConfig {
|
||||
/// `http://host:port[/path]`. Loopback-only enforcement stays in
|
||||
/// [`parse_http_url`].
|
||||
pub rpc_url: String,
|
||||
/// `user:pass`. Never logged, never in a status line, never on disk in the
|
||||
/// clear.
|
||||
pub rpc_login: Zeroizing<String>,
|
||||
/// View-only deployment: `/tip` is refused locally, before any dial.
|
||||
pub no_spend: bool,
|
||||
}
|
||||
|
||||
impl WalletConfig {
|
||||
pub fn new(rpc_url: &str, rpc_login: &str, no_spend: bool) -> Self {
|
||||
Self {
|
||||
rpc_url: rpc_url.trim().to_string(),
|
||||
rpc_login: Zeroizing::new(rpc_login.trim().to_string()),
|
||||
no_spend,
|
||||
}
|
||||
}
|
||||
|
||||
/// The password half of `user:pass` (the whole string when there is no
|
||||
/// colon), for redaction. Never rendered anywhere.
|
||||
pub fn secret(&self) -> &str {
|
||||
match self.rpc_login.split_once(':') {
|
||||
Some((_, pass)) => pass,
|
||||
None => self.rpc_login.as_str(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Redacted on purpose: a `Debug` that prints the login turns any `{:?}` —
|
||||
/// a log line, a panic message, an assert — into a credential leak.
|
||||
impl std::fmt::Debug for WalletConfig {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("WalletConfig")
|
||||
.field("rpc_url", &self.rpc_url)
|
||||
.field("rpc_login", &"<redacted>")
|
||||
.field("no_spend", &self.no_spend)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for WalletConfig {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.rpc_url == other.rpc_url
|
||||
&& self.rpc_login.as_str() == other.rpc_login.as_str()
|
||||
&& self.no_spend == other.no_spend
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for WalletConfig {}
|
||||
|
||||
impl Default for WalletConfig {
|
||||
fn default() -> Self {
|
||||
Self::new("", "", false)
|
||||
}
|
||||
}
|
||||
|
||||
/// The snapshot the TUI draws (main-screen indicator + config-screen status
|
||||
/// line). No dialing, no secrets: `last_error` is already sanitized and short.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct WalletStatus {
|
||||
/// A stored or env config resolved to a usable `Wallet`.
|
||||
pub configured: bool,
|
||||
/// The last probe succeeded. **Never** set from config-existence: config is
|
||||
/// not reachability.
|
||||
pub connected: bool,
|
||||
/// The most recent failure, sanitized for display. Cleared on success.
|
||||
pub last_error: Option<String>,
|
||||
/// Human-readable balance, e.g. `123456 piconero`, or `—`.
|
||||
pub balance_line: String,
|
||||
/// The address `/pay` invoices would hand out, or `—`.
|
||||
pub receive_address: String,
|
||||
}
|
||||
|
||||
/// The `—` the TUI shows for a readout that has no honest value yet.
|
||||
pub const NOT_SET: &str = "—";
|
||||
|
||||
impl WalletStatus {
|
||||
/// Configured, never probed: the state right after boot or a save.
|
||||
pub fn idle(configured: bool) -> Self {
|
||||
Self {
|
||||
configured,
|
||||
connected: false,
|
||||
last_error: None,
|
||||
balance_line: NOT_SET.to_string(),
|
||||
receive_address: NOT_SET.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn configured(&self) -> bool {
|
||||
self.configured
|
||||
}
|
||||
|
||||
pub fn connected(&self) -> bool {
|
||||
self.connected
|
||||
}
|
||||
}
|
||||
|
||||
/// The config screen's Test-connection result. `status` is the success copy;
|
||||
/// `error` is a short sanitized reason, and it never carries the login.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PingResult {
|
||||
pub ok: bool,
|
||||
/// Short human status, e.g. `connected`, or `not connected` on failure.
|
||||
pub status: String,
|
||||
/// Short sanitized reason on failure, or `None`.
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
impl PingResult {
|
||||
/// The TUI's status line: one string, never a secret.
|
||||
pub fn line(&self) -> String {
|
||||
match &self.error {
|
||||
Some(e) => format!("{} · {e}", self.status),
|
||||
None => self.status.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Refusal copy for the pay/tip guard. Deterministic: the TUI asserts these
|
||||
/// exact strings.
|
||||
pub const NOT_CONFIGURED_MSG: &str =
|
||||
"wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC";
|
||||
pub const NOT_CONNECTED_MSG: &str = "wallet not connected — check endpoint, login, daemon";
|
||||
|
||||
/// The pay/tip pre-check answer, in the order the guard evaluates it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Readiness {
|
||||
/// Configured, reachable, and (for `/tip`) spend-capable.
|
||||
Ready,
|
||||
/// No stored and no env config.
|
||||
NotConfigured,
|
||||
/// Configured but the probe failed (or there was none).
|
||||
NotConnected,
|
||||
/// `/tip` on a view-only/no-spend wallet. Never a dial.
|
||||
NoSpend,
|
||||
}
|
||||
|
||||
impl Readiness {
|
||||
/// The refusal copy when the guard rejects, `None` when ready.
|
||||
pub fn refusal(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Readiness::Ready => None,
|
||||
Readiness::NotConfigured => Some(NOT_CONFIGURED_MSG),
|
||||
Readiness::NotConnected => Some(NOT_CONNECTED_MSG),
|
||||
Readiness::NoSpend => Some(VIEW_ONLY_MSG),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_ready(self) -> bool {
|
||||
matches!(self, Readiness::Ready)
|
||||
}
|
||||
}
|
||||
|
||||
/// The guard's state table, and the only place its order is decided:
|
||||
///
|
||||
/// 1. not configured — the copy names the fix (F7, or the env var);
|
||||
/// 2. `/tip` on a no-spend wallet — it can never spend, so it is refused
|
||||
/// before any dial, reachable or not (same rule as `transfer`);
|
||||
/// 3. configured but not connected — check endpoint, login, daemon;
|
||||
/// 4. otherwise ready. `/pay` is fine on a view-only wallet.
|
||||
pub fn readiness(configured: bool, connected: bool, no_spend: bool, is_tip: bool) -> Readiness {
|
||||
if !configured {
|
||||
return Readiness::NotConfigured;
|
||||
}
|
||||
if is_tip && no_spend {
|
||||
return Readiness::NoSpend;
|
||||
}
|
||||
if !connected {
|
||||
return Readiness::NotConnected;
|
||||
}
|
||||
Readiness::Ready
|
||||
}
|
||||
|
||||
/// Display copy, not a log line: drop the secret if some lower layer put it in
|
||||
/// the message, and keep it short enough for a status line.
|
||||
pub(crate) fn redact(msg: &str, secret: &str) -> String {
|
||||
let mut out = msg.trim().to_string();
|
||||
if !secret.is_empty() {
|
||||
out = out.replace(secret, "<redacted>");
|
||||
}
|
||||
const MAX: usize = 120;
|
||||
if out.chars().count() > MAX {
|
||||
out = out.chars().take(MAX).collect();
|
||||
out.push('…');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Endpoint {
|
||||
host: String,
|
||||
|
|
@ -83,12 +281,14 @@ pub struct Wallet {
|
|||
|
||||
/// What /tip says when the wallet cannot spend. Same text for the explicit
|
||||
/// `ONIONWIRE_WALLET_NO_SPEND=1` switch and for a view-only wallet detected over
|
||||
/// RPC, so the operator never has to guess which one it was.
|
||||
const VIEW_ONLY_MSG: &str = "wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work";
|
||||
/// RPC, so the operator never has to guess which one it was. The TUI's
|
||||
/// pay/tip guard returns this exact string (see [`Readiness::refusal`]).
|
||||
pub const VIEW_ONLY_MSG: &str = "wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work";
|
||||
|
||||
/// What a spend says while the wallet is not synced. Honest state, not a bug:
|
||||
/// the caller retries once the daemon has caught up.
|
||||
pub const NOT_SYNCED_MSG: &str = "wallet is not synced — spend refused until the daemon reaches the chain tip";
|
||||
pub const NOT_SYNCED_MSG: &str =
|
||||
"wallet is not synced — spend refused until the daemon reaches the chain tip";
|
||||
|
||||
/// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in monero's
|
||||
/// `src/wallet/wallet_rpc_server_error_codes.h`.
|
||||
|
|
@ -160,6 +360,125 @@ impl Wallet {
|
|||
Ok(Self::new(Some(parse_http_url(url, None)?), false))
|
||||
}
|
||||
|
||||
/// Build the wallet from stored config. `rpc_url` must be a usable loopback
|
||||
/// `http://` endpoint; the login is required and never echoed in an error.
|
||||
pub fn from_config(cfg: &WalletConfig) -> Result<Self> {
|
||||
if cfg.rpc_url.trim().is_empty() {
|
||||
return Err(Error("wallet RPC endpoint required".into()));
|
||||
}
|
||||
let ep = parse_http_url(cfg.rpc_url.trim(), Some(cfg.rpc_login.as_str()))
|
||||
.map_err(|e| Error(redact(&e.to_string(), cfg.secret())))?;
|
||||
Ok(Self::new(Some(ep), cfg.no_spend))
|
||||
}
|
||||
|
||||
/// Boot path: stored config wins, env is the migration/fallback path, and
|
||||
/// nothing at all means a disabled wallet (chat still works).
|
||||
///
|
||||
/// A stored config that cannot be used does not silently dial anything: it
|
||||
/// falls back to env/env-less, so a typo cannot point a spend at a host the
|
||||
/// user did not mean.
|
||||
pub fn for_boot(stored: Option<&WalletConfig>) -> Self {
|
||||
if let Some(cfg) = stored {
|
||||
match Self::from_config(cfg) {
|
||||
Ok(w) => return w,
|
||||
Err(e) => eprintln!("wallet config: {e}"),
|
||||
}
|
||||
}
|
||||
Self::from_env()
|
||||
}
|
||||
|
||||
/// The config in use, for the F7 screen's prefill. `None` when the wallet
|
||||
/// has no endpoint. The URL is rebuilt without userinfo; the login is the
|
||||
/// secret half.
|
||||
pub fn config(&self) -> Option<WalletConfig> {
|
||||
let ep = self.endpoint.as_ref()?;
|
||||
Some(WalletConfig {
|
||||
rpc_url: format!("http://{}{}", host_header(&ep.host, ep.port), ep.path),
|
||||
rpc_login: Zeroizing::new(format!("{}:{}", ep.user, ep.pass.as_str())),
|
||||
no_spend: self.no_spend,
|
||||
})
|
||||
}
|
||||
|
||||
/// One probe, folded into the snapshot the TUI draws: `get_address` (the
|
||||
/// cheapest call that also proves the RPC has a wallet open) then
|
||||
/// `get_balance` for the readout.
|
||||
///
|
||||
/// This is the freshness rule: `connected` is whatever the *last* probe
|
||||
/// said, never "config exists". A successful probe clears `last_error`; a
|
||||
/// failure sets `connected=false` and keeps `configured=true`.
|
||||
pub async fn status(&self) -> WalletStatus {
|
||||
if !self.configured() {
|
||||
return WalletStatus::idle(false);
|
||||
}
|
||||
match self.get_address().await {
|
||||
Ok(addr) => {
|
||||
let balance = match self.get_balance().await {
|
||||
Ok(b) if !b.trim().is_empty() => format!("{} piconero", b.trim()),
|
||||
_ => NOT_SET.to_string(),
|
||||
};
|
||||
WalletStatus {
|
||||
configured: true,
|
||||
connected: true,
|
||||
last_error: None,
|
||||
balance_line: balance,
|
||||
receive_address: if addr.trim().is_empty() {
|
||||
NOT_SET.to_string()
|
||||
} else {
|
||||
addr
|
||||
},
|
||||
}
|
||||
}
|
||||
Err(e) => WalletStatus {
|
||||
configured: true,
|
||||
connected: false,
|
||||
last_error: Some(self.sanitize(&e.to_string())),
|
||||
balance_line: NOT_SET.to_string(),
|
||||
receive_address: NOT_SET.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// One-shot Test-connection probe against an endpoint the user is *typing*
|
||||
/// (not necessarily the stored one). Same rules as every other call:
|
||||
/// loopback only, digest required, no password in the result.
|
||||
pub async fn ping(rpc_url: &str, rpc_login: &str) -> PingResult {
|
||||
let cfg = WalletConfig::new(rpc_url, rpc_login, false);
|
||||
let wallet = match Self::from_config(&cfg) {
|
||||
Ok(w) => w,
|
||||
Err(e) => {
|
||||
return PingResult {
|
||||
ok: false,
|
||||
status: "not connected".into(),
|
||||
error: Some(redact(&e.to_string(), cfg.secret())),
|
||||
};
|
||||
}
|
||||
};
|
||||
let st = wallet.status().await;
|
||||
if st.connected {
|
||||
PingResult {
|
||||
ok: true,
|
||||
status: "connected".into(),
|
||||
error: None,
|
||||
}
|
||||
} else {
|
||||
PingResult {
|
||||
ok: false,
|
||||
status: "not connected".into(),
|
||||
error: st.last_error,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Display-safe copy of an error: no RPC password, short enough for a line.
|
||||
fn sanitize(&self, msg: &str) -> String {
|
||||
let pass = self
|
||||
.endpoint
|
||||
.as_ref()
|
||||
.map(|e| e.pass.as_str())
|
||||
.unwrap_or("");
|
||||
redact(msg, pass)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
|
|
@ -298,10 +617,7 @@ impl Wallet {
|
|||
.and_then(|b| b.as_bool())
|
||||
.unwrap_or(false);
|
||||
let height = v.get("height").and_then(|h| h.as_u64()).unwrap_or(0);
|
||||
let target = v
|
||||
.get("target_height")
|
||||
.and_then(|h| h.as_u64())
|
||||
.unwrap_or(0);
|
||||
let target = v.get("target_height").and_then(|h| h.as_u64()).unwrap_or(0);
|
||||
Ok(synced && height > 0 && (target == 0 || height >= target))
|
||||
}
|
||||
|
||||
|
|
@ -351,11 +667,7 @@ impl Wallet {
|
|||
let v = self
|
||||
.rpc("query_key", serde_json::json!({"key_type": "mnemonic"}))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
Error(format!(
|
||||
"wallet created but seed backup unavailable: {e}"
|
||||
))
|
||||
})?;
|
||||
.map_err(|e| Error(format!("wallet created but seed backup unavailable: {e}")))?;
|
||||
json_str(&v, "key")
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue