sdk: expose the wallet catalogue, the open wallet's keys, and the self profile
Some checks failed
ci / test (pull_request) Successful in 5m59s
ci / sdk (pull_request) Successful in 1m35s
android-ci / android (pull_request) Successful in 12m42s
ci / fuzz (pull_request) Has been cancelled

The Android wallet/profile screens had nothing to call: the core could list
wallets, switch the child onto one, read its keys and read/write the self
profile, but none of it crossed UniFFI.

Core:
- Wallet::keys() -> WalletKeys { view_key, spend_key: Option<String> }: two
  query_key calls against the file the RPC has open. A view-only wallet's -29
  is spend_key: None, not an error. WalletKeys' Debug redacts both halves.
- Node::wallet_keys() mirrors wallet_create/wallet_seed; refuses locally when
  no wallet is configured.
- Node::active_wallet_filename() -> Option<String>: the file the child is
  pointed at, None until wallet-child settings exist, so a client can mark the
  open row.

SDK (UniFFI):
- records WalletRow / WalletKeys / SelfProfile, and Wire::{wallets,
  open_wallet, active_wallet_filename, wallet_keys, self_profile,
  set_self_profile, push_self_profile}.
- The rule the clients must express is in the docs: the seed and the private
  keys come from the OPEN wallet, so there is deliberately no accessor that
  reads another saved wallet's secrets without opening it.

docs/WALLET.md (catalogue + 'secrets belong to the open wallet'),
docs/THREAT_MODEL.md (the new on-demand-display exposure surface) and the SDK
README are updated in the same commit.
This commit is contained in:
sirius 2026-09-22 00:25:33 -04:00
commit 5f19a56be3
No known key found for this signature in database
7 changed files with 784 additions and 3 deletions

View file

