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.
This commit is contained in:
parent
c5725856ad
commit
ed29131a67
12 changed files with 1262 additions and 54 deletions
689
src/node.rs
689
src/node.rs
|
|
@ -32,7 +32,9 @@ use crate::store::{
|
|||
Friend, FriendProfile, Message, NewWallet, Payment, PaymentWrite, Store, WalletRecord,
|
||||
};
|
||||
use crate::wallet::{self, ChainNetwork, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus};
|
||||
use crate::wallet_child::{ChildConfig, WalletChild, WalletChildState, WalletChildStatus};
|
||||
use crate::wallet_child::{
|
||||
ChildConfig, ChildWalletState, WalletChild, WalletChildState, WalletChildStatus,
|
||||
};
|
||||
|
||||
pub struct RotateResult {
|
||||
pub notified: usize,
|
||||
|
|
@ -134,6 +136,12 @@ pub struct Node {
|
|||
child_target: AtomicU64,
|
||||
/// The last child failure, display-ready. Cleared on a successful start.
|
||||
child_error: Mutex<Option<String>>,
|
||||
/// Whether the running child's wallet **file** is open. Not derivable from
|
||||
/// the process: `monero-wallet-rpc` starts with no wallet open, so a live
|
||||
/// child that answers every call with `-13 No wallet file` is a child
|
||||
/// waiting for a passphrase, not a healthy one. Only the start path, an
|
||||
/// explicit open, and a successful probe write it.
|
||||
child_wallet: Mutex<ChildWalletState>,
|
||||
incoming_limit: Mutex<TokenBucket>,
|
||||
inbox: Mutex<file::Inbox>,
|
||||
outbox: Arc<Outbox>,
|
||||
|
|
@ -206,6 +214,7 @@ impl Node {
|
|||
child_height: AtomicU64::new(0),
|
||||
child_target: AtomicU64::new(0),
|
||||
child_error: Mutex::new(None),
|
||||
child_wallet: Mutex::new(ChildWalletState::Unknown),
|
||||
incoming_limit: Mutex::new(TokenBucket::default()),
|
||||
inbox: Mutex::new(inbox),
|
||||
outbox: Arc::clone(&outbox),
|
||||
|
|
@ -659,23 +668,32 @@ impl Node {
|
|||
self.set_wallet_child_config(&cfg)
|
||||
}
|
||||
|
||||
/// Start the app-owned wallet child and point this node's wallet at it.
|
||||
/// Start the app-owned wallet child, point this node's wallet at it, and
|
||||
/// **open its wallet file**.
|
||||
///
|
||||
/// Idempotent: a live wallet child is reported, not respawned. Spawning is
|
||||
/// synchronous — argv is built, the child is spawned, and a `.onion` chain
|
||||
/// source waits up to `SOCKS_READY_TIMEOUT` for the SOCKS listener — which
|
||||
/// is why callers block on it (`rt.block_on` in the TUI).
|
||||
///
|
||||
/// The open is the whole point: `monero-wallet-rpc` starts with no wallet
|
||||
/// open, so a child that came up and was left alone answered every read
|
||||
/// with `-13 No wallet file` — a restart, a Lock/unlock, or a wallet
|
||||
/// re-point silently produced an inert wallet manager. The stored
|
||||
/// passphrase ([`Self::seal_wallet_passphrase`]) opens it.
|
||||
pub fn start_wallet_child(&self) -> Result<(), String> {
|
||||
self.start_wallet_child_with(None)
|
||||
}
|
||||
|
||||
/// [`Self::start_wallet_child`], with a passphrase the caller just collected
|
||||
/// instead of the stored one. Used by [`Self::open_wallet_with_passphrase`]:
|
||||
/// a passphrase is only trusted once a live RPC has opened a file with it.
|
||||
fn start_wallet_child_with(&self, passphrase: Option<&str>) -> Result<(), String> {
|
||||
let cfg = self.wallet_child_config();
|
||||
if !cfg.is_enabled() {
|
||||
return Err("no chain source configured — the wallet child is receive-only".into());
|
||||
}
|
||||
let already_running = self
|
||||
.wallet_child
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
.as_ref()
|
||||
.is_some_and(|child| child.wallet_rpc_running());
|
||||
let already_running = self.child_running();
|
||||
if already_running {
|
||||
return Ok(());
|
||||
}
|
||||
|
|
@ -699,9 +717,152 @@ impl Node {
|
|||
*self.child_error.lock().map_err(|e| e.to_string())? = None;
|
||||
self.reset_child_probe();
|
||||
*self.wallet_child.lock().map_err(|e| e.to_string())? = Some(child);
|
||||
*self.child_wallet.lock().map_err(|e| e.to_string())? = ChildWalletState::Unknown;
|
||||
if let Err(e) = self.open_child_wallet(passphrase) {
|
||||
// A child whose wallet the RPC would not open is not a child to
|
||||
// leave running: every read answers `-13`, which is exactly the
|
||||
// inert state this path exists to end, so stop it and report why.
|
||||
// A failure to *store* the passphrase is a different thing — the
|
||||
// wallet is open — so that child keeps running and the error says
|
||||
// what was lost.
|
||||
let state = self
|
||||
.child_wallet
|
||||
.lock()
|
||||
.map(|s| *s)
|
||||
.unwrap_or_default();
|
||||
if state != ChildWalletState::Open {
|
||||
self.stop_wallet_child()?;
|
||||
}
|
||||
*self.child_error.lock().map_err(|e| e.to_string())? = Some(e.clone());
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Is a wallet child process alive right now?
|
||||
fn child_running(&self) -> bool {
|
||||
self.wallet_child
|
||||
.lock()
|
||||
.map(|guard| guard.as_ref().is_some_and(|c| c.wallet_rpc_running()))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Does the catalogue hold this file name? The catalogue is the only
|
||||
/// directory this app has, so it decides what may be opened at all.
|
||||
fn catalogue_holds(&self, filename: &str) -> Result<bool, String> {
|
||||
Ok(self
|
||||
.list_wallets()?
|
||||
.iter()
|
||||
.any(|w| w.wallet_filename == filename))
|
||||
}
|
||||
|
||||
/// The wallet-file passphrase this install remembers, or empty. A store
|
||||
/// read: it never dials, and it works with the wallet off.
|
||||
fn stored_wallet_passphrase(&self) -> Result<Zeroizing<String>, String> {
|
||||
let cfg = self
|
||||
.store
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
.load_wallet_config()
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(match cfg {
|
||||
Some(cfg) => cfg.wallet_passphrase,
|
||||
None => Zeroizing::new(String::new()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Remember the passphrase that opens the wallet file, sealed beside the
|
||||
/// RPC creds. A read-modify-write: the stored endpoint, login, view-only
|
||||
/// flag and the generated child creds are all untouched.
|
||||
///
|
||||
/// This is the deliberate part of the design (see `docs/THREAT_MODEL.md`):
|
||||
/// the wallet file is only reopenable with its passphrase, `/wipe` keeps
|
||||
/// the wallet file, and a passphrase the user must re-type after every
|
||||
/// restart is a passphrase they will not use. Keeping it makes the store
|
||||
/// passphrase sufficient to spend.
|
||||
fn seal_wallet_passphrase(&self, passphrase: &str) -> Result<(), String> {
|
||||
if passphrase.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||||
let mut cfg = store
|
||||
.load_wallet_config()
|
||||
.map_err(|e| e.to_string())?
|
||||
.unwrap_or_default();
|
||||
if cfg.wallet_passphrase.as_str() == passphrase {
|
||||
return Ok(());
|
||||
}
|
||||
cfg.wallet_passphrase = Zeroizing::new(passphrase.to_string());
|
||||
store.save_wallet_config(&cfg).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Open the wallet file the configured child is pointed at, when this
|
||||
/// install can. `supplied` is a passphrase the user just handed over;
|
||||
/// `None` means "use the stored one".
|
||||
///
|
||||
/// Four outcomes, one of which is an error:
|
||||
/// * the configured file is not in the catalogue → nothing to open
|
||||
/// ([`ChildWalletState::Unknown`], `Ok`);
|
||||
/// * no passphrase is known → the child stays wallet-less and reports
|
||||
/// [`ChildWalletState::NeedsPassphrase`], `Ok`. An install whose wallet
|
||||
/// predates the stored passphrase must still start — the alternative is
|
||||
/// turning a missing secret into a start failure;
|
||||
/// * the file opens → [`ChildWalletState::Open`], and the passphrase is
|
||||
/// sealed;
|
||||
/// * the RPC refuses it → `Err` naming the file, never a generic start
|
||||
/// failure, and the caller stops the child.
|
||||
fn open_child_wallet(&self, supplied: Option<&str>) -> Result<(), String> {
|
||||
let filename = self.wallet_child_config().wallet_filename;
|
||||
if !self.catalogue_holds(&filename)? {
|
||||
*self.child_wallet.lock().map_err(|e| e.to_string())? = ChildWalletState::Unknown;
|
||||
return Ok(());
|
||||
}
|
||||
let passphrase = match supplied {
|
||||
Some(p) => Zeroizing::new(p.to_string()),
|
||||
None => self.stored_wallet_passphrase()?,
|
||||
};
|
||||
if passphrase.is_empty() {
|
||||
*self.child_wallet.lock().map_err(|e| e.to_string())? =
|
||||
ChildWalletState::NeedsPassphrase;
|
||||
return Ok(());
|
||||
}
|
||||
self.open_wallet_file(&filename, passphrase.as_str())
|
||||
}
|
||||
|
||||
/// Issue `open_wallet` against the RPC this node is talking to, and seal the
|
||||
/// passphrase only once a live daemon has accepted it. An unverified
|
||||
/// passphrase is never stored: the next start would then fail on a secret
|
||||
/// the user believed was right.
|
||||
fn open_wallet_file(&self, filename: &str, passphrase: &str) -> Result<(), String> {
|
||||
let wallet = self.wallet_snapshot();
|
||||
match open_wallet_blocking(&wallet, filename, passphrase) {
|
||||
Ok(()) => {
|
||||
*self.child_wallet.lock().map_err(|e| e.to_string())? = ChildWalletState::Open;
|
||||
*self.child_error.lock().map_err(|e| e.to_string())? = None;
|
||||
self.seal_wallet_passphrase(passphrase).map_err(|e| {
|
||||
format!("wallet {filename} opened but its passphrase was not stored: {e}")
|
||||
})
|
||||
}
|
||||
Err(failure) => {
|
||||
let msg = failure.message(filename);
|
||||
*self.child_wallet.lock().map_err(|e| e.to_string())? =
|
||||
ChildWalletState::NeedsPassphrase;
|
||||
*self.child_error.lock().map_err(|e| e.to_string())? = Some(msg.clone());
|
||||
Err(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The wallet file this process just created or imported is the one the
|
||||
/// child holds open — but only while a child is actually up to hold it.
|
||||
fn mark_child_wallet_open(&self) {
|
||||
if self.child_running()
|
||||
&& let Ok(mut state) = self.child_wallet.lock()
|
||||
{
|
||||
*state = ChildWalletState::Open;
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop the app-owned wallet child (idempotent) and put the wallet back on
|
||||
/// the stored/env config, if any. The next launch starts the child again —
|
||||
/// nothing promises it stays up across a restart, and Android will not.
|
||||
|
|
@ -711,6 +872,10 @@ impl Node {
|
|||
child.stop().map_err(|e| e.to_string())?;
|
||||
}
|
||||
self.reset_child_probe();
|
||||
// No process, no open wallet file. Whatever the last child managed is
|
||||
// gone with it, and claiming otherwise would make the UI skip the
|
||||
// prompt that opens the next one.
|
||||
*self.child_wallet.lock().map_err(|e| e.to_string())? = ChildWalletState::Unknown;
|
||||
let stored = self
|
||||
.store
|
||||
.lock()
|
||||
|
|
@ -766,9 +931,27 @@ impl Node {
|
|||
self.child_target.load(Ordering::Relaxed),
|
||||
),
|
||||
};
|
||||
let child_wallet = self
|
||||
.child_wallet
|
||||
.lock()
|
||||
.map(|state| *state)
|
||||
.unwrap_or_default();
|
||||
// A child that has exited holds nothing, whatever the last run managed.
|
||||
// An `off` node is not the same statement: with no app-owned child the
|
||||
// node may be talking to a remote-mode RPC the user runs themselves, and
|
||||
// an open wallet file there is a real open.
|
||||
let (wallet_open, needs_passphrase) = match state {
|
||||
WalletChildState::Exited => (false, child_wallet == ChildWalletState::NeedsPassphrase),
|
||||
_ => (
|
||||
child_wallet == ChildWalletState::Open,
|
||||
child_wallet == ChildWalletState::NeedsPassphrase,
|
||||
),
|
||||
};
|
||||
WalletChildStatus {
|
||||
state,
|
||||
running,
|
||||
wallet_open,
|
||||
needs_passphrase,
|
||||
configured: cfg.is_enabled(),
|
||||
chain_source: cfg.source_label(),
|
||||
height: heights.0,
|
||||
|
|
@ -813,6 +996,13 @@ impl Node {
|
|||
} else {
|
||||
None
|
||||
};
|
||||
// A wallet RPC that answers has a wallet open: `get_address` cannot
|
||||
// answer without one. That is the honest signal that the file is open,
|
||||
// whoever opened it (this node, or the user's own client against a
|
||||
// remote-mode endpoint).
|
||||
if connected && let Ok(mut slot) = self.child_wallet.lock() {
|
||||
*slot = ChildWalletState::Open;
|
||||
}
|
||||
let synced = progress.as_ref().is_some_and(wallet::ChainInfo::ready);
|
||||
let (height, target_height) = match progress {
|
||||
Some(info) => (info.height, info.target_height),
|
||||
|
|
@ -873,9 +1063,13 @@ impl Node {
|
|||
/// 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 mut cfg = cfg.clone();
|
||||
// The passphrase is the *file's*, not this screen's: keep whatever is
|
||||
// stored, or an F7 save would lock the wallet out of itself.
|
||||
cfg.wallet_passphrase = self.stored_wallet_passphrase()?;
|
||||
{
|
||||
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||||
store.save_wallet_config(cfg).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
|
||||
|
|
@ -1217,6 +1411,14 @@ impl Node {
|
|||
self.point_child_at(&filename).map_err(|e| {
|
||||
format!("wallet {filename} created but the child is not pointed at it: {e}")
|
||||
})?;
|
||||
// The passphrase that opens the file is a thing this app needs again on
|
||||
// the next start: the RPC drops the open wallet when the process goes.
|
||||
self.seal_wallet_passphrase(password).map_err(|e| {
|
||||
format!("wallet {filename} created but its passphrase was not stored: {e}")
|
||||
})?;
|
||||
// This process just created the file, so the RPC has it open — while a
|
||||
// child is running to hold it.
|
||||
self.mark_child_wallet_open();
|
||||
Ok(CreatedWallet { record, seed })
|
||||
}
|
||||
|
||||
|
|
@ -1287,6 +1489,12 @@ impl Node {
|
|||
self.point_child_at(&filename).map_err(|e| {
|
||||
format!("wallet {filename} imported but the child is not pointed at it: {e}")
|
||||
})?;
|
||||
// Import is a creation path too: remember the passphrase the RPC just
|
||||
// opened the file with, so the next start can open it again.
|
||||
self.seal_wallet_passphrase(password).map_err(|e| {
|
||||
format!("wallet {filename} imported but its passphrase was not stored: {e}")
|
||||
})?;
|
||||
self.mark_child_wallet_open();
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
|
|
@ -1300,27 +1508,24 @@ impl Node {
|
|||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Switch the wallet child to a catalogue wallet's file.
|
||||
/// Switch the wallet child to a catalogue wallet's file and open it.
|
||||
///
|
||||
/// The catalogue is the only directory this app has, so a file it does not
|
||||
/// hold is refused instead of pointing a spend-capable child at a path. A
|
||||
/// running child is restarted onto the new file; an idle one is only
|
||||
/// re-pointed, and the change applies on the next `start_wallet_child`. The
|
||||
/// write is a read-modify-write, so the generated RPC creds survive.
|
||||
/// running child is restarted onto the new file and opens it with the
|
||||
/// stored passphrase; an idle one is only re-pointed, and the change
|
||||
/// applies on the next `start_wallet_child`. The write is a
|
||||
/// read-modify-write, so the generated RPC creds survive.
|
||||
///
|
||||
/// When this install holds no passphrase for the file, the child comes up
|
||||
/// with no wallet open and the status reports `needs_passphrase` — not an
|
||||
/// error: [`Self::open_wallet_with_passphrase`] is the one-time fix, and
|
||||
/// after it the passphrase is stored.
|
||||
pub fn open_wallet(&self, filename: &str) -> Result<(), String> {
|
||||
if !self
|
||||
.list_wallets()?
|
||||
.iter()
|
||||
.any(|w| w.wallet_filename == filename)
|
||||
{
|
||||
if !self.catalogue_holds(filename)? {
|
||||
return Err(format!("no saved wallet in {filename}"));
|
||||
}
|
||||
let running = self
|
||||
.wallet_child
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
.as_ref()
|
||||
.is_some_and(|child| child.wallet_rpc_running());
|
||||
let running = self.child_running();
|
||||
if running {
|
||||
self.stop_wallet_child()?;
|
||||
}
|
||||
|
|
@ -1331,6 +1536,41 @@ impl Node {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Open a catalogue wallet with a passphrase the user just supplied, and
|
||||
/// remember it (sealed) once the RPC has accepted it.
|
||||
///
|
||||
/// This is the counterpart of a `needs_passphrase` status: a wallet created
|
||||
/// before the passphrase was stored, or created on another install, is
|
||||
/// opened once here and then reopens on every later start. A passphrase is
|
||||
/// only *verified* by a live RPC, so with a running child this restarts the
|
||||
/// child (opening the file as part of the start); with an idle child it
|
||||
/// dials the RPC this node is already talking to. With nothing to dial it
|
||||
/// refuses rather than sealing an unverified secret.
|
||||
pub fn open_wallet_with_passphrase(
|
||||
&self,
|
||||
filename: &str,
|
||||
passphrase: &str,
|
||||
) -> Result<(), String> {
|
||||
if passphrase.is_empty() {
|
||||
return Err("wallet passphrase required".into());
|
||||
}
|
||||
if !self.catalogue_holds(filename)? {
|
||||
return Err(format!("no saved wallet in {filename}"));
|
||||
}
|
||||
if !self.wallet_snapshot().configured() {
|
||||
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
||||
}
|
||||
let running = self.child_running();
|
||||
if running {
|
||||
self.stop_wallet_child()?;
|
||||
}
|
||||
self.point_child_at(filename)?;
|
||||
if running {
|
||||
return self.start_wallet_child_with(Some(passphrase));
|
||||
}
|
||||
self.open_wallet_file(filename, passphrase)
|
||||
}
|
||||
|
||||
/// The file name a wallet created now should live in. `wallet_filename` is
|
||||
/// UNIQUE and the catalogue is the only directory the app has, so this is
|
||||
/// `<default>-<n>` for the first `n` the catalogue does not already hold.
|
||||
|
|
@ -1852,6 +2092,84 @@ impl Node {
|
|||
}
|
||||
}
|
||||
|
||||
/// How long a freshly spawned child's wallet RPC gets to start answering before
|
||||
/// an `open_wallet` attempt is a failure rather than a start still in progress.
|
||||
/// `monero-wallet-rpc` binds its port well inside this; a child that never
|
||||
/// answers is reported, not waited on forever.
|
||||
const WALLET_OPEN_WAIT: Duration = Duration::from_secs(10);
|
||||
const WALLET_OPEN_POLL: Duration = Duration::from_millis(100);
|
||||
|
||||
/// Why an `open_wallet` did not happen. Split because the two want opposite
|
||||
/// treatment: one is a child still coming up, the other is the RPC's own answer
|
||||
/// and retrying it would only repeat it.
|
||||
enum OpenFailure {
|
||||
/// The RPC never answered inside the budget.
|
||||
NotAnswering(String),
|
||||
/// The RPC answered and refused — a wrong passphrase for that file.
|
||||
Refused(String),
|
||||
}
|
||||
|
||||
impl OpenFailure {
|
||||
/// Display copy. Names the file and the RPC's own reason; carries no secret
|
||||
/// (the passphrase never enters an error string).
|
||||
fn message(&self, filename: &str) -> String {
|
||||
match self {
|
||||
OpenFailure::Refused(detail) => format!(
|
||||
"wallet file {filename} is not open — the RPC refused its passphrase ({detail})"
|
||||
),
|
||||
OpenFailure::NotAnswering(detail) => format!(
|
||||
"wallet file {filename} is not open — the wallet RPC never answered ({detail})"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run one `open_wallet` from a synchronous caller, retrying only while the
|
||||
/// child's RPC is still coming up.
|
||||
///
|
||||
/// `Node::start_wallet_child` is synchronous (the TUI's key handler, and the
|
||||
/// SDK's `spawn_blocking` wrapper) while the wallet client is `tokio`, and a
|
||||
/// synchronous caller is not always somewhere the thread may be parked: a
|
||||
/// current-thread runtime (every `#[tokio::test]` here) shares its single thread
|
||||
/// with the reactor the future needs, so a nested `block_on` there would
|
||||
/// deadlock. The RPC therefore runs on a scratch thread with its own runtime —
|
||||
/// no nested runtime, no assumption about the caller.
|
||||
fn open_wallet_blocking(
|
||||
wallet: &Wallet,
|
||||
filename: &str,
|
||||
passphrase: &str,
|
||||
) -> std::result::Result<(), OpenFailure> {
|
||||
let wallet = wallet.clone();
|
||||
let filename = filename.to_string();
|
||||
let passphrase = Zeroizing::new(passphrase.to_string());
|
||||
std::thread::scope(|scope| {
|
||||
scope
|
||||
.spawn(|| {
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.map_err(|e| OpenFailure::NotAnswering(format!("runtime: {e}")))?;
|
||||
rt.block_on(async {
|
||||
let deadline = tokio::time::Instant::now() + WALLET_OPEN_WAIT;
|
||||
loop {
|
||||
match wallet.open_wallet(&filename, passphrase.as_str()).await {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) if e.is_unreachable() => {
|
||||
if tokio::time::Instant::now() >= deadline {
|
||||
return Err(OpenFailure::NotAnswering(e.to_string()));
|
||||
}
|
||||
tokio::time::sleep(WALLET_OPEN_POLL).await;
|
||||
}
|
||||
Err(e) => return Err(OpenFailure::Refused(e.to_string())),
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
.join()
|
||||
.map_err(|_| OpenFailure::NotAnswering("open_wallet thread panicked".into()))?
|
||||
})
|
||||
}
|
||||
|
||||
/// HKDF info strings for the bootstrap derivation (see [`bootstrap_ratchet`]).
|
||||
const RATCHET_BOOTSTRAP_SALT: &[u8] = b"onionwire-ratchet-v1-bootstrap";
|
||||
const RATCHET_BOOTSTRAP_ROOT_INFO: &[u8] = b"root";
|
||||
|
|
@ -2213,6 +2531,7 @@ pub(crate) mod tests {
|
|||
child_height: AtomicU64::new(0),
|
||||
child_target: AtomicU64::new(0),
|
||||
child_error: Mutex::new(None),
|
||||
child_wallet: Mutex::new(ChildWalletState::Unknown),
|
||||
incoming_limit: Mutex::new(TokenBucket::default()),
|
||||
inbox: Mutex::new(file::Inbox::new(home.join("inbox"))),
|
||||
outbox,
|
||||
|
|
@ -3225,6 +3544,12 @@ pub(crate) mod tests {
|
|||
vec![created.record],
|
||||
"the wallet just created is the catalogue"
|
||||
);
|
||||
assert_eq!(
|
||||
sealed_passphrase(&node),
|
||||
"hunter2",
|
||||
"the passphrase that opens the file is remembered, or the next \
|
||||
start cannot open it"
|
||||
);
|
||||
}
|
||||
|
||||
/// The second half of the bug: a second create reused the one hardcoded file
|
||||
|
|
@ -3498,4 +3823,320 @@ pub(crate) mod tests {
|
|||
"the RPC's -29 is the wallet's answer, not a failure"
|
||||
);
|
||||
}
|
||||
|
||||
/// A loopback wallet RPC that records every request it is asked and answers
|
||||
/// what a reopened wallet needs: `open_wallet`, `get_address` /
|
||||
/// `get_balance`, and a synced `get_info`. The request log is the evidence —
|
||||
/// a mock that answers whatever it is asked cannot tell a client that opened
|
||||
/// the file from one that never asked.
|
||||
fn recording_wallet_reply(
|
||||
requests: Arc<Mutex<Vec<String>>>,
|
||||
) -> Arc<dyn Fn(&str) -> String + Send + Sync> {
|
||||
Arc::new(move |req: &str| {
|
||||
requests.lock().expect("requests").push(req.to_string());
|
||||
if req.contains("open_wallet") {
|
||||
r#"{"jsonrpc":"2.0","id":"0","result":{}}"#.to_string()
|
||||
} else if req.contains("get_address") {
|
||||
format!(
|
||||
r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#,
|
||||
addr = xmr_addr()
|
||||
)
|
||||
} else if req.contains("get_info") {
|
||||
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"#
|
||||
.to_string()
|
||||
} else {
|
||||
r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0","unlocked_balance":"0"}}"#
|
||||
.to_string()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The port the fake child was spawned with. The fake bin writes its argv one
|
||||
/// argument per line, so `--rpc-bind-port` is followed by the number; the
|
||||
/// write happens right after `spawn` returns, hence the wait.
|
||||
async fn wait_for_child_rpc_port(argv_log: &Path) -> u16 {
|
||||
for _ in 0..600 {
|
||||
if let Ok(raw) = std::fs::read_to_string(argv_log) {
|
||||
let lines: Vec<&str> = raw.lines().collect();
|
||||
if let Some(i) = lines.iter().position(|line| *line == "--rpc-bind-port")
|
||||
&& let Some(port) = lines.get(i + 1).and_then(|p| p.trim().parse::<u16>().ok())
|
||||
{
|
||||
return port;
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
panic!(
|
||||
"the fake child never wrote an --rpc-bind-port to {}",
|
||||
argv_log.display()
|
||||
);
|
||||
}
|
||||
|
||||
/// The wallet-file passphrase this install remembers, `""` when none.
|
||||
fn sealed_passphrase(node: &Node) -> String {
|
||||
node.store
|
||||
.lock()
|
||||
.expect("store")
|
||||
.load_wallet_config()
|
||||
.expect("load wallet config")
|
||||
.map(|cfg| cfg.wallet_passphrase.as_str().to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The bug this card exists for: `monero-wallet-rpc` keeps a wallet open
|
||||
/// only for the life of its process, so a restarted child answered every
|
||||
/// read with `-13 No wallet file` while the file sat on disk. The second
|
||||
/// start must issue `open_wallet` with the file and the stored passphrase,
|
||||
/// and the read after it must take the success path.
|
||||
///
|
||||
/// Multi-threaded on purpose: the start path is synchronous and blocks, so
|
||||
/// only another worker can answer on the restarted child's port while it
|
||||
/// waits for its RPC to come up.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_restart_opens_the_stored_wallet_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let home = dir.path().join("child");
|
||||
let argv_log = dir.path().join("argv.log");
|
||||
let bin = fake_child_bin(
|
||||
&dir.path().join("fake-bins"),
|
||||
"monero-wallet-rpc",
|
||||
&argv_log,
|
||||
"sleep 30",
|
||||
);
|
||||
let node = Arc::new(offline_node(&home, Arc::new(NoDial)));
|
||||
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire-1"))
|
||||
.expect("set config");
|
||||
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
|
||||
|
||||
// First start: the catalogue holds the file, but this install holds no
|
||||
// passphrase for it. That is a state, not a failure.
|
||||
node.start_wallet_child().expect("first start");
|
||||
let status = node.wallet_child_status();
|
||||
assert!(status.running, "{status:?}");
|
||||
assert!(!status.wallet_open, "{status:?}");
|
||||
assert!(status.needs_passphrase, "{status:?}");
|
||||
assert!(status.last_error.is_none(), "{status:?}");
|
||||
|
||||
// Restart it with the passphrase the user supplied. The child picks a
|
||||
// fresh port, so the mock is bound to what the new argv names while the
|
||||
// open waits for the RPC to answer.
|
||||
std::fs::write(&argv_log, b"").expect("clear the argv log");
|
||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||
let starter = Arc::clone(&node);
|
||||
let started = tokio::task::spawn_blocking(move || {
|
||||
starter.open_wallet_with_passphrase("onionwire-1", "walletfile-pass")
|
||||
});
|
||||
let port = wait_for_child_rpc_port(&argv_log).await;
|
||||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("bind the restarted child's mock on {port}: {e}"));
|
||||
tokio::spawn(serve_mock_rpc(
|
||||
listener,
|
||||
recording_wallet_reply(Arc::clone(&requests)),
|
||||
));
|
||||
started
|
||||
.await
|
||||
.expect("join the start")
|
||||
.expect("open the wallet with a passphrase");
|
||||
|
||||
let sent = requests.lock().unwrap().join("\n");
|
||||
assert!(
|
||||
sent.contains(r#""method":"open_wallet""#),
|
||||
"the restart never asked the RPC to open the file: {sent}"
|
||||
);
|
||||
assert!(
|
||||
sent.contains(r#""filename":"onionwire-1""#),
|
||||
"the restart opened the wrong file: {sent}"
|
||||
);
|
||||
assert!(
|
||||
sent.contains(r#""password":"walletfile-pass""#),
|
||||
"the restart did not send the passphrase it was handed: {sent}"
|
||||
);
|
||||
assert_eq!(
|
||||
sealed_passphrase(&node),
|
||||
"walletfile-pass",
|
||||
"a verified passphrase is kept, or the next restart cannot open the file"
|
||||
);
|
||||
|
||||
// The read after the restart takes the success path: the same mock
|
||||
// answers `get_address`/`get_balance`/`get_info`.
|
||||
let status = node.wallet_child_refresh().await;
|
||||
assert!(status.wallet_open, "{status:?}");
|
||||
assert!(!status.needs_passphrase, "{status:?}");
|
||||
assert_eq!(status.state, WalletChildState::Ready, "{status:?}");
|
||||
assert!(
|
||||
requests
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|r| r.contains("get_balance")),
|
||||
"the wallet was read back through the reopened file"
|
||||
);
|
||||
|
||||
node.stop_wallet_child().expect("stop");
|
||||
}
|
||||
|
||||
/// No stored passphrase: the child starts with no wallet open and the status
|
||||
/// says `needs passphrase`. It must not fail the start — a wallet created
|
||||
/// before the passphrase was stored still has a working node — and it must
|
||||
/// not send an `open_wallet` it has no passphrase for.
|
||||
///
|
||||
/// Multi-threaded so the mock can answer while the start blocks, which is
|
||||
/// what makes "no `open_wallet` was sent" a measurement rather than a
|
||||
/// consequence of nothing being able to listen.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_catalogue_wallet_without_a_sealed_passphrase_never_asks_to_open() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let home = dir.path().join("child");
|
||||
let argv_log = dir.path().join("argv.log");
|
||||
let bin = fake_child_bin(
|
||||
&dir.path().join("fake-bins"),
|
||||
"monero-wallet-rpc",
|
||||
&argv_log,
|
||||
"sleep 30",
|
||||
);
|
||||
let node = Arc::new(offline_node(&home, Arc::new(NoDial)));
|
||||
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire-1"))
|
||||
.expect("set config");
|
||||
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
|
||||
|
||||
node.start_wallet_child()
|
||||
.expect("a wallet-less child still starts");
|
||||
let status = node.wallet_child_status();
|
||||
assert!(status.running, "{status:?}");
|
||||
assert!(!status.wallet_open, "{status:?}");
|
||||
assert!(status.needs_passphrase, "{status:?}");
|
||||
node.stop_wallet_child().expect("stop");
|
||||
|
||||
// A second start, this time with an RPC listening on the port it was
|
||||
// spawned with: had the start tried to open a file it would have dialed
|
||||
// this and left the request in the log (or died trying, and failed).
|
||||
std::fs::write(&argv_log, b"").expect("clear the argv log");
|
||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||
let starter = Arc::clone(&node);
|
||||
let started = tokio::task::spawn_blocking(move || starter.start_wallet_child());
|
||||
let port = wait_for_child_rpc_port(&argv_log).await;
|
||||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("bind the fake child's mock on {port}: {e}"));
|
||||
tokio::spawn(serve_mock_rpc(
|
||||
listener,
|
||||
recording_wallet_reply(Arc::clone(&requests)),
|
||||
));
|
||||
started
|
||||
.await
|
||||
.expect("join the start")
|
||||
.expect("second start");
|
||||
|
||||
let status = node.wallet_child_status();
|
||||
assert!(status.running, "{status:?}");
|
||||
assert!(status.needs_passphrase, "{status:?}");
|
||||
assert!(
|
||||
!requests
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|r| r.contains("open_wallet")),
|
||||
"there is no passphrase to open with, so no open_wallet may be sent"
|
||||
);
|
||||
node.stop_wallet_child().expect("stop");
|
||||
}
|
||||
|
||||
/// A refused passphrase is its own error, not a generic start failure, and
|
||||
/// an unverified passphrase is never stored: the next start must not be
|
||||
/// broken by a secret the user believed was right.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_refused_passphrase_is_a_distinct_error_and_is_not_sealed() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind mock wallet");
|
||||
let port = listener.local_addr().expect("mock wallet addr").port();
|
||||
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(|req: &str| {
|
||||
if req.contains("open_wallet") {
|
||||
r#"{"jsonrpc":"2.0","id":"0","error":{"code":-1,"message":"Failed to open wallet"}}"#
|
||||
.to_string()
|
||||
} else {
|
||||
r#"{"jsonrpc":"2.0","id":"0","result":{}}"#.to_string()
|
||||
}
|
||||
});
|
||||
tokio::spawn(serve_mock_rpc(listener, reply));
|
||||
let node = offline_node_with_wallet(
|
||||
&dir.path().join("bob"),
|
||||
Arc::new(NoDial),
|
||||
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url"),
|
||||
);
|
||||
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
|
||||
|
||||
let err = node
|
||||
.open_wallet_with_passphrase("onionwire-1", "wrong-pass")
|
||||
.expect_err("the RPC refuses the wrong passphrase");
|
||||
assert!(
|
||||
err.contains("onionwire-1"),
|
||||
"the error names the file: {err}"
|
||||
);
|
||||
assert!(
|
||||
err.contains("Failed to open wallet"),
|
||||
"the RPC's own reason is carried through: {err}"
|
||||
);
|
||||
assert!(!err.contains("wrong-pass"), "no secret in an error: {err}");
|
||||
let status = node.wallet_child_status();
|
||||
assert!(status.needs_passphrase, "{status:?}");
|
||||
assert!(!status.wallet_open, "{status:?}");
|
||||
assert!(
|
||||
sealed_passphrase(&node).is_empty(),
|
||||
"a passphrase no daemon accepted must not be stored"
|
||||
);
|
||||
assert_eq!(
|
||||
node.wallet_child_config().wallet_filename,
|
||||
"onionwire-1",
|
||||
"the child is still pointed at the wallet the user is unlocking"
|
||||
);
|
||||
}
|
||||
|
||||
/// The one-time path that ends the `needs passphrase` state: the passphrase
|
||||
/// is verified by a live RPC, then stored, and the status flips to open. The
|
||||
/// catalogue still refuses a file it does not hold.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn open_wallet_with_passphrase_seals_what_a_daemon_verified() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind mock wallet");
|
||||
let port = listener.local_addr().expect("mock wallet addr").port();
|
||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||
tokio::spawn(serve_mock_rpc(
|
||||
listener,
|
||||
recording_wallet_reply(Arc::clone(&requests)),
|
||||
));
|
||||
let node = offline_node_with_wallet(
|
||||
&dir.path().join("bob"),
|
||||
Arc::new(NoDial),
|
||||
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url"),
|
||||
);
|
||||
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
|
||||
|
||||
let err = node
|
||||
.open_wallet_with_passphrase("onionwire-1", "")
|
||||
.expect_err("no passphrase to open with");
|
||||
assert!(err.contains("passphrase"), "{err}");
|
||||
let err = node
|
||||
.open_wallet_with_passphrase("onionwire-9", "walletfile-pass")
|
||||
.expect_err("not a saved wallet");
|
||||
assert!(err.contains("no saved wallet"), "{err}");
|
||||
|
||||
node.open_wallet_with_passphrase("onionwire-1", "walletfile-pass")
|
||||
.expect("open a saved wallet");
|
||||
|
||||
let sent = requests.lock().unwrap().join("\n");
|
||||
assert!(
|
||||
sent.contains(r#""method":"open_wallet""#),
|
||||
"no open_wallet request: {sent}"
|
||||
);
|
||||
assert!(sent.contains(r#""filename":"onionwire-1""#), "{sent}");
|
||||
assert_eq!(sealed_passphrase(&node), "walletfile-pass");
|
||||
let status = node.wallet_child_status();
|
||||
assert!(status.wallet_open, "{status:?}");
|
||||
assert!(!status.needs_passphrase, "{status:?}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
84
src/store.rs
84
src/store.rs
|
|
@ -294,13 +294,17 @@ impl Store {
|
|||
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`).
|
||||
-- the login, the view-only flag, and the passphrase that opens the
|
||||
-- wallet file the child is pointed at. One row; the login and the
|
||||
-- passphrase are each sealed with the store data key under their
|
||||
-- own AAD (see `save_wallet_config`), so one ciphertext cannot be
|
||||
-- swapped for the other.
|
||||
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,
|
||||
sealed_passphrase BLOB,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
-- The wallet catalogue: one row per wallet file this install knows
|
||||
|
|
@ -410,26 +414,49 @@ impl Store {
|
|||
|
||||
/// 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).
|
||||
/// turns the stored wallet off again) — unless a wallet **passphrase** is
|
||||
/// remembered in the row, which the endpoint has nothing to do with and
|
||||
/// must survive: it belongs to the wallet file, not to the RPC endpoint.
|
||||
///
|
||||
/// 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.
|
||||
/// The login is `user:pass` for a wallet that can spend and the passphrase
|
||||
/// opens the wallet file, so both are sealed with the store data key on top
|
||||
/// of the whole-db SQLCipher layer — the same discipline as the wallet-child
|
||||
/// creds — and under separate AADs, so neither ciphertext can be replayed
|
||||
/// into the other's column.
|
||||
pub fn save_wallet_config(&self, cfg: &crate::wallet::WalletConfig) -> Result<()> {
|
||||
if cfg.rpc_url.trim().is_empty() {
|
||||
if cfg.rpc_url.trim().is_empty() && cfg.wallet_passphrase.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)?;
|
||||
let sealed_pass = if cfg.wallet_passphrase.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(
|
||||
crate::backup::aead_encrypt(
|
||||
&self.msg_key,
|
||||
cfg.wallet_passphrase.as_bytes(),
|
||||
WALLET_PASSPHRASE_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)
|
||||
"INSERT INTO wallet_config (id, rpc_url, sealed_login, no_spend, sealed_passphrase, updated_at)
|
||||
VALUES (1, ?1, ?2, ?3, ?4, ?5)
|
||||
ON CONFLICT(id) DO UPDATE SET rpc_url = excluded.rpc_url,
|
||||
sealed_login = excluded.sealed_login, no_spend = excluded.no_spend,
|
||||
sealed_passphrase = excluded.sealed_passphrase,
|
||||
updated_at = excluded.updated_at",
|
||||
params![cfg.rpc_url.trim(), sealed, cfg.no_spend as i64, unix_now()],
|
||||
params![
|
||||
cfg.rpc_url.trim(),
|
||||
sealed,
|
||||
cfg.no_spend as i64,
|
||||
sealed_pass,
|
||||
unix_now()
|
||||
],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -437,27 +464,42 @@ impl Store {
|
|||
/// 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
|
||||
type WalletConfigRow = (String, Vec<u8>, i64, Option<Vec<u8>>);
|
||||
let row: Option<WalletConfigRow> = self
|
||||
.conn
|
||||
.query_row(
|
||||
"SELECT rpc_url, sealed_login, no_spend FROM wallet_config WHERE id = 1",
|
||||
"SELECT rpc_url, sealed_login, no_spend, sealed_passphrase
|
||||
FROM wallet_config WHERE id = 1",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
|
||||
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let Some((rpc_url, sealed, no_spend)) = row else {
|
||||
let Some((rpc_url, sealed, no_spend, sealed_pass)) = 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`.
|
||||
// Both are secrets: neither may survive in a bare `String`.
|
||||
let login = Zeroizing::new(
|
||||
String::from_utf8(login).map_err(|_| Error("wallet config is not utf-8".into()))?,
|
||||
);
|
||||
let wallet_passphrase = match sealed_pass {
|
||||
None => Zeroizing::new(String::new()),
|
||||
Some(blob) => {
|
||||
let plain =
|
||||
crate::backup::aead_decrypt(&self.msg_key, &blob, WALLET_PASSPHRASE_AAD)
|
||||
.map_err(|_| Error("wallet passphrase decrypt failed".into()))?;
|
||||
Zeroizing::new(
|
||||
String::from_utf8(plain)
|
||||
.map_err(|_| Error("wallet passphrase is not utf-8".into()))?,
|
||||
)
|
||||
}
|
||||
};
|
||||
Ok(Some(crate::wallet::WalletConfig {
|
||||
rpc_url,
|
||||
rpc_login: login,
|
||||
no_spend: no_spend != 0,
|
||||
wallet_passphrase,
|
||||
}))
|
||||
}
|
||||
|
||||
|
|
@ -595,6 +637,14 @@ impl Store {
|
|||
"hs_nickname",
|
||||
"ALTER TABLE self ADD COLUMN hs_nickname TEXT NOT NULL DEFAULT 'ow0'",
|
||||
)?;
|
||||
// The wallet file's passphrase (sealed). NULL on an install that has
|
||||
// never been told one — a wallet created before this column, or a
|
||||
// remote-mode wallet the user opens themselves.
|
||||
self.add_column_if_missing(
|
||||
"wallet_config",
|
||||
"sealed_passphrase",
|
||||
"ALTER TABLE wallet_config ADD COLUMN sealed_passphrase BLOB",
|
||||
)?;
|
||||
// Opaque send payload for rows that cannot re-derive their bytes (a
|
||||
// chat send's ratchet frame). NULL means "send the message body", the
|
||||
// pre-payload behaviour, so locator/profile/payment rows are unchanged.
|
||||
|
|
@ -1813,6 +1863,10 @@ 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";
|
||||
/// The wallet-file passphrase's own AAD: same key and construction as the
|
||||
/// login, a different binding, so the two sealed columns are not
|
||||
/// interchangeable.
|
||||
const WALLET_PASSPHRASE_AAD: &[u8] = b"onionwire/wallet-passphrase/v1";
|
||||
|
||||
fn fingerprint(pubkey: &[u8]) -> String {
|
||||
pubkey.iter().map(|b| format!("{b:02x}")).collect()
|
||||
|
|
|
|||
95
src/tui.rs
95
src/tui.rs
|
|
@ -1307,6 +1307,14 @@ enum WalletSetup {
|
|||
CreateSeed { seed: Zeroizing<String>, typed: String },
|
||||
ImportSeed { buf: Zeroizing<String> },
|
||||
ImportPass { seed: Zeroizing<String>, entry: PassphraseEntry },
|
||||
/// The wallet file the child is pointed at is not open because this install
|
||||
/// has no passphrase for it. Same prompt idiom as the create path: one
|
||||
/// hidden entry, `Enter` submits, `Esc` cancels, and the buffer is zeroized
|
||||
/// on every exit.
|
||||
UnlockPass {
|
||||
filename: String,
|
||||
entry: PassphraseEntry,
|
||||
},
|
||||
}
|
||||
|
||||
/// A function key the TUI answers before the per-screen `match`; the screen's
|
||||
|
|
@ -2112,8 +2120,26 @@ impl App {
|
|||
let opened = self.select_wallet(index);
|
||||
match opened {
|
||||
Ok(label) => {
|
||||
self.status_note = Some(format!("opened wallet {label}"));
|
||||
self.screen = Screen::Main;
|
||||
// The child is pointed at the file either way; whether
|
||||
// it could *open* it is a separate fact, and the one the
|
||||
// user has to answer for when this install holds no
|
||||
// passphrase (a wallet created before one was stored).
|
||||
if self.node.wallet_child_status().needs_passphrase {
|
||||
let filename = self
|
||||
.node
|
||||
.active_wallet_filename()
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or_default();
|
||||
self.status_note = Some(format!("wallet {label} needs its passphrase"));
|
||||
self.screen = Screen::WalletSetup(WalletSetup::UnlockPass {
|
||||
filename,
|
||||
entry: PassphraseEntry::new(),
|
||||
});
|
||||
} else {
|
||||
self.status_note = Some(format!("opened wallet {label}"));
|
||||
self.screen = Screen::Main;
|
||||
}
|
||||
}
|
||||
Err(e) => self.alert = Some(e),
|
||||
}
|
||||
|
|
@ -2247,6 +2273,26 @@ impl App {
|
|||
Ok(()) => self.wallet_child_note(),
|
||||
Err(e) => format!("wallet child: {e}"),
|
||||
});
|
||||
self.prompt_for_wallet_passphrase();
|
||||
}
|
||||
|
||||
/// A started child whose wallet file is not open: ask for the passphrase
|
||||
/// instead of leaving the user with a child that answers `-13` to every
|
||||
/// read. Reuses the create path's prompt.
|
||||
fn prompt_for_wallet_passphrase(&mut self) {
|
||||
if !self.node.wallet_child_status().needs_passphrase {
|
||||
return;
|
||||
}
|
||||
let filename = self
|
||||
.node
|
||||
.active_wallet_filename()
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or_default();
|
||||
self.screen = Screen::WalletSetup(WalletSetup::UnlockPass {
|
||||
filename,
|
||||
entry: PassphraseEntry::new(),
|
||||
});
|
||||
}
|
||||
|
||||
/// Key `x`: stop the child (idempotent) and drop back to the stored/env
|
||||
|
|
@ -2341,7 +2387,9 @@ impl App {
|
|||
};
|
||||
if key.code == KeyCode::Esc {
|
||||
match setup {
|
||||
WalletSetup::CreatePass { entry } | WalletSetup::ImportPass { entry, .. } => {
|
||||
WalletSetup::CreatePass { entry }
|
||||
| WalletSetup::ImportPass { entry, .. }
|
||||
| WalletSetup::UnlockPass { entry, .. } => {
|
||||
entry.close();
|
||||
}
|
||||
WalletSetup::CreateSeed { seed, .. } => seed.zeroize(),
|
||||
|
|
@ -2476,6 +2524,33 @@ impl App {
|
|||
}
|
||||
_ => {}
|
||||
},
|
||||
WalletSetup::UnlockPass { filename, entry } => match key.code {
|
||||
KeyCode::Backspace => entry.backspace(),
|
||||
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
entry.push(c);
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
// One entry, no confirm: this passphrase is already the
|
||||
// file's, and a re-type would only be a second chance to
|
||||
// typo it.
|
||||
let pass = entry.take_buf();
|
||||
let filename = filename.clone();
|
||||
match self
|
||||
.node
|
||||
.open_wallet_with_passphrase(&filename, pass.as_str())
|
||||
{
|
||||
Ok(()) => {
|
||||
self.status_note = Some(format!("opened wallet {filename}"));
|
||||
self.screen = Screen::Main;
|
||||
}
|
||||
Err(e) => {
|
||||
self.alert = Some(e);
|
||||
self.screen = Screen::Main;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -3326,7 +3401,11 @@ match screen {
|
|||
"c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help"
|
||||
}
|
||||
Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help",
|
||||
Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => {
|
||||
Screen::WalletSetup(
|
||||
WalletSetup::CreatePass { .. }
|
||||
| WalletSetup::ImportPass { .. }
|
||||
| WalletSetup::UnlockPass { .. },
|
||||
) => {
|
||||
"Enter submit Esc cancel ? help"
|
||||
}
|
||||
Screen::WalletSetup(WalletSetup::CreateSeed { .. }) => "type SEEN Esc cancel ? help",
|
||||
|
|
@ -5222,6 +5301,14 @@ fn draw_wallet_setup(f: &mut Frame, setup: &WalletSetup) {
|
|||
"passphrase for the imported wallet file\n\nEnter continues Esc cancels".into()
|
||||
},
|
||||
),
|
||||
WalletSetup::UnlockPass { filename, .. } => (
|
||||
"wallet passphrase",
|
||||
format!(
|
||||
"the wallet file {filename} is not open\n\
|
||||
enter its passphrase to open it (it is then remembered, sealed)\n\n\
|
||||
Enter submits Esc cancels"
|
||||
),
|
||||
),
|
||||
};
|
||||
draw_text_overlay(f, title, &body);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,6 +19,20 @@ impl std::fmt::Display for Error {
|
|||
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
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 {
|
||||
|
|
@ -147,6 +161,17 @@ pub struct WalletConfig {
|
|||
pub rpc_login: Zeroizing<String>,
|
||||
/// View-only deployment: `/tip` is refused locally, before any dial.
|
||||
pub no_spend: bool,
|
||||
/// The passphrase that opens the wallet *file* the child is pointed at
|
||||
/// ([`Wallet::open_wallet`]). Sealed at rest beside `rpc_login`; empty when
|
||||
/// this install has never been told one (a wallet that predates the field,
|
||||
/// or a remote-mode wallet the user runs themselves).
|
||||
///
|
||||
/// Keeping it is deliberate: it makes the store passphrase sufficient to
|
||||
/// spend, and it is why the app can reopen a wallet file across a restart
|
||||
/// at all — `monero-wallet-rpc` holds an open file only for the life of the
|
||||
/// process, and re-opening it needs the passphrase. See
|
||||
/// `docs/THREAT_MODEL.md`.
|
||||
pub wallet_passphrase: Zeroizing<String>,
|
||||
}
|
||||
|
||||
impl WalletConfig {
|
||||
|
|
@ -155,9 +180,19 @@ impl WalletConfig {
|
|||
rpc_url: rpc_url.trim().to_string(),
|
||||
rpc_login: Zeroizing::new(rpc_login.trim().to_string()),
|
||||
no_spend,
|
||||
wallet_passphrase: Zeroizing::new(String::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the passphrase that opens the wallet file this config's child is
|
||||
/// pointed at. Chainable, and the only way to supply it from outside the
|
||||
/// crate: the field is public too, but a builder keeps a caller from
|
||||
/// forgetting that it is sealed beside the login.
|
||||
pub fn with_wallet_passphrase(mut self, passphrase: &str) -> Self {
|
||||
self.wallet_passphrase = Zeroizing::new(passphrase.to_string());
|
||||
self
|
||||
}
|
||||
|
||||
/// The password half of `user:pass` (the whole string when there is no
|
||||
/// colon), for redaction. Never rendered anywhere.
|
||||
pub fn secret(&self) -> &str {
|
||||
|
|
@ -176,6 +211,14 @@ impl std::fmt::Debug for WalletConfig {
|
|||
.field("rpc_url", &self.rpc_url)
|
||||
.field("rpc_login", &"<redacted>")
|
||||
.field("no_spend", &self.no_spend)
|
||||
.field(
|
||||
"wallet_passphrase",
|
||||
&if self.wallet_passphrase.is_empty() {
|
||||
"<none>"
|
||||
} else {
|
||||
"<redacted>"
|
||||
},
|
||||
)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
|
@ -185,6 +228,7 @@ impl PartialEq for WalletConfig {
|
|||
self.rpc_url == other.rpc_url
|
||||
&& self.rpc_login.as_str() == other.rpc_login.as_str()
|
||||
&& self.no_spend == other.no_spend
|
||||
&& self.wallet_passphrase.as_str() == other.wallet_passphrase.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -525,6 +569,10 @@ impl Wallet {
|
|||
rpc_url: format!("http://{}{}", host_header(&ep.host, ep.port), ep.path),
|
||||
rpc_login: Zeroizing::new(format!("{}:{}", ep.user, ep.pass.as_str())),
|
||||
no_spend: self.no_spend,
|
||||
// Not known here: the passphrase is the *file's*, and this builds
|
||||
// the config of the RPC endpoint in use. Callers that persist a
|
||||
// config do a read-modify-write so the stored one survives.
|
||||
wallet_passphrase: Zeroizing::new(String::new()),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -809,6 +857,41 @@ impl Wallet {
|
|||
json_str(&v, "key")
|
||||
}
|
||||
|
||||
/// Open a wallet *file* on the RPC (`open_wallet`).
|
||||
///
|
||||
/// `monero-wallet-rpc` starts with no wallet open, and `create_wallet` /
|
||||
/// `restore_deterministic_wallet` leave theirs open for that process only:
|
||||
/// after a restart every read answers `-13 No wallet file` even though the
|
||||
/// file is on disk. This is the call that opens it, and the only way a
|
||||
/// wallet survives the child being restarted.
|
||||
///
|
||||
/// The passphrase travels in the JSON-RPC body, never on the argv: `ps` is
|
||||
/// world-readable for the same user, and `--wallet-file`/`--password`
|
||||
/// would put the secret there. `filename` is a name inside the child's
|
||||
/// `--wallet-dir`, never a path.
|
||||
///
|
||||
/// A wrong passphrase is the RPC's own error (the daemon does not open a
|
||||
/// file it cannot decrypt); it is surfaced as-is, never retried into a
|
||||
/// generic failure by the caller.
|
||||
pub async fn open_wallet(&self, filename: &str, password: &str) -> Result<()> {
|
||||
let filename = filename.trim();
|
||||
if filename.is_empty() {
|
||||
return Err(Error("wallet filename required".into()));
|
||||
}
|
||||
if password.is_empty() {
|
||||
return Err(Error("wallet passphrase required".into()));
|
||||
}
|
||||
self.rpc(
|
||||
"open_wallet",
|
||||
serde_json::json!({
|
||||
"filename": filename,
|
||||
"password": password,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Re-read the seed of the wallet file the RPC has open (`query_key
|
||||
/// mnemonic`). After `create_wallet` this is the **only** way to recover a
|
||||
/// created wallet's seed, so the UI can offer a backup action instead of
|
||||
|
|
|
|||
|
|
@ -892,12 +892,49 @@ impl WalletChildState {
|
|||
}
|
||||
}
|
||||
|
||||
/// Whether the wallet **file** the child is pointed at is open in the running
|
||||
/// `monero-wallet-rpc`.
|
||||
///
|
||||
/// This is not the same question as "is the RPC up": the daemon starts with no
|
||||
/// wallet open, so a live child that answers every call with `-13 No wallet
|
||||
/// file` is `NeedsPassphrase`, not a start failure.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum ChildWalletState {
|
||||
/// Nothing to open, or nothing attempted yet: no catalogue wallet under the
|
||||
/// configured file name, or no child.
|
||||
#[default]
|
||||
Unknown,
|
||||
/// The wallet file is open (`open_wallet` succeeded, or this process just
|
||||
/// created it).
|
||||
Open,
|
||||
/// A wallet file the catalogue holds is not open, and this install holds no
|
||||
/// passphrase that could open it. Not an error: the user supplies it once.
|
||||
NeedsPassphrase,
|
||||
}
|
||||
|
||||
impl ChildWalletState {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
ChildWalletState::Unknown => "unknown",
|
||||
ChildWalletState::Open => "open",
|
||||
ChildWalletState::NeedsPassphrase => "needs-passphrase",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One snapshot of the child. Cheap to read: no dial, no lock held across work.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct WalletChildStatus {
|
||||
pub state: WalletChildState,
|
||||
/// A child process is alive right now.
|
||||
pub running: bool,
|
||||
/// The wallet file the child is pointed at is open in its RPC. `false` is
|
||||
/// the honest answer for an off/exited child and for one whose
|
||||
/// `open_wallet` has not succeeded.
|
||||
pub wallet_open: bool,
|
||||
/// A catalogue wallet is configured but not open, so a passphrase is needed
|
||||
/// before any read can work. Distinct from a failed start.
|
||||
pub needs_passphrase: bool,
|
||||
/// A chain source is configured (not receive-only), whether or not it runs.
|
||||
pub configured: bool,
|
||||
/// The chain-source label: `receive-only` / `local node` /
|
||||
|
|
@ -921,6 +958,9 @@ impl WalletChildStatus {
|
|||
return String::new();
|
||||
}
|
||||
let mut line = format!("child {} · {}", self.state.as_str(), self.chain_source);
|
||||
if self.needs_passphrase {
|
||||
line.push_str(" · wallet locked");
|
||||
}
|
||||
// A probe that read nothing says nothing: the line is unchanged until a
|
||||
// daemon (or the wallet's daemon) actually reported numbers. No
|
||||
// percentage is derived — `target_height == 0` is "the daemon told us
|
||||
|
|
@ -1997,6 +2037,8 @@ mod tests {
|
|||
WalletChildStatus {
|
||||
state,
|
||||
running: true,
|
||||
wallet_open: true,
|
||||
needs_passphrase: false,
|
||||
configured: true,
|
||||
chain_source: "in-process node".to_string(),
|
||||
height,
|
||||
|
|
|
|||
Loading…
Reference in a new issue