store: a wallet catalogue in the encrypted db
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.
This commit is contained in:
parent
3769bd9a42
commit
467510f096
3 changed files with 309 additions and 2 deletions
|
|
@ -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,
|
||||
};
|
||||
|
|
|
|||
184
src/store.rs
184
src/store.rs
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue