store: a wallet catalogue in the encrypted db (wallets table + CRUD) #141

Merged
sirius merged 1 commit from wt/t_64c9ba3c into main 2026-09-21 15:09:46 +00:00
3 changed files with 309 additions and 2 deletions
Showing only changes of commit 467510f096 - Show all commits

store: a wallet catalogue in the encrypted db
All checks were successful
ci / test (pull_request) Successful in 5m48s
ci / sdk (pull_request) Successful in 1m34s
android-ci / android (pull_request) Successful in 12m4s
ci / fuzz (pull_request) Successful in 18m24s

Wallets were only ever a file in $ONIONWIRE_HOME/wallet plus the
single-row wallet_child config for the one the child is currently
pointed at, so a created wallet was not remembered and a second create
had nowhere to go.

Add a 'wallets' table (id, name, identity_pubkey, onion_locator,
wallet_filename, created_at) and CRUD on Store: create_wallet,
get_wallet_by_id, list_wallets, delete_wallet. wallet_filename is
UNIQUE so a second wallet cannot silently reuse the first one's file,
and identity_pubkey is deliberately not unique (identity is the roster
key, a wallet is a file; the locator may rotate or be empty).

No new crate: the store is already rusqlite + SQLCipher with a raw
PRAGMA key, and sqlx has no SQLCipher path, so a second pool would be a
second unencrypted way in.

Tests: 5 store cases in tests/store.rs (round-trip, coexistence across
a reopen, duplicate filename, delete, blank label/filename) plus the
at_rest upgrade case in src/store.rs.
rust-dev (hermes) 2026-09-21 10:21:48 -04:00
No known key found for this signature in database

View file

@ -20,6 +20,6 @@ pub mod wallet;
pub mod wallet_child;
pub use store::{
Friend, FriendProfile, Message, Payment, PaymentWrite, SelfIdentity, Store,
resolve_store_passphrase,
Friend, FriendProfile, Message, NewWallet, Payment, PaymentWrite, SelfIdentity, Store,
WalletRecord, resolve_store_passphrase,
};

View file