@ -28,14 +28,14 @@
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use onionwire::Message;
use onionwire::hs::TorState as CoreTorState;
use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node};
use onionwire::outbox::{DEFAULT_MAX_ATTEMPTS, OutboxEntry, OutboxStatus};
use onionwire::pay;
use onionwire::qr;
use onionwire::wallet::{ChainNetwork, ChainSource};
use onionwire::wallet::{ChainNetwork, ChainSource, WalletKeys as CoreWalletKeys};
use onionwire::wallet_child::{ChildConfig, WalletChildState};
use onionwire::{FriendProfile, Message, WalletRecord};
uniffi::setup_scaffolding!();
@ -540,6 +540,128 @@ impl Wire {
.collect())
}
// ---- Wallet catalogue, the open wallet, and its secrets ----
/// Every wallet this install remembers, oldest first.
///
/// A store read: it never dials the wallet RPC or the chain, so it works
/// with the wallet child stopped or never configured. "No wallets" is an
/// empty list, never an error. `WireError.Stopped` after `shutdown`;
/// `WireError.Failed` only when the store itself cannot be read.
///
/// The Kotlin binding is `Wire.wallets()`.
pub async fn wallets(&self) -> WResult<Vec<WalletRow>> {
let rows = self.node()?.list_wallets().map_err(WireError::new)?;
Ok(rows.iter().map(wallet_row).collect())
}
/// Point the wallet child at a catalogue wallet's file: afterwards the
/// balance, transfers, seed and keys this surface reports are that
/// wallet's.
///
/// **It may restart a running wallet child.** A live child is stopped and
/// started again onto the new file, which is what makes the change take
/// effect immediately — and why this call is slow (a `.onion` source waits
/// for its SOCKS listener, an in-process chain daemon for its RPC). An idle
/// child is only re-pointed: nothing is spawned, and the change applies at
/// the next [`Wire::start_wallet_child`].
///
/// A `filename` the catalogue does not hold is **refused**: the catalogue is
/// the only directory this app keeps wallets in, and a spend-capable child
/// is never pointed at a path a caller invented. Get the name from
/// [`Wire::wallets`]. `WireError.Stopped` after `shutdown`.
pub async fn open_wallet(&self, filename: String) -> WResult<()> {
self.node()?.open_wallet(&filename).map_err(WireError::new)
}
/// The wallet file the child is currently pointed at, or `None` when no
/// wallet-child settings were ever stored (a fresh install has no open
/// wallet).
///
/// A picker marks the open row with
/// `row.wallet_filename == active`; every other row means "open it first to
/// see its seed or keys", because the seed and the private keys always come
/// from the file the child has **open**. The value can name a file that is
/// not in the catalogue (an install whose wallet predates it) — that is "no
/// open wallet row", not an error.
///
/// It never dials and never spawns. `WireError.Stopped` after `shutdown`.
pub async fn active_wallet_filename(&self) -> WResult<Option<String>> {
self.node()?
.active_wallet_filename()
.map_err(WireError::new)
}
/// The private view key and spend key of the wallet file the child has
/// **open** (`query_key`). This is a dial to the wallet child's loopback
/// RPC, so call it from an explicit user action, not from a refresh loop.
///
/// `spend_key` is `None` for a view-only wallet: the RPC answers `-29`
/// ("Cannot retrieve spend key") and that is the wallet's own answer, not a
/// failure, so it is not surfaced as one. `WireError.Failed` when no wallet
/// is configured or the child is not answering; `WireError.Stopped` after
/// `shutdown`.
///
/// The values are spend secrets: show them, never log them, never persist
/// them. `WalletKeys`'s `Debug` redacts both.
pub async fn wallet_keys(&self) -> WResult<WalletKeys> {
let keys = self.node()?.wallet_keys().await.map_err(WireError::new)?;
Ok(keys_record(keys))
}
// ---- This identity's own profile ----
/// This identity's own profile (nickname, bio, Monero address) as stored.
///
/// A store read: never dials. It is the local copy — what friends show for
/// you only changes once [`Wire::push_self_profile`] reaches them.
/// `WireError.Stopped` after `shutdown`.
pub async fn self_profile(&self) -> WResult<SelfProfile> {
let p = self.node()?.self_profile().map_err(WireError::new)?;
Ok(self_profile_record(&p))
}
/// Replace this identity's own profile.
///
/// Validated before it is written, so a rejected edit leaves the stored
/// profile untouched: a nickname over 64 characters, a bio over 512, or a
/// non-empty address that fails the Monero checksum (the same check `/pay`
/// and `/tip` use) is refused with `WireError.Failed`. An empty address is
/// allowed.
///
/// It does not tell anyone. Friends still see the previous profile until
/// [`Wire::push_self_profile`] is sent to them. `WireError.Stopped` after
/// `shutdown`.
pub async fn set_self_profile(
&self,
display_name: String,
bio: String,
xmr_addr: String,
) -> WResult<()> {
self.node()?
.set_self_profile(&display_name, &bio, &xmr_addr)
.map_err(WireError::new)
}
/// Send this identity's signed profile to one friend, so the nickname and
/// address they show for you are current.
///
/// One-shot and fail closed: a peer whose onion is down means this fails
/// and **nothing is queued** — no retry, no outbox row (profiles are not
/// chat). Send it again when they are reachable.
///
/// `pubkey_hex` is the friend's identity pubkey, the encoding
/// [`FriendInfo::pubkey_hex`] carries; an unparseable hex is
/// `WireError.Failed` before anything is dialled. `WireError.Stopped` after
/// `shutdown`.
pub async fn push_self_profile(&self, pubkey_hex: String) -> WResult<()> {
let pk = unhex(&pubkey_hex)?;
self.node()?
.push_self_profile(&pk)
.await
.map_err(WireError::new)
}
/// Send an invoice to a friend: sign an invoice for my receive address and send
/// the frame one-shot. Peer onion down → this fails; invoices are not queued.
///
@ -1018,6 +1140,39 @@ fn outbox_row(entry: &OutboxEntry) -> OutboxRow {
}
}
/// `WalletRecord` → the picker row. `wallet_filename` is the file name only
/// (never a path): the core resolves it inside `$ONIONWIRE_HOME/wallet`.
fn wallet_row(w: &WalletRecord) -> WalletRow {
WalletRow {
id: w.id,
name: w.name.clone(),
wallet_filename: w.wallet_filename.clone(),
onion_locator: w.onion_locator.clone(),
identity_pubkey_hex: hex(&w.identity_pubkey),
created_at: w.created_at,
}
}
/// The core's key record → the SDK's, with the secrets carried across verbatim
/// (this is a display path; nothing here logs or stores them).
fn keys_record(keys: CoreWalletKeys) -> WalletKeys {
WalletKeys {
view_key: keys.view_key,
spend_key: keys.spend_key,
}
}
/// `FriendProfile` → the profile screen's record. `updated_at` is deliberately
/// not carried: the SDK surface has no use for it, and a client that wants
/// "did my push land" compares the fields it set.
fn self_profile_record(p: &FriendProfile) -> SelfProfile {
SelfProfile {
display_name: p.display_name.clone(),
bio: p.bio.clone(),
xmr_addr: p.xmr_addr.clone(),
}
}
/// A Monero transfer row for the wallet screen.
///
/// `amount` is formatted XMR (not raw piconero) — the SDK formats it from the
@ -1029,6 +1184,71 @@ pub struct TransferRow {
pub address: String,
}
/// One row of the saved-wallet catalogue, for the wallet picker.
///
/// Mirrors the core's `WalletRecord`, with the identity pubkey as hex. `id` is
/// the `wallets.id` row id, `wallet_filename` is the file inside
/// `$ONIONWIRE_HOME/wallet` and is what [`Wire::open_wallet`] takes, and the
/// rows come back oldest-first so a list is stable between calls.
///
/// `identity_pubkey_hex` is the identity this wallet belongs to and is **not**
/// unique; `onion_locator` is a locator that may be empty or stale. Never key a
/// selection, or the roster, on the locator.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct WalletRow {
pub id: i64,
/// The user's label for this wallet. `None` when it was never named, and
/// never an empty string.
pub name: Option<String>,
pub wallet_filename: String,
pub onion_locator: String,
/// The owning identity's ed25519 pubkey, hex — the same encoding
/// [`FriendInfo::pubkey_hex`] carries.
pub identity_pubkey_hex: String,
/// Unix seconds, assigned by the store when the row was created.
pub created_at: i64,
}
/// The private keys of the **open** wallet file, for a backup screen.
///
/// Both values are spend secrets: show them only from an explicit user action,
/// never log them, and never persist them. `Debug` is hand-written to redact
/// them so a stray `{:?}` cannot leak a key into a log.
#[derive(Clone, PartialEq, Eq, uniffi::Record)]
pub struct WalletKeys {
/// The open wallet file's private view key.
pub view_key: String,
/// The open wallet file's private spend key, or `None` for a view-only
/// wallet. `None` is the wallet's own answer — it has no spend key — and
/// not a failure.
pub spend_key: Option<String>,
}
/// Hand-written so a stray `{:?}` cannot print a private key.
impl std::fmt::Debug for WalletKeys {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WalletKeys")
.field("view_key", &"<redacted>")
.field("spend_key", &self.spend_key.as_ref().map(|_| "<redacted>"))
.finish()
}
}
/// This identity's own profile, as the profile screen reads and edits it.
///
/// It is what friends are shown for this identity once it has been pushed;
/// nothing here is secret (an empty `xmr_addr` is allowed, a non-empty one is
/// validated).
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct SelfProfile {
pub display_name: String,
pub bio: String,
/// This identity's Monero address. May be empty. When non-empty the core
/// refuses to store it unless it passes the same address check `/pay` and
/// `/tip` use.
pub xmr_addr: String,
}
/// Where the app-owned wallet child gets its chain from. Mirrors the core's
/// `ChainSource`: nothing is implied — `Remote` is a daemon the user supplied.
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
@ -1341,8 +1561,8 @@ mod tests {
//! handle, which is what a shut-down node must guarantee. A `Wire` with no
//! node is exactly the state `shutdown()` leaves behind.
use super::*;
use onionwire::Store;
use onionwire::outbox::OutboxStatus;
use onionwire::{NewWallet, Store};
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
@ -2105,4 +2325,163 @@ mod tests {
let err = block_on(stopped_wire().wallet_child_refresh()).expect_err("must fail");
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
}
// ---- wallet catalogue, the open wallet, its keys, and the self profile ----
#[test]
fn wallets_on_a_stopped_handle_is_stopped_error() {
let err = block_on(stopped_wire().wallets()).expect_err("must fail");
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
}
#[test]
fn open_wallet_on_a_stopped_handle_is_stopped_error() {
let err =
block_on(stopped_wire().open_wallet("onionwire".to_string())).expect_err("must fail");
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
}
#[test]
fn active_wallet_filename_on_a_stopped_handle_is_stopped_error() {
let err = block_on(stopped_wire().active_wallet_filename()).expect_err("must fail");
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
}
#[test]
fn wallet_keys_on_a_stopped_handle_is_stopped_error() {
let err = block_on(stopped_wire().wallet_keys()).expect_err("must fail");
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
}
#[test]
fn self_profile_on_a_stopped_handle_is_stopped_error() {
let err = block_on(stopped_wire().self_profile()).expect_err("must fail");
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
}
#[test]
fn set_self_profile_on_a_stopped_handle_is_stopped_error() {
let err = block_on(stopped_wire().set_self_profile(
"nick".to_string(),
String::new(),
String::new(),
))
.expect_err("must fail");
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
}
#[test]
fn push_self_profile_on_a_stopped_handle_is_stopped_error() {
// Valid 32-byte hex, so the hex parse cannot be the thing that failed:
// the handle is.
let err =
block_on(stopped_wire().push_self_profile("11".repeat(32))).expect_err("must fail");
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
}
#[test]
fn push_self_profile_rejects_a_pubkey_that_is_not_hex_before_any_work() {
let err =
block_on(stopped_wire().push_self_profile("nope".to_string())).expect_err("must fail");
// The hex check runs first, so this is `Failed`, not `Stopped`.
assert!(matches!(err, WireError::Failed { .. }), "got {err:?}");
}
/// The picker row is the catalogue row, row for row: same id, same file
/// name, same label, and the pubkey as hex. A Kotlin picker keys on
/// `wallet_filename` for [`Wire::open_wallet`], so it has to be exact.
#[test]
fn wallet_rows_carry_the_catalogue_verbatim() {
let home = temp_home();
let store = Store::open_at_with_passphrase(&home, "wallet-catalogue-pass").unwrap();
let named = store
.create_wallet(&NewWallet {
name: Some("savings".to_string()),
identity_pubkey: [0xab; 32],
onion_locator: "peer.onion".to_string(),
wallet_filename: "onionwire-1".to_string(),
})
.unwrap();
let unnamed = store
.create_wallet(&NewWallet {
name: None,
identity_pubkey: [0xab; 32],
onion_locator: String::new(),
wallet_filename: "onionwire-2".to_string(),
})
.unwrap();
let rows: Vec<WalletRow> = store
.list_wallets()
.unwrap()
.iter()
.map(wallet_row)
.collect();
assert_eq!(rows.len(), 2, "both wallets are listed");
assert_eq!(rows[0].id, named.id);
assert_eq!(rows[0].name.as_deref(), Some("savings"));
assert_eq!(rows[0].wallet_filename, "onionwire-1");
assert_eq!(rows[0].onion_locator, "peer.onion");
assert_eq!(rows[0].identity_pubkey_hex, "ab".repeat(32));
assert_eq!(rows[0].created_at, named.created_at);
// A wallet created without a label is `None`, never an empty string.
assert_eq!(rows[1].id, unnamed.id);
assert_eq!(rows[1].name, None);
// The locator is a locator: it may be empty, and it is not an identity.
assert_eq!(rows[1].onion_locator, "");
std::fs::remove_dir_all(&home).ok();
}
#[test]
fn keys_mapping_carries_both_halves_and_the_view_only_answer() {
let both = keys_record(CoreWalletKeys {
view_key: "view-material".to_string(),
spend_key: Some("spend-material".to_string()),
});
assert_eq!(both.view_key, "view-material");
assert_eq!(both.spend_key.as_deref(), Some("spend-material"));
let view_only = keys_record(CoreWalletKeys {
view_key: "view-material".to_string(),
spend_key: None,
});
assert_eq!(view_only.view_key, "view-material");
assert_eq!(view_only.spend_key, None);
}
/// These two are spend secrets: the record the Kotlin side receives must not
/// print them through `Debug`, or a `{:?}` in a crash log leaks a key.
#[test]
fn wallet_keys_debug_never_prints_a_private_key() {
let keys = keys_record(CoreWalletKeys {
view_key: "VIEWKEYMATERIAL".to_string(),
spend_key: Some("SPENDKEYMATERIAL".to_string()),
});
let printed = format!("{keys:?}");
assert!(
!printed.contains("VIEWKEYMATERIAL"),
"view key leaked: {printed}"
);
assert!(
!printed.contains("SPENDKEYMATERIAL"),
"spend key leaked: {printed}"
);
assert!(printed.contains("redacted"), "got {printed}");
}
#[test]
fn self_profile_mapping_carries_the_three_editable_fields() {
let core = FriendProfile {
display_name: "nick".to_string(),
bio: "bio".to_string(),
xmr_addr: String::new(),
updated_at: 1_700_000_000,
};
let got = self_profile_record(&core);
assert_eq!(got.display_name, "nick");
assert_eq!(got.bio, "bio");
assert_eq!(got.xmr_addr, "");
}
}