Compare commits

..
4 changed files with 44 additions and 701 deletions

View file

@ -587,16 +587,11 @@ impl Wire {
/// Create a new spend-capable wallet. Returns the 25-word seed once so the /// Create a new spend-capable wallet. Returns the 25-word seed once so the
/// UI can show a backup screen. The user does not paste a key on this path. /// UI can show a backup screen. The user does not paste a key on this path.
/// Requires `ONIONWIRE_WALLET_RPC` pointed at a `--wallet-dir` RPC. /// Requires `ONIONWIRE_WALLET_RPC` pointed at a `--wallet-dir` RPC.
///
/// The core also records the new wallet in its catalogue (`Node::wallet_create`
/// returns the stored row); the seed is what this surface carries.
pub async fn create_wallet(&self, password: String) -> WResult<String> { pub async fn create_wallet(&self, password: String) -> WResult<String> {
Ok(self self.node()?
.node()?
.wallet_create(&password) .wallet_create(&password)
.await .await
.map_err(WireError::new)? .map_err(WireError::new)
.seed)
} }
/// Re-read this wallet's 25-word seed so the UI can offer a "back up seed" /// Re-read this wallet's 25-word seed so the UI can offer a "back up seed"
@ -611,14 +606,12 @@ impl Wire {
} }
/// Import a wallet from an existing 25-word seed. This is the only path /// Import a wallet from an existing 25-word seed. This is the only path
/// that takes a user-supplied secret. Like a create, the core records the /// that takes a user-supplied secret.
/// imported wallet in its catalogue.
pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> { pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> {
self.node()? self.node()?
.wallet_restore(&password, &seed) .wallet_restore(&password, &seed)
.await .await
.map_err(WireError::new) .map_err(WireError::new)
.map(|_| ())
} }
/// Start the app-owned wallet child (`monero-wallet-rpc`, plus `monerod` for /// Start the app-owned wallet child (`monero-wallet-rpc`, plus `monerod` for

View file

@ -150,24 +150,9 @@ failed is named on the screen — that is a different state from `no saved walle
yet`, and the two never share copy. yet`, and the two never share copy.
Rows are plain display data (`WalletRow`), built by the caller from Rows are plain display data (`WalletRow`), built by the caller from
`Node::list_wallets`; the render path never reads the store. Selection is by `Store::list_wallets`; the render path never reads the store. Selection is by
row index, not by identity key (two records may share one). row index, not by identity key (two records may share one).
The list is read when the screen opens — from the start screen and from
`F6` `w` — so a wallet created or imported in this session is offered the next
time the screen opens, with no restart. Enter on a wallet row re-points the
app-owned wallet child at that row's `wallet_filename` (`Node::open_wallet`,
a read-modify-write of the sealed record, so the generated RPC creds survive);
a running child is restarted onto the new file, and an idle one picks the
change up on its next start.
**Start screen.** An install with at least one saved wallet opens on
`WalletSelect`; a fresh install (empty catalogue) opens on the create flow
(`WalletSetup::CreateWarn`), so the first run has no dead empty list. The
stored identity and locator are catalogue columns, not session state: a locator
rotates (`F4`) and identity is the roster key the node already holds, so the
live header keeps reading them from the node.
## Wallets & settings (`F9` / `/settings`) ## Wallets & settings (`F9` / `/settings`)
Discovery layer, not a replacement. Function keys stay live on this screen. Discovery layer, not a replacement. Function keys stay live on this screen.

View file

@ -28,9 +28,7 @@ use crate::ratchet::{RatchetKeyPair, RatchetState};
use crate::ratelimit::TokenBucket; use crate::ratelimit::TokenBucket;
use crate::sanitize; use crate::sanitize;
use crate::session::{self, Keys}; use crate::session::{self, Keys};
use crate::store::{ use crate::store::{Friend, FriendProfile, Message, Payment, PaymentWrite, Store};
Friend, FriendProfile, Message, NewWallet, Payment, PaymentWrite, Store, WalletRecord,
};
use crate::wallet::{self, ChainNetwork, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus}; use crate::wallet::{self, ChainNetwork, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus};
use crate::wallet_child::{ChildConfig, WalletChild, WalletChildState, WalletChildStatus}; use crate::wallet_child::{ChildConfig, WalletChild, WalletChildState, WalletChildStatus};
@ -82,29 +80,6 @@ impl Drop for WorkerHandle {
} }
} }
/// A wallet just created on the wallet RPC and recorded in the store's
/// catalogue: the row is what makes it survive a restart, and the seed is the
/// one-time backup the UI shows before the wallet is used. The caller owns
/// wiping `seed` (the TUI moves it straight into a `Zeroizing`).
pub struct CreatedWallet {
/// The stored catalogue row, with the id and `created_at` the store
/// assigned. `wallet_filename` is the file this wallet lives in.
pub record: WalletRecord,
/// The 25-word seed, returned once by the create path.
pub seed: String,
}
/// Hand-written so a stray `{:?}` cannot print the seed: the record is the
/// wallet, the mnemonic is the money.
impl std::fmt::Debug for CreatedWallet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CreatedWallet")
.field("record", &self.record)
.field("seed", &"<redacted>")
.finish()
}
}
pub struct Node { pub struct Node {
home: PathBuf, home: PathBuf,
store: Arc<Mutex<Store>>, store: Arc<Mutex<Store>>,
@ -1192,32 +1167,16 @@ impl Node {
Ok(rows.into_iter().take(cap).collect()) Ok(rows.into_iter().take(cap).collect())
} }
/// Create a new spend-capable wallet and record it in the catalogue. The /// Create a new spend-capable wallet. Returns the seed once for backup.
/// user never pastes a key on this path. /// The user never pastes a key on this path.
/// pub async fn wallet_create(&self, password: &str) -> Result<String, String> {
/// The wallet file gets its own name ([`Self::next_wallet_filename`]):
/// `wallet_filename` is UNIQUE, so a second create that reused the old
/// hardcoded name would open the first wallet's file — or be refused by the
/// RPC outright, which is the "cannot create a new wallet" failure. The
/// stored row is what makes the wallet survive a restart; the wallet dir is
/// not scanned.
pub async fn wallet_create(&self, password: &str) -> Result<CreatedWallet, String> {
let w = self.wallet_snapshot(); let w = self.wallet_snapshot();
if !w.configured() { if !w.configured() {
return Err(wallet::NOT_CONFIGURED_MSG.into()); return Err(wallet::NOT_CONFIGURED_MSG.into());
} }
let filename = self.next_wallet_filename()?; w.create_wallet(wallet::DEFAULT_WALLET_FILENAME, password)
let seed = w
.create_wallet(&filename, password)
.await .await
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())
let record = self
.record_wallet(&filename)
.map_err(|e| format!("wallet {filename} created but not remembered: {e}"))?;
self.point_child_at(&filename).map_err(|e| {
format!("wallet {filename} created but the child is not pointed at it: {e}")
})?;
Ok(CreatedWallet { record, seed })
} }
/// Re-read the seed of the wallet file the child has open. `create_wallet` /// Re-read the seed of the wallet file the child has open. `create_wallet`
@ -1233,108 +1192,14 @@ impl Node {
} }
/// Import a wallet from an existing 25-word seed. This is the only path /// Import a wallet from an existing 25-word seed. This is the only path
/// that takes a user-supplied secret — and, like a create, it is remembered /// that takes a user-supplied secret.
/// in the catalogue under its own file name. pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<(), String> {
pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<WalletRecord, String> {
let w = self.wallet_snapshot(); let w = self.wallet_snapshot();
if !w.configured() { if !w.configured() {
return Err(wallet::NOT_CONFIGURED_MSG.into()); return Err(wallet::NOT_CONFIGURED_MSG.into());
} }
let filename = self.next_wallet_filename()?; w.restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed)
w.restore_wallet(&filename, password, seed)
.await .await
.map_err(|e| e.to_string())?;
let record = self
.record_wallet(&filename)
.map_err(|e| format!("wallet {filename} imported but not remembered: {e}"))?;
self.point_child_at(&filename).map_err(|e| {
format!("wallet {filename} imported but the child is not pointed at it: {e}")
})?;
Ok(record)
}
/// Every wallet this install remembers, oldest first. A store read: it must
/// work with no wallet RPC configured, and it never dials.
pub fn list_wallets(&self) -> Result<Vec<WalletRecord>, String> {
self.store
.lock()
.map_err(|e| e.to_string())?
.list_wallets()
.map_err(|e| e.to_string())
}
/// Switch the wallet child to a catalogue wallet's file.
///
/// 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.
pub fn open_wallet(&self, filename: &str) -> Result<(), String> {
if !self
.list_wallets()?
.iter()
.any(|w| w.wallet_filename == 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());
if running {
self.stop_wallet_child()?;
}
self.point_child_at(filename)?;
if running {
self.start_wallet_child()?;
}
Ok(())
}
/// 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.
fn next_wallet_filename(&self) -> Result<String, String> {
let taken = self.list_wallets()?;
for n in 1.. {
let candidate = format!("{}-{}", wallet::DEFAULT_WALLET_FILENAME, n);
if !taken.iter().any(|w| w.wallet_filename == candidate) {
return Ok(candidate);
}
}
unreachable!("an unused wallet file name always exists")
}
/// Point the wallet child at a wallet file. A read-modify-write of the
/// sealed record, so the generated RPC creds and every other setting are
/// kept. A running child is not restarted: the change applies on the next
/// `start_wallet_child`.
fn point_child_at(&self, filename: &str) -> Result<(), String> {
let mut cfg = self.wallet_child_config();
if cfg.wallet_filename == filename {
return Ok(());
}
cfg.wallet_filename = filename.to_string();
self.set_wallet_child_config(&cfg)
}
/// Add a freshly created wallet file to the catalogue: this node's identity
/// (several wallets may share one) and the onion it is reachable at right
/// now (a locator, and empty until the HS publishes).
fn record_wallet(&self, filename: &str) -> Result<WalletRecord, String> {
let new = NewWallet {
name: None,
identity_pubkey: self.identity_pk(),
onion_locator: self.onion(),
wallet_filename: filename.to_string(),
};
self.store
.lock()
.map_err(|e| e.to_string())?
.create_wallet(&new)
.map_err(|e| e.to_string()) .map_err(|e| e.to_string())
} }
@ -2033,42 +1898,7 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool {
} }
#[cfg(test)] #[cfg(test)]
/// A catalogue row written straight into the store, for tests that need a saved mod tests {
/// wallet without a wallet RPC.
pub(crate) fn test_record_wallet(store: &Store, file: &str, label: &str) {
let identity_pubkey: [u8; 32] = store
.self_identity()
.expect("self identity")
.identity_pk
.try_into()
.expect("32-byte identity");
store
.create_wallet(&NewWallet {
name: (!label.trim().is_empty()).then(|| label.to_string()),
identity_pubkey,
onion_locator: format!("{file}.onion"),
wallet_filename: file.to_string(),
})
.expect("create wallet");
}
/// A real `Node` with no Tor and a seeded wallet catalogue, for the TUI's own
/// tests: `App` reads the catalogue, and the only public `Node` constructor
/// bootstraps Tor. `wallets` is `(file name, label)` — a blank label is stored
/// as `NULL`, like a wallet created without one.
#[cfg(test)]
pub(crate) fn test_node_with_wallets(home: &Path, wallets: &[(&str, &str)]) -> Arc<Node> {
{
let store = Store::open_at_with_passphrase(home, tests::PASS).expect("open store");
for (file, label) in wallets {
test_record_wallet(&store, file, label);
}
}
Arc::new(tests::offline_node(home, Arc::new(tests::NoDial)))
}
#[cfg(test)]
pub(crate) mod tests {
use super::*; use super::*;
use crate::wallet_child::DEFAULT_MONEROD_RPC_PORT; use crate::wallet_child::DEFAULT_MONEROD_RPC_PORT;
use std::pin::Pin; use std::pin::Pin;
@ -2080,11 +1910,11 @@ pub(crate) mod tests {
use tokio::io::AsyncRead as TokioRead; use tokio::io::AsyncRead as TokioRead;
use tokio::io::AsyncWrite as TokioWrite; use tokio::io::AsyncWrite as TokioWrite;
pub(crate) const PASS: &str = "node-ratchet-test-pass"; const PASS: &str = "node-ratchet-test-pass";
/// Never dials: every send queues, which is what leaves the encoded frame /// Never dials: every send queues, which is what leaves the encoded frame
/// visible on the outbox row. /// visible on the outbox row.
pub(crate) struct NoDial; struct NoDial;
impl crate::outbox::Deliverer for NoDial { impl crate::outbox::Deliverer for NoDial {
fn deliver<'a>( fn deliver<'a>(
@ -2141,7 +1971,7 @@ pub(crate) mod tests {
/// are the only public constructors and both bootstrap Tor and publish an /// are the only public constructors and both bootstrap Tor and publish an
/// onion service, so this is the only way to drive the shipped send and /// onion service, so this is the only way to drive the shipped send and
/// receive path offline. /// receive path offline.
pub(crate) fn offline_node(home: &Path, deliverer: Arc<dyn crate::outbox::Deliverer>) -> Node { fn offline_node(home: &Path, deliverer: Arc<dyn crate::outbox::Deliverer>) -> Node {
offline_node_with_wallet(home, deliverer, Wallet::disabled()) offline_node_with_wallet(home, deliverer, Wallet::disabled())
} }
@ -3146,232 +2976,4 @@ pub(crate) mod tests {
} }
assert!(gone, "shutdown must not leave the wallet child behind"); assert!(gone, "shutdown must not leave the wallet child behind");
} }
/// A loopback wallet RPC for the setup path: a per-socket digest challenge,
/// then the method's own result. `create_wallet` and
/// `restore_deterministic_wallet` both answer `{}`; only the seed backup
/// query has a body worth reading.
async fn mock_wallet_setup() -> Wallet {
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("query_key") {
r#"{"jsonrpc":"2.0","id":"0","result":{"key":"lumber tacit lemon ivory risk"}}"#
.to_string()
} else {
r#"{"jsonrpc":"2.0","id":"0","result":{}}"#.to_string()
}
});
tokio::spawn(serve_mock_rpc(listener, reply));
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
}
/// The reported bug: a created wallet was never remembered, because the
/// creation path never reached the store's catalogue.
#[tokio::test]
async fn creating_a_wallet_records_it_in_the_catalogue() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("bob");
let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await);
let created = node.wallet_create("hunter2").await.expect("create wallet");
assert!(created.record.id > 0, "the store assigns the row id");
assert_eq!(created.record.wallet_filename, "onionwire-1");
assert_eq!(created.record.identity_pubkey, node.identity_pk());
assert_eq!(created.record.onion_locator, "test.onion");
assert_eq!(created.seed, "lumber tacit lemon ivory risk");
assert_eq!(
node.list_wallets().expect("list wallets"),
vec![created.record],
"the wallet just created is the catalogue"
);
}
/// The second half of the bug: a second create reused the one hardcoded file
/// name, so the RPC refused it — and nothing was remembered across a restart.
#[tokio::test]
async fn a_second_wallet_gets_its_own_file_and_both_survive_a_reopen() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("bob");
let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await);
let first = node.wallet_create("p1").await.expect("first wallet");
let second = node.wallet_create("p1").await.expect("second wallet");
assert_ne!(
first.record.wallet_filename, second.record.wallet_filename,
"a second wallet must not reuse the first one's file"
);
drop(node);
let reopened = Store::open_at_with_passphrase(&home, PASS).expect("reopen store");
assert_eq!(
reopened.list_wallets().expect("list wallets").len(),
2,
"both wallets are remembered across a restart"
);
}
/// Import is a creation path too: it takes the same hardcoded name today.
#[tokio::test]
async fn importing_a_wallet_records_it_in_the_catalogue() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node_with_wallet(
&dir.path().join("bob"),
Arc::new(NoDial),
mock_wallet_setup().await,
);
let imported = node
.wallet_restore("hunter2", "lumber tacit lemon ivory risk")
.await
.expect("restore wallet");
assert_eq!(imported.wallet_filename, "onionwire-1");
assert_eq!(
node.list_wallets().expect("list wallets").len(),
1,
"an imported wallet is remembered too"
);
}
/// A catalogue row the child never opens is still a broken wallet: the
/// child's stored config defaults to `onionwire`, which no created wallet
/// uses any more.
#[tokio::test]
async fn creating_a_wallet_points_the_child_at_its_own_file() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node_with_wallet(
&dir.path().join("bob"),
Arc::new(NoDial),
mock_wallet_setup().await,
);
let first = node.wallet_create("p1").await.expect("first wallet");
assert_eq!(
node.wallet_child_config().wallet_filename,
first.record.wallet_filename,
"the child must open the wallet that was just created"
);
let second = node.wallet_create("p1").await.expect("second wallet");
assert_eq!(
node.wallet_child_config().wallet_filename,
second.record.wallet_filename
);
assert_eq!(
node.list_wallets().expect("list wallets")[0].wallet_filename,
first.record.wallet_filename,
"the first wallet keeps its own file"
);
}
/// The catalogue is a store fact, not a wallet-RPC fact: listing must work
/// with no wallet configured, and creating must still refuse without one.
#[tokio::test]
async fn a_wallet_off_install_lists_an_empty_catalogue() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
assert!(node.list_wallets().expect("list wallets").is_empty());
let err = node
.wallet_create("hunter2")
.await
.expect_err("no wallet RPC");
assert!(err.contains("ONIONWIRE_WALLET_RPC"), "{err}");
}
/// Switching wallets is a catalogue read plus a child re-point: the chosen
/// row's file name is what the child opens, and the generated RPC creds in
/// the same sealed record survive the read-modify-write.
#[tokio::test]
async fn open_wallet_points_the_child_at_the_chosen_file_and_keeps_the_creds() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("bob");
let node = offline_node(&home, Arc::new(NoDial));
{
let store = node.store.lock().unwrap();
store
.save_wallet_child(
r#"{"user":"owuser","pass":"ow-secret-pass-xyz","wallet_filename":"onionwire"}"#,
)
.unwrap();
for file in ["onionwire", "onionwire-1"] {
store
.create_wallet(&NewWallet {
name: None,
identity_pubkey: [7u8; 32],
onion_locator: "abcd.onion".into(),
wallet_filename: file.to_string(),
})
.unwrap();
}
}
node.open_wallet("onionwire-1")
.expect("open a saved wallet");
assert_eq!(
node.wallet_child_config().wallet_filename,
"onionwire-1",
"the child must open the wallet that was chosen"
);
let sealed = node
.store
.lock()
.unwrap()
.load_wallet_child()
.unwrap()
.expect("sealed record");
assert!(
sealed.contains("ow-secret-pass-xyz"),
"the re-point dropped the generated creds: {sealed}"
);
assert!(
sealed.contains("\"user\":\"owuser\""),
"the re-point dropped the generated creds: {sealed}"
);
// A restart re-reads the record, so the choice is remembered.
drop(node);
let restarted = offline_node(&home, Arc::new(NoDial));
assert_eq!(
restarted.wallet_child_config().wallet_filename,
"onionwire-1",
"the chosen wallet must survive a restart"
);
}
/// The catalogue is the only directory the app has, so a file it does not
/// hold is refused instead of pointing a spend-capable child at a path.
#[tokio::test]
async fn open_wallet_refuses_a_file_the_catalogue_does_not_hold() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
{
let store = node.store.lock().unwrap();
store
.save_wallet_child(r#"{"user":"owuser","pass":"p","wallet_filename":"onionwire"}"#)
.unwrap();
store
.create_wallet(&NewWallet {
name: None,
identity_pubkey: [7u8; 32],
onion_locator: String::new(),
wallet_filename: "onionwire".to_string(),
})
.unwrap();
}
let err = node
.open_wallet("onionwire-9")
.expect_err("not a saved wallet");
assert!(err.contains("no saved wallet"), "{err}");
assert_eq!(
node.wallet_child_config().wallet_filename,
"onionwire",
"a refused switch must leave the child where it was"
);
}
} }

View file

@ -17,9 +17,7 @@ use crate::node::Node;
use crate::outbox::DEFAULT_MAX_ATTEMPTS; use crate::outbox::DEFAULT_MAX_ATTEMPTS;
use crate::qr::{self, QrPayload}; use crate::qr::{self, QrPayload};
use crate::sanitize; use crate::sanitize;
use crate::store::{ use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment};
Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment, WalletRecord,
};
use crate::wallet::{self, ChainNetwork, ChainSource}; use crate::wallet::{self, ChainNetwork, ChainSource};
const C_ACCENT: Color = Color::Rgb(232, 165, 75); const C_ACCENT: Color = Color::Rgb(232, 165, 75);
@ -1350,27 +1348,12 @@ fn function_key_for(screen: &Screen, code: KeyCode) -> Option<FunctionKey> {
impl App { impl App {
fn new(node: Arc<Node>, rt: tokio::runtime::Handle) -> Result<Self, String> { fn new(node: Arc<Node>, rt: tokio::runtime::Handle) -> Result<Self, String> {
let friends = node.list_friends()?; let friends = node.list_friends()?;
// First run is the create flow, not an empty list to pick from; an
// install that already has wallets starts on the list, so a restart
// lands on the wallets it remembers. A catalogue that cannot be read is
// the screen's own error state (the create row still works there).
let screen = match node.list_wallets() {
Ok(rows) if rows.is_empty() => Screen::WalletSetup(WalletSetup::CreateWarn {
typed: String::new(),
}),
Ok(rows) => Screen::WalletSelect {
state: WalletSelectState::from_rows(wallet_rows(rows)),
},
Err(e) => Screen::WalletSelect {
state: WalletSelectState::error(e),
},
};
Ok(Self { Ok(Self {
me_fp: to_hex(&node.identity_pk()), me_fp: to_hex(&node.identity_pk()),
me_onion: node.onion(), me_onion: node.onion(),
node, node,
rt, rt,
screen, screen: Screen::Main,
friends, friends,
selected: 0, selected: 0,
alert: None, alert: None,
@ -2090,14 +2073,14 @@ impl App {
} }
/// Enter on the wallet selection screen: `create new wallet` starts the /// Enter on the wallet selection screen: `create new wallet` starts the
/// existing creation flow, and a wallet row switches the wallet child to /// existing creation flow, and a wallet row is a choice the app has to
/// that row's file. /// resolve.
/// ///
/// `WalletChoice::Open` carries a **row index**, so it is resolved against /// Resolving a row into the session is the wallet-store integration step:
/// the catalogue as it is now, not against anything the screen cached: two /// the record's identity and locator have to be read back and loaded, and
/// saved wallets may share an identity key, and only the position (then the /// `Node` has no wallet-record accessor yet. Until that lands the choice is
/// row's own `wallet_filename`) names one. A list that changed under the /// reported instead of silently dropped — an Enter that does nothing is
/// screen is reported rather than silently opening the wrong wallet. /// worse than one that says what is missing.
fn choose_wallet(&mut self) -> Result<(), String> { fn choose_wallet(&mut self) -> Result<(), String> {
let Screen::WalletSelect { state } = &self.screen else { let Screen::WalletSelect { state } = &self.screen else {
return Ok(()); return Ok(());
@ -2108,52 +2091,24 @@ impl App {
typed: String::new(), typed: String::new(),
}); });
} }
WalletChoice::Open(index) => { WalletChoice::Open(_) => {
let opened = self.select_wallet(index); self.status_note = Some("wallet switching is not wired up yet".into());
match opened {
Ok(label) => {
self.status_note = Some(format!("opened wallet {label}"));
self.screen = Screen::Main;
}
Err(e) => self.alert = Some(e),
}
} }
} }
Ok(()) Ok(())
} }
/// Load the catalogue row at `index` into the session: point the wallet /// F6 `w`: the wallet selection screen.
/// child at that wallet's file (and restart it if it was running), then read
/// the list back so the screen never shows a stale catalogue.
/// ///
/// The stored identity and locator are not pushed into the session: they are /// The rows come from the wallet store; reading them is the integration
/// the identity/locator *at creation* (a locator rotates, and the identity is /// card's step (`Store::list_wallets`), and the render path never touches
/// the roster key this node already holds), so the live values keep coming /// the store. Until that accessor exists the screen opens on its
/// from the node. Returns the label to report. /// unavailable state, which says so — the `create new wallet` row at the
fn select_wallet(&mut self, index: usize) -> Result<String, String> { /// bottom works either way.
let row = self
.node
.list_wallets()?
.into_iter()
.nth(index)
.ok_or_else(|| "the saved wallets changed — reopen the list".to_string())?;
self.node.open_wallet(&row.wallet_filename)?;
Ok(wallet_label(&row))
}
/// F6 `w`: the wallet selection screen, read from the catalogue now.
///
/// The rows come from the wallet store ([`Node::list_wallets`]) at the
/// moment the screen opens — never cached from startup — so a wallet created
/// in this session shows up on the next look. A read that fails is the
/// screen's own error state, which is not the same word as "no saved
/// wallets": the `create new wallet` row stays reachable either way.
fn open_wallet_select(&mut self) { fn open_wallet_select(&mut self) {
let state = match self.node.list_wallets() { self.screen = Screen::WalletSelect {
Ok(records) => WalletSelectState::from_rows(wallet_rows(records)), state: WalletSelectState::error(SELECT_UNAVAILABLE.to_string()),
Err(e) => WalletSelectState::error(e),
}; };
self.screen = Screen::WalletSelect { state };
} }
/// `c` on the WALLETS & SETTINGS menu: copy the receive address through the /// `c` on the WALLETS & SETTINGS menu: copy the receive address through the
@ -2382,9 +2337,9 @@ impl App {
return Ok(()); return Ok(());
} }
match self.rt.block_on(self.node.wallet_create(pass.as_str())) { match self.rt.block_on(self.node.wallet_create(pass.as_str())) {
Ok(created) => { Ok(seed) => {
self.screen = Screen::WalletSetup(WalletSetup::CreateSeed { self.screen = Screen::WalletSetup(WalletSetup::CreateSeed {
seed: Zeroizing::new(created.seed), seed: Zeroizing::new(seed),
typed: String::new(), typed: String::new(),
}); });
} }
@ -2457,7 +2412,7 @@ impl App {
.block_on(self.node.wallet_restore(pass.as_str(), seed.as_str())); .block_on(self.node.wallet_restore(pass.as_str(), seed.as_str()));
seed.zeroize(); seed.zeroize();
match result { match result {
Ok(_) => { Ok(()) => {
self.status_note = Some("wallet imported".into()); self.status_note = Some("wallet imported".into());
return self.open_wallet(); return self.open_wallet();
} }
@ -4601,37 +4556,6 @@ impl WalletSelectState {
} }
} }
/// Catalogue rows, display-ready and in store order (oldest first).
///
/// The mapping is the one documented on [`WalletRow`]: a `NULL` label is the
/// empty string (the screen says `(unlabelled)`), the identity column is
/// `[u8; 32]` and is hex-encoded here, the locator passes through (empty until
/// the HS publishes), and `created_at` is unix seconds. `wallet_filename` is
/// not carried: it is not on the screen. The rows stay index-aligned with the
/// catalogue, which is how [`WalletChoice::Open`] resolves.
pub fn wallet_rows(records: Vec<WalletRecord>) -> Vec<WalletRow> {
records
.into_iter()
.map(|r| WalletRow {
name: r.name.unwrap_or_default(),
identity_pubkey: to_hex(&r.identity_pubkey),
onion_locator: r.onion_locator,
created_at: r.created_at,
})
.collect()
}
/// What to call a saved wallet in a status line: its label, or the file when it
/// has none (a blank label is stored as `NULL`).
fn wallet_label(r: &WalletRecord) -> String {
r.name
.as_deref()
.map(str::trim)
.filter(|n| !n.is_empty())
.unwrap_or(&r.wallet_filename)
.to_string()
}
/// Marker column in cells: `> ` when focused, ` ` otherwise. /// Marker column in cells: `> ` when focused, ` ` otherwise.
const WALLET_MARK_W: usize = 2; const WALLET_MARK_W: usize = 2;
/// Identity column in cells: an 8-character prefix plus the ellipsis — 11 /// Identity column in cells: an 8-character prefix plus the ellipsis — 11
@ -4999,6 +4923,11 @@ pub fn wallet_select_footer_hint() -> &'static str {
const WALLET_SELECT_FOOTER_HINT: &str = "Esc back j k select Enter open ? help"; const WALLET_SELECT_FOOTER_HINT: &str = "Esc back j k select Enter open ? help";
/// The sub-line the screen prints when the wallet store has not been wired into
/// the app yet (see [`WalletRow`]): the list is genuinely unreadable, which is
/// not the same state as "no saved wallets".
pub const SELECT_UNAVAILABLE: &str = "the wallet store is not wired up yet";
/// OSC 52 clipboard write for `text`: the terminal copies it, so no crate and /// OSC 52 clipboard write for `text`: the terminal copies it, so no crate and
/// no clipboard daemon are involved and it still works over SSH. A terminal /// no clipboard daemon are involved and it still works over SSH. A terminal
/// that does not implement OSC 52 ignores the sequence. /// that does not implement OSC 52 ignores the sequence.
@ -5404,169 +5333,3 @@ mod passphrase_buffer_tests {
); );
} }
} }
/// The wallet selection screen against a real store-backed node: the rows come
/// from the catalogue, a choice loads that wallet, and the start screen depends
/// on whether any wallet is remembered.
#[cfg(test)]
mod wallet_store_tests {
use super::*;
use crate::node::{test_node_with_wallets, test_record_wallet};
const PASS: &str = crate::node::tests::PASS;
/// A real node (no Tor) over a seeded catalogue, plus the runtime the app
/// holds a handle to. `wallets` is `(file name, label)`; a blank label is a
/// wallet with no name, like one created from the app.
fn app(home: &std::path::Path, wallets: &[(&str, &str)]) -> (App, tokio::runtime::Runtime) {
let rt = tokio::runtime::Runtime::new().expect("tokio runtime");
// The offline node's unbootstrapped Arti client needs a runtime context
// to be built (the same reason the node tests are `#[tokio::test]`).
let _guard = rt.enter();
let node = test_node_with_wallets(home, wallets);
let app = App::new(node, rt.handle().clone()).expect("app");
(app, rt)
}
fn select_rows(app: &App) -> Vec<String> {
let Screen::WalletSelect { state } = &app.screen else {
panic!("not on the wallet selection screen");
};
state
.rows
.iter()
.map(|r| r.name.clone())
.collect::<Vec<_>>()
}
/// Nothing remembered means there is no list to choose from: the first run
/// goes straight to the existing creation flow.
#[test]
fn an_install_with_no_wallet_starts_on_the_create_flow() {
let dir = tempfile::tempdir().unwrap();
let (app, _rt) = app(&dir.path().join("home"), &[]);
assert!(
matches!(
app.screen,
Screen::WalletSetup(WalletSetup::CreateWarn { .. })
),
"a first run must start on the create flow"
);
}
/// A restart lands on the wallets it remembers, and each row carries the
/// catalogue's own fields (label, hex identity, locator, creation time).
#[test]
fn an_install_with_wallets_starts_on_the_list_read_from_the_catalogue() {
let dir = tempfile::tempdir().unwrap();
let (app, _rt) = app(
&dir.path().join("home"),
&[("onionwire", "lance"), ("onionwire-1", "")],
);
let Screen::WalletSelect { state } = &app.screen else {
panic!("saved wallets must start on the selection screen");
};
assert!(state.error.is_none(), "{:?}", state.error);
assert!(!state.reading);
assert_eq!(
state.rows.len(),
2,
"two saved wallets, plus the create row"
);
assert_eq!(state.rows[0].name, "lance");
assert_eq!(state.rows[1].name, "");
assert_eq!(
state.rows[0].identity_pubkey,
to_hex(&app.node.identity_pk())
);
assert_eq!(state.rows[0].identity_pubkey.len(), 64, "hex, not bytes");
assert_eq!(state.rows[0].onion_locator, "onionwire.onion");
assert!(state.rows[0].created_at > 0, "creation time is real");
assert_eq!(state.choice(), WalletChoice::Open(0));
}
/// The choice is a row index into a list whose records may share an
/// identity key, so the second row must open the second wallet's file.
#[test]
fn choosing_a_row_opens_that_wallets_file_not_the_first_identity_match() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(
&dir.path().join("home"),
&[("onionwire", "lance"), ("onionwire-1", "cold")],
);
{
let Screen::WalletSelect { state } = &mut app.screen else {
panic!("not on the selection screen");
};
state.select_next();
assert_eq!(state.choice(), WalletChoice::Open(1));
}
app.choose_wallet().expect("choosing a saved wallet");
assert!(
matches!(app.screen, Screen::Main),
"a loaded wallet returns to the main view"
);
assert_eq!(
app.node.wallet_child_config().wallet_filename,
"onionwire-1",
"the child must open the wallet under the marker"
);
assert_eq!(app.status_note.as_deref(), Some("opened wallet cold"));
}
/// The last item is not a wallet: Enter on it starts the creation flow.
#[test]
fn the_create_row_starts_the_creation_flow() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"), &[("onionwire", "lance")]);
{
let Screen::WalletSelect { state } = &mut app.screen else {
panic!("not on the selection screen");
};
state.select_next();
assert_eq!(state.choice(), WalletChoice::Create);
}
app.choose_wallet().expect("choosing create");
assert!(matches!(
app.screen,
Screen::WalletSetup(WalletSetup::CreateWarn { .. })
));
}
/// The list is read when the screen opens, never cached from startup, so a
/// wallet recorded in this session is offered the next time — that is what
/// makes a create show up without a restart.
#[test]
fn a_wallet_recorded_after_startup_appears_the_next_time_the_list_opens() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("home");
let (mut app, _rt) = app(&home, &[]);
assert!(matches!(app.screen, Screen::WalletSetup(_)));
assert!(
app.node.list_wallets().expect("list wallets").is_empty(),
"nothing to list yet"
);
{
// The create path writes exactly this row (a `wallets` entry keyed
// on the file it just made).
let store =
crate::store::Store::open_at_with_passphrase(&home, PASS).expect("open store");
test_record_wallet(&store, "onionwire-1", "fresh");
}
// F6 `w`.
app.open_wallet_select();
assert_eq!(select_rows(&app), vec!["fresh".to_string()]);
// And switching to it works from the screen the user is looking at.
app.choose_wallet().expect("open the new wallet");
assert_eq!(
app.node.wallet_child_config().wallet_filename,
"onionwire-1"
);
assert_eq!(app.status_note.as_deref(), Some("opened wallet fresh"));
}
}