@ -177,6 +177,34 @@ pub struct PaymentWrite<'a> {
pub verified: bool,
}
/// Fields the caller supplies to add a wallet to the catalogue. `id` and
/// `created_at` are assigned by the store, never by the caller.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NewWallet {
/// Optional user label. Blank (or whitespace) is stored as SQL NULL.
pub name: Option<String>,
/// The identity this wallet belongs to. Identity is the pubkey, so several
/// wallets may share one — this column is deliberately not unique.
pub identity_pubkey: [u8; 32],
/// The onion locator current at creation. A locator, not an identity: it
/// rotates (F4) and is allowed to be empty before the HS publishes.
pub onion_locator: String,
/// The wallet file name under the wallet dir. Unique: a second wallet must
/// get its own file rather than overwrite the first one's.
pub wallet_filename: String,
}
/// One wallet in the catalogue: the row that makes a wallet survive a restart.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalletRecord {
pub id: i64,
pub name: Option<String>,
pub identity_pubkey: [u8; 32],
pub onion_locator: String,
pub wallet_filename: String,
pub created_at: i64,
}
impl Store {
pub fn open() -> Result<Self> {
Self::open_at(&home_dir()?)
@ -275,6 +303,21 @@ impl Store {
no_spend INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
-- The wallet catalogue: one row per wallet file this install knows
-- about, so a created wallet is remembered across restarts (the
-- wallet child's own config only describes the one it is pointed at
-- right now). `identity_pubkey` is the owning identity and is NOT
-- unique — identity is the roster key, while a wallet is one file;
-- `onion_locator` is a locator and may be stale or empty.
CREATE TABLE IF NOT EXISTS wallets (
id INTEGER PRIMARY KEY,
name TEXT,
identity_pubkey BLOB NOT NULL,
onion_locator TEXT NOT NULL DEFAULT '',
wallet_filename TEXT NOT NULL UNIQUE,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS wallets_by_created ON wallets (created_at, id);
CREATE TABLE IF NOT EXISTS payments (
id INTEGER PRIMARY KEY,
friend_id INTEGER NOT NULL REFERENCES friends(id),
@ -418,6 +461,93 @@ impl Store {
}))
}
/// Add a wallet to the catalogue and return the stored row (id and
/// `created_at` assigned here). This is the only way a wallet becomes
/// remembered: the wallet file on disk is not a directory listing the app
/// scans.
///
/// `wallet_filename` is unique. Creating a second wallet is not a rewrite of
/// the first — it must be handed its own file name, otherwise both wallets
/// would open the same file and the second would look like a failed create.
pub fn create_wallet(&self, w: &NewWallet) -> Result<WalletRecord> {
let filename = w.wallet_filename.trim();
if filename.is_empty() {
return Err(Error("wallet filename required".into()));
}
let name = w.name.as_deref().map(str::trim).filter(|n| !n.is_empty());
let taken: Option<i64> = self
.conn
.query_row(
"SELECT id FROM wallets WHERE wallet_filename = ?1",
params![filename],
|row| row.get(0),
)
.optional()?;
if let Some(id) = taken {
return Err(Error(format!(
"wallet filename already in use: {filename} (wallet {id})"
)));
}
let created_at = unix_now();
self.conn.execute(
"INSERT INTO wallets (name, identity_pubkey, onion_locator, wallet_filename, created_at)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![
name,
w.identity_pubkey.as_slice(),
w.onion_locator,
filename,
created_at
],
)?;
Ok(WalletRecord {
id: self.conn.last_insert_rowid(),
name: name.map(str::to_string),
identity_pubkey: w.identity_pubkey,
onion_locator: w.onion_locator.clone(),
wallet_filename: filename.to_string(),
created_at,
})
}
/// One wallet by row id, or `None` when there is no such wallet.
pub fn get_wallet_by_id(&self, id: i64) -> Result<Option<WalletRecord>> {
Ok(self
.conn
.query_row(
"SELECT id, name, identity_pubkey, onion_locator, wallet_filename, created_at
FROM wallets WHERE id = ?1",
params![id],
wallet_row,
)
.optional()?)
}
/// Every known wallet, oldest first (row id breaks a `created_at` tie, so
/// the order a wallet-selection screen shows is stable across runs).
pub fn list_wallets(&self) -> Result<Vec<WalletRecord>> {
let mut stmt = self.conn.prepare(
"SELECT id, name, identity_pubkey, onion_locator, wallet_filename, created_at
FROM wallets ORDER BY created_at, id",
)?;
let rows = stmt
.query_map([], wallet_row)?
.collect::<std::result::Result<Vec<_>, _>>()?;
Ok(rows)
}
/// Forget a wallet. `true` when a row was removed, `false` when there was
/// nothing to remove (an unknown id is not an error).
///
/// This drops the catalogue row only; the wallet file on disk and the
/// payments already recorded stay where they are.
pub fn delete_wallet(&self, id: i64) -> Result<bool> {
let removed = self
.conn
.execute("DELETE FROM wallets WHERE id = ?1", params![id])?;
Ok(removed > 0)
}
pub fn replace_identity_keys(
&self,
identity_sk: &[u8],
@ -1651,6 +1781,31 @@ fn unix_now() -> i64 {
.unwrap_or(0)
}
/// Read one `wallets` row. A pubkey column that is not exactly 32 bytes is a
/// corrupt row, not a value to guess at.
fn wallet_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<WalletRecord> {
let pubkey: Vec<u8> = row.get(2)?;
let len = pubkey.len();
let identity_pubkey: [u8; 32] = pubkey.try_into().map_err(|_| {
rusqlite::Error::FromSqlConversionFailure(
2,
rusqlite::types::Type::Blob,
Box::new(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("identity_pubkey is {len} bytes, expected 32"),
)),
)
})?;
Ok(WalletRecord {
id: row.get(0)?,
name: row.get(1)?,
identity_pubkey,
onion_locator: row.get(3)?,
wallet_filename: row.get(4)?,
created_at: row.get(5)?,
})
}
/// AAD for the sealed wallet-child row. Domain-separates it from message and
/// outbox blobs that share the same store data key.
const WALLET_CHILD_AAD: &[u8] = b"onionwire/wallet-child/v1";
@ -2308,4 +2463,33 @@ mod at_rest {
}
}
}
/// An install that predates the `wallets` table (the Android upgrade path)
/// gains it on the next open, and keeps everything else it had: the schema
/// is additive (`CREATE TABLE IF NOT EXISTS` on every open).
#[test]
fn a_store_without_the_wallets_table_gains_it_on_reopen() {
let dir = tempfile::tempdir().unwrap();
let wallet = crate::store::NewWallet {
name: Some("First".into()),
identity_pubkey: [9u8; 32],
onion_locator: "w.onion".into(),
wallet_filename: "onionwire".into(),
};
{
let store = Store::open_at_with_passphrase(dir.path(), "upgrade-pass").unwrap();
let row = store.create_wallet(&wallet).unwrap();
assert_eq!(store.get_wallet_by_id(row.id).unwrap().unwrap(), row);
// Simulate a pre-`wallets` install.
store.conn.execute_batch("DROP TABLE wallets").unwrap();
}
let store = Store::open_at_with_passphrase(dir.path(), "upgrade-pass").unwrap();
assert!(
store.list_wallets().unwrap().is_empty(),
"the dropped table comes back empty, not missing"
);
let row = store.create_wallet(&wallet).unwrap();
assert_eq!(store.list_wallets().unwrap().len(), 1);
assert_eq!(store.get_wallet_by_id(row.id).unwrap().unwrap(), row);
}
}

View file

@ -540,3 +540,126 @@ fn ratchet_state_survives_reopening_the_store() {
assert_eq!(store.load_ratchet(&pk(1)).expect("load"), Some(blob));
assert_eq!(store.list_messages(&pk(1)).unwrap()[0].plaintext, b"hello");
}
// ---- the wallet catalogue (`wallets`) --------------------------------------
//
// Several wallet *files* live under one identity: the row here is what makes a
// wallet survive a restart, because the wallet child's own config only ever
// describes the one it is pointed at right now.
fn new_wallet(filename: &str, name: Option<&str>) -> onionwire::NewWallet {
onionwire::NewWallet {
name: name.map(str::to_string),
identity_pubkey: pk(7),
onion_locator: "walletloc.onion".to_string(),
wallet_filename: filename.to_string(),
}
}
#[test]
fn create_wallet_stores_every_field_and_reads_it_back() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open");
let row = store
.create_wallet(&new_wallet("savings", Some("Savings")))
.expect("create");
assert!(row.id > 0, "id assigned: {row:?}");
assert!(row.created_at > 0, "created_at stamped: {row:?}");
assert_eq!(row.wallet_filename, "savings");
assert_eq!(row.name.as_deref(), Some("Savings"));
assert_eq!(row.identity_pubkey, pk(7));
assert_eq!(row.onion_locator, "walletloc.onion");
let got = store
.get_wallet_by_id(row.id)
.expect("get")
.expect("row exists");
assert_eq!(got, row, "the stored row is what came back");
}
#[test]
fn multiple_wallets_coexist_and_survive_a_reopen() {
let dir = tempfile::tempdir().expect("tempdir");
let (spending, savings) = {
let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open");
let spending = store
.create_wallet(&new_wallet("spending", Some("Spending")))
.expect("spending");
let savings = store
.create_wallet(&new_wallet("savings", None))
.expect("savings");
assert_ne!(spending.id, savings.id, "two wallets, two rows");
(spending.id, savings.id)
};
let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("reopen");
let rows = store.list_wallets().expect("list");
assert_eq!(rows.len(), 2, "both wallets remembered: {rows:?}");
assert_eq!(rows[0].id, spending, "creation order");
assert_eq!(rows[1].id, savings);
assert_eq!(
rows[1].name, None,
"an unlabelled wallet round-trips as None"
);
assert_eq!(rows[1].wallet_filename, "savings");
}
#[test]
fn a_second_wallet_cannot_reuse_a_wallet_filename() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open");
let first = store
.create_wallet(&new_wallet("onionwire", None))
.expect("first");
let err = store
.create_wallet(&new_wallet("onionwire", Some("Clash")))
.expect_err("a duplicate filename must not overwrite the first wallet");
assert!(
err.to_string().contains("onionwire"),
"names the file: {err}"
);
let rows = store.list_wallets().expect("list");
assert_eq!(rows.len(), 1, "the rejected insert left one row: {rows:?}");
assert_eq!(rows[0], first, "the first wallet is untouched");
}
#[test]
fn delete_wallet_removes_only_that_row() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open");
let a = store.create_wallet(&new_wallet("a", None)).expect("a");
let b = store.create_wallet(&new_wallet("b", None)).expect("b");
assert!(store.delete_wallet(a.id).expect("delete"), "row was there");
assert_eq!(store.get_wallet_by_id(a.id).expect("get"), None);
let rows = store.list_wallets().expect("list");
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].id, b.id);
assert!(
!store
.delete_wallet(9999)
.expect("unknown id is not an error"),
"nothing to delete reports false"
);
}
#[test]
fn a_wallet_without_a_label_or_locator_stores_nulls_and_rejects_a_blank_filename() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open");
let mut blank = new_wallet("blank", Some(" "));
blank.onion_locator = String::new();
let row = store.create_wallet(&blank).expect("blank label");
assert_eq!(row.name, None, "a whitespace label is no label");
assert_eq!(row.onion_locator, "", "a locator may be empty pre-publish");
let err = store
.create_wallet(&new_wallet(" ", None))
.expect_err("an empty filename cannot name a wallet file");
assert!(err.to_string().contains("filename"), "{err}");
}