node: remember a created wallet in the store's catalogue
A wallet created in-app was never remembered: `Node::wallet_create` called
the RPC and returned the seed, and the wallet file name was the one
hardcoded `wallet::DEFAULT_WALLET_FILENAME` ("onionwire"). A second create
reused that name, so the RPC refused it (or opened the first wallet's
file) and no row was ever written — the "cannot create a new wallet, and
nothing survives a restart" report.
Creation and import now go through the catalogue (t_64c9ba3c's
`Store::{create_wallet,list_wallets}`):
- each create/import gets its own file name, `onionwire-<n>` for the first
`n` the catalogue does not hold, so several wallets coexist;
- the stored row (id, identity, locator, file, created_at) is returned:
`Node::wallet_create` -> `CreatedWallet` (row + the one-time seed, with a
redacting `Debug`), `Node::wallet_restore` -> `WalletRecord`;
- `Node::list_wallets` reads the catalogue without dialing;
- the child config is re-pointed at the new file (read-modify-write, so the
sealed RPC creds survive) — a row the child never opens would still be a
broken wallet.
The SDK keeps its UniFFI signature (`create_wallet -> String` seed,
`import_wallet -> ()`), so no Kotlin change: it unwraps `.seed`.
TDD: 5 new `src/node.rs` cases (row + list, two wallets + reopen, import,
wallet-off empty list, child re-pointed) over a loopback wallet-RPC mock.
`cargo test --locked` exit 0, `cargo clippy --locked --all-targets -- -D
warnings` clean, and the same two commands are clean in
`crates/onionwire-sdk`.
This commit is contained in:
parent
467510f096
commit
0043fa0b34
3 changed files with 262 additions and 15 deletions
|
|
@ -587,20 +587,27 @@ impl Wire {
|
|||
/// 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.
|
||||
/// 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> {
|
||||
self.node()?
|
||||
Ok(self
|
||||
.node()?
|
||||
.wallet_create(&password)
|
||||
.await
|
||||
.map_err(WireError::new)
|
||||
.map_err(WireError::new)?
|
||||
.seed)
|
||||
}
|
||||
|
||||
/// Import a wallet from an existing 25-word seed. This is the only path
|
||||
/// that takes a user-supplied secret.
|
||||
/// that takes a user-supplied secret. Like a create, the core records the
|
||||
/// imported wallet in its catalogue.
|
||||
pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> {
|
||||
self.node()?
|
||||
.wallet_restore(&password, &seed)
|
||||
.await
|
||||
.map_err(WireError::new)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
/// Start the app-owned wallet child (`monero-wallet-rpc`, plus `monerod` for
|
||||
|
|
|
|||
258
src/node.rs
258
src/node.rs
|
|
@ -28,7 +28,9 @@ use crate::ratchet::{RatchetKeyPair, RatchetState};
|
|||
use crate::ratelimit::TokenBucket;
|
||||
use crate::sanitize;
|
||||
use crate::session::{self, Keys};
|
||||
use crate::store::{Friend, FriendProfile, Message, Payment, PaymentWrite, Store};
|
||||
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};
|
||||
|
||||
|
|
@ -80,6 +82,29 @@ 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 {
|
||||
home: PathBuf,
|
||||
store: Arc<Mutex<Store>>,
|
||||
|
|
@ -1167,27 +1192,106 @@ impl Node {
|
|||
Ok(rows.into_iter().take(cap).collect())
|
||||
}
|
||||
|
||||
/// Create a new spend-capable wallet. Returns the seed once for backup.
|
||||
/// The user never pastes a key on this path.
|
||||
pub async fn wallet_create(&self, password: &str) -> Result<String, String> {
|
||||
/// Create a new spend-capable wallet and record it in the catalogue. The
|
||||
/// user never pastes a key on this path.
|
||||
///
|
||||
/// 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();
|
||||
if !w.configured() {
|
||||
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
||||
}
|
||||
w.create_wallet(wallet::DEFAULT_WALLET_FILENAME, password)
|
||||
let filename = self.next_wallet_filename()?;
|
||||
let seed = w
|
||||
.create_wallet(&filename, password)
|
||||
.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 })
|
||||
}
|
||||
|
||||
/// Import a wallet from an existing 25-word seed. This is the only path
|
||||
/// that takes a user-supplied secret.
|
||||
pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<(), String> {
|
||||
/// that takes a user-supplied secret — and, like a create, it is remembered
|
||||
/// in the catalogue under its own file name.
|
||||
pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<WalletRecord, String> {
|
||||
let w = self.wallet_snapshot();
|
||||
if !w.configured() {
|
||||
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
||||
}
|
||||
w.restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed)
|
||||
let filename = self.next_wallet_filename()?;
|
||||
w.restore_wallet(&filename, password, seed)
|
||||
.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())
|
||||
}
|
||||
|
||||
/// 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())
|
||||
}
|
||||
|
||||
|
|
@ -2964,4 +3068,140 @@ mod tests {
|
|||
}
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2263,9 +2263,9 @@ impl App {
|
|||
return Ok(());
|
||||
}
|
||||
match self.rt.block_on(self.node.wallet_create(pass.as_str())) {
|
||||
Ok(seed) => {
|
||||
Ok(created) => {
|
||||
self.screen = Screen::WalletSetup(WalletSetup::CreateSeed {
|
||||
seed: Zeroizing::new(seed),
|
||||
seed: Zeroizing::new(created.seed),
|
||||
typed: String::new(),
|
||||
});
|
||||
}
|
||||
|
|
@ -2338,7 +2338,7 @@ impl App {
|
|||
.block_on(self.node.wallet_restore(pass.as_str(), seed.as_str()));
|
||||
seed.zeroize();
|
||||
match result {
|
||||
Ok(()) => {
|
||||
Ok(_) => {
|
||||
self.status_note = Some("wallet imported".into());
|
||||
return self.open_wallet();
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue