The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2311 lines
84 KiB
Rust
2311 lines
84 KiB
Rust
use std::fs;
|
|
use std::io::Read;
|
|
use std::os::unix::fs::PermissionsExt;
|
|
use std::path::{Path, PathBuf};
|
|
use std::time::{SystemTime, UNIX_EPOCH};
|
|
|
|
use ed25519_dalek::SigningKey;
|
|
use rand::RngCore;
|
|
use rand::rngs::OsRng;
|
|
use rusqlite::{Connection, OptionalExtension, params};
|
|
use x25519_dalek::{PublicKey as X25519Public, StaticSecret};
|
|
use zeroize::Zeroizing;
|
|
|
|
pub type Result<T> = std::result::Result<T, Error>;
|
|
|
|
#[derive(Debug)]
|
|
pub struct Error(String);
|
|
|
|
impl std::fmt::Display for Error {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
self.0.fmt(f)
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for Error {}
|
|
|
|
impl From<rusqlite::Error> for Error {
|
|
fn from(e: rusqlite::Error) -> Self {
|
|
Self(e.to_string())
|
|
}
|
|
}
|
|
|
|
impl From<std::io::Error> for Error {
|
|
fn from(e: std::io::Error) -> Self {
|
|
Self(e.to_string())
|
|
}
|
|
}
|
|
|
|
impl From<String> for Error {
|
|
fn from(e: String) -> Self {
|
|
Self(e)
|
|
}
|
|
}
|
|
|
|
/// The store error is a message and nothing else, and the rest of the crate
|
|
/// (transport, UI) already speaks `String`. Lossless, so `?` is enough at the
|
|
/// outbox boundary — no per-call `map_err`.
|
|
impl From<Error> for String {
|
|
fn from(e: Error) -> Self {
|
|
e.0
|
|
}
|
|
}
|
|
|
|
pub struct Store {
|
|
conn: Connection,
|
|
msg_key: Zeroizing<[u8; 32]>,
|
|
}
|
|
|
|
/// The identity row. Secret halves wipe when this is dropped.
|
|
pub struct SelfIdentity {
|
|
pub identity_sk: Zeroizing<Vec<u8>>,
|
|
pub identity_pk: Vec<u8>,
|
|
pub onion: String,
|
|
pub prekey_sk: Zeroizing<Vec<u8>>,
|
|
pub prekey_pk: Vec<u8>,
|
|
}
|
|
|
|
pub struct Friend {
|
|
pub pubkey: Vec<u8>,
|
|
pub fingerprint: String,
|
|
pub petname: Option<String>,
|
|
pub onion: String,
|
|
pub last_connect_ok: bool,
|
|
pub prekey: Vec<u8>,
|
|
}
|
|
|
|
pub struct FriendProfile {
|
|
pub display_name: String,
|
|
pub bio: String,
|
|
pub xmr_addr: String,
|
|
pub updated_at: i64,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub struct Message {
|
|
/// `messages.id` row id. The outbox row for a send carries the same
|
|
/// `message_id`, so the UI can join exactly instead of matching bodies.
|
|
pub id: i64,
|
|
pub dir: String,
|
|
pub plaintext: Vec<u8>,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub struct Payment {
|
|
pub id: i64,
|
|
pub dir: String,
|
|
pub kind: String,
|
|
pub amount_atomic: String,
|
|
pub address: String,
|
|
pub memo: String,
|
|
pub txid: Option<String>,
|
|
pub verified: bool,
|
|
pub created_at: i64,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum OutboxStatus {
|
|
Queued,
|
|
Sending,
|
|
Sent,
|
|
/// Terminal: transport or protocol failure that will not be retried.
|
|
Failed(String),
|
|
}
|
|
|
|
impl OutboxStatus {
|
|
pub fn is_terminal(&self) -> bool {
|
|
matches!(self, OutboxStatus::Sent | OutboxStatus::Failed(_))
|
|
}
|
|
|
|
/// Column encoding for the `outbox.status` CHECK constraint.
|
|
pub fn as_db_str(&self) -> &'static str {
|
|
match self {
|
|
OutboxStatus::Queued => "queued",
|
|
OutboxStatus::Sending => "sending",
|
|
OutboxStatus::Sent => "sent",
|
|
OutboxStatus::Failed(_) => "failed",
|
|
}
|
|
}
|
|
|
|
pub fn from_db(status: &str, last_error: Option<&str>) -> Self {
|
|
match status {
|
|
"sending" => OutboxStatus::Sending,
|
|
"sent" => OutboxStatus::Sent,
|
|
"failed" => OutboxStatus::Failed(last_error.unwrap_or("failed").to_string()),
|
|
_ => OutboxStatus::Queued,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl std::fmt::Display for OutboxStatus {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
match self {
|
|
OutboxStatus::Failed(why) => write!(f, "failed: {why}"),
|
|
other => f.write_str(other.as_db_str()),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// One queued chat send. The body is not copied: it lives in the `messages`
|
|
/// row the outbox row points at, under that row's own AEAD.
|
|
#[derive(Debug, Clone)]
|
|
pub struct OutboxEntry {
|
|
pub id: i64,
|
|
pub friend_pk: Vec<u8>,
|
|
pub message_id: i64,
|
|
pub body: Vec<u8>,
|
|
/// What to put on the wire when it is set, instead of `body`. A chat send
|
|
/// stores its already-encoded ratchet frame here so a retry re-sends the
|
|
/// identical bytes instead of re-encrypting (which would burn a second
|
|
/// chain key and land as a second chat line at the peer). `None` means the
|
|
/// row predates payloads or is a locator/profile/payment row: send `body`.
|
|
pub payload: Option<Vec<u8>>,
|
|
pub attempts: u32,
|
|
pub next_attempt_at: i64,
|
|
pub created_at: i64,
|
|
pub status: OutboxStatus,
|
|
pub last_error: Option<String>,
|
|
}
|
|
|
|
pub struct PaymentWrite<'a> {
|
|
pub dir: &'a str,
|
|
pub kind: &'a str,
|
|
pub amount_atomic: &'a str,
|
|
pub address: &'a str,
|
|
pub memo: &'a str,
|
|
pub txid: Option<&'a str>,
|
|
pub verified: bool,
|
|
}
|
|
|
|
impl Store {
|
|
pub fn open() -> Result<Self> {
|
|
Self::open_at(&home_dir()?)
|
|
}
|
|
|
|
pub fn home_dir() -> Result<PathBuf> {
|
|
home_dir()
|
|
}
|
|
|
|
pub fn open_at(home: &Path) -> Result<Self> {
|
|
let passphrase = passphrase_from_env()?;
|
|
Self::open_at_with_passphrase(home, passphrase.as_str())
|
|
}
|
|
|
|
pub fn open_at_with_passphrase(home: &Path, passphrase: &str) -> Result<Self> {
|
|
if passphrase.is_empty() {
|
|
return Err(Error("empty passphrase".into()));
|
|
}
|
|
mkdir_700(home)?;
|
|
mkdir_700(&home.join("arti"))?;
|
|
mkdir_700(&home.join("cache"))?;
|
|
let db_path = home.join("onionwire.db");
|
|
let conn = open_store_db(home, &db_path, passphrase)?;
|
|
let journal: String = conn.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))?;
|
|
if !journal.eq_ignore_ascii_case("wal") {
|
|
return Err(Error(format!("journal_mode WAL failed: {journal}")));
|
|
}
|
|
// Overwrite freed pages on DELETE. Flash wear-leveling can still keep copies;
|
|
// this is not a forensic / SSD crypto-shred.
|
|
conn.pragma_update(None, "secure_delete", "ON")?;
|
|
conn.execute_batch(
|
|
"
|
|
PRAGMA foreign_keys = ON;
|
|
CREATE TABLE IF NOT EXISTS friends (
|
|
id INTEGER PRIMARY KEY,
|
|
pubkey BLOB NOT NULL UNIQUE,
|
|
fingerprint TEXT NOT NULL,
|
|
petname TEXT,
|
|
onion TEXT NOT NULL,
|
|
onion_updated_at INTEGER NOT NULL,
|
|
added_at INTEGER NOT NULL,
|
|
last_connect_ok INTEGER NOT NULL DEFAULT 1,
|
|
prekey BLOB NOT NULL DEFAULT x''
|
|
);
|
|
CREATE TABLE IF NOT EXISTS messages (
|
|
id INTEGER PRIMARY KEY,
|
|
friend_id INTEGER NOT NULL REFERENCES friends(id),
|
|
dir TEXT NOT NULL CHECK(dir IN ('in','out')),
|
|
plaintext BLOB NOT NULL,
|
|
created_at INTEGER NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS self (
|
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
identity_sk BLOB NOT NULL,
|
|
identity_pk BLOB NOT NULL,
|
|
onion TEXT NOT NULL,
|
|
onion_rotated_at INTEGER NOT NULL,
|
|
prekey_sk BLOB NOT NULL,
|
|
prekey_pk BLOB NOT NULL,
|
|
hs_nickname TEXT NOT NULL DEFAULT 'ow0'
|
|
);
|
|
CREATE TABLE IF NOT EXISTS self_profile (
|
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
display_name TEXT NOT NULL DEFAULT '',
|
|
bio TEXT NOT NULL DEFAULT '',
|
|
xmr_addr TEXT NOT NULL DEFAULT '',
|
|
updated_at INTEGER NOT NULL DEFAULT 0
|
|
);
|
|
CREATE TABLE IF NOT EXISTS friend_profiles (
|
|
pubkey BLOB PRIMARY KEY,
|
|
display_name TEXT NOT NULL,
|
|
bio TEXT NOT NULL,
|
|
xmr_addr TEXT NOT NULL DEFAULT '',
|
|
updated_at INTEGER NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS store_meta (
|
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
kdf_salt BLOB NOT NULL,
|
|
wrapped_key BLOB NOT NULL
|
|
);
|
|
-- The wallet child's RPC creds + chain-source snapshot. One row,
|
|
-- sealed with the store data key (see `save_wallet_child`): the
|
|
-- creds never touch the filesystem in the clear.
|
|
CREATE TABLE IF NOT EXISTS wallet_child (
|
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
sealed BLOB NOT NULL,
|
|
updated_at INTEGER NOT NULL
|
|
);
|
|
-- Remote-mode wallet config the user set in-app (F7): the endpoint,
|
|
-- the login, and the view-only flag. One row; the login is sealed
|
|
-- with the store data key (see `save_wallet_config`).
|
|
CREATE TABLE IF NOT EXISTS wallet_config (
|
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
rpc_url TEXT NOT NULL,
|
|
sealed_login BLOB NOT NULL,
|
|
no_spend INTEGER NOT NULL,
|
|
updated_at INTEGER NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS payments (
|
|
id INTEGER PRIMARY KEY,
|
|
friend_id INTEGER NOT NULL REFERENCES friends(id),
|
|
dir TEXT NOT NULL CHECK(dir IN ('in','out')),
|
|
kind TEXT NOT NULL CHECK(kind IN ('invoice','receipt','tip')),
|
|
amount_atomic TEXT NOT NULL,
|
|
address TEXT NOT NULL,
|
|
memo TEXT NOT NULL DEFAULT '',
|
|
txid TEXT,
|
|
verified INTEGER NOT NULL DEFAULT 0,
|
|
created_at INTEGER NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS outbox (
|
|
id INTEGER PRIMARY KEY,
|
|
friend_id INTEGER NOT NULL REFERENCES friends(id),
|
|
message_id INTEGER NOT NULL,
|
|
attempts INTEGER NOT NULL DEFAULT 0,
|
|
next_attempt_at INTEGER NOT NULL,
|
|
status TEXT NOT NULL CHECK(status IN ('queued','sending','sent','failed')),
|
|
last_error TEXT,
|
|
created_at INTEGER NOT NULL,
|
|
updated_at INTEGER NOT NULL,
|
|
payload BLOB
|
|
);
|
|
CREATE INDEX IF NOT EXISTS outbox_due ON outbox (status, next_attempt_at);
|
|
CREATE TABLE IF NOT EXISTS ratchet_sessions (
|
|
friend_id INTEGER PRIMARY KEY REFERENCES friends(id) ON DELETE CASCADE,
|
|
state BLOB NOT NULL,
|
|
updated_at INTEGER NOT NULL
|
|
);
|
|
INSERT OR IGNORE INTO self_profile (id) VALUES (1);
|
|
",
|
|
)?;
|
|
let check: String = conn.query_row("PRAGMA integrity_check", [], |row| row.get(0))?;
|
|
if check != "ok" {
|
|
return Err(Error(format!("integrity_check: {check}")));
|
|
}
|
|
let mut store = Self {
|
|
conn,
|
|
msg_key: Zeroizing::new([0u8; 32]),
|
|
};
|
|
store.migrate()?;
|
|
store.ensure_self()?;
|
|
store.unlock_messages(passphrase)?;
|
|
Ok(store)
|
|
}
|
|
|
|
pub fn journal_mode(&self) -> Result<String> {
|
|
self.conn
|
|
.query_row("PRAGMA journal_mode", [], |row| row.get(0))
|
|
.map_err(Into::into)
|
|
}
|
|
|
|
/// Seal the wallet child's config (RPC creds + chain-source snapshot) into
|
|
/// the encrypted store, replacing the single row.
|
|
///
|
|
/// The creds are generated per install and grant spend authority over the
|
|
/// wallet child, so they are stored the same way message bodies are: AEAD
|
|
/// with the store data key on top of the whole-db SQLCipher layer. They are
|
|
/// never written to a plaintext file beside the wallet.
|
|
pub fn save_wallet_child(&self, json: &str) -> Result<()> {
|
|
let blob = crate::backup::aead_encrypt(&self.msg_key, json.as_bytes(), WALLET_CHILD_AAD)
|
|
.map_err(Error)?;
|
|
self.conn.execute(
|
|
"INSERT INTO wallet_child (id, sealed, updated_at) VALUES (1, ?1, ?2)
|
|
ON CONFLICT(id) DO UPDATE SET sealed = excluded.sealed, updated_at = excluded.updated_at",
|
|
params![blob, unix_now()],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Read back the sealed wallet-child config, or `None` before the first
|
|
/// child start. A blob that does not decrypt is an error, never a guess.
|
|
pub fn load_wallet_child(&self) -> Result<Option<String>> {
|
|
let row: Option<Vec<u8>> = self
|
|
.conn
|
|
.query_row("SELECT sealed FROM wallet_child WHERE id = 1", [], |row| {
|
|
row.get(0)
|
|
})
|
|
.optional()?;
|
|
let Some(blob) = row else {
|
|
return Ok(None);
|
|
};
|
|
let plain = crate::backup::aead_decrypt(&self.msg_key, &blob, WALLET_CHILD_AAD)
|
|
.map_err(|_| Error("wallet-child config decrypt failed".into()))?;
|
|
String::from_utf8(plain)
|
|
.map(Some)
|
|
.map_err(|_| Error("wallet-child config is not utf-8".into()))
|
|
}
|
|
|
|
/// Persist the remote-mode wallet config the F7 screen saved. One row,
|
|
/// replaced in place; an empty `rpc_url` clears it (that is how a user
|
|
/// turns the stored wallet off again).
|
|
///
|
|
/// The login is `user:pass` for a wallet that can spend, so it is sealed
|
|
/// with the store data key on top of the whole-db SQLCipher layer — the
|
|
/// same discipline as the wallet-child creds.
|
|
pub fn save_wallet_config(&self, cfg: &crate::wallet::WalletConfig) -> Result<()> {
|
|
if cfg.rpc_url.trim().is_empty() {
|
|
self.conn.execute("DELETE FROM wallet_config", [])?;
|
|
return Ok(());
|
|
}
|
|
let sealed =
|
|
crate::backup::aead_encrypt(&self.msg_key, cfg.rpc_login.as_bytes(), WALLET_CONFIG_AAD)
|
|
.map_err(Error)?;
|
|
self.conn.execute(
|
|
"INSERT INTO wallet_config (id, rpc_url, sealed_login, no_spend, updated_at)
|
|
VALUES (1, ?1, ?2, ?3, ?4)
|
|
ON CONFLICT(id) DO UPDATE SET rpc_url = excluded.rpc_url,
|
|
sealed_login = excluded.sealed_login, no_spend = excluded.no_spend,
|
|
updated_at = excluded.updated_at",
|
|
params![cfg.rpc_url.trim(), sealed, cfg.no_spend as i64, unix_now()],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Read the stored remote-mode config, or `None` when none was ever saved.
|
|
/// A blob that does not decrypt is an error, never a guess.
|
|
pub fn load_wallet_config(&self) -> Result<Option<crate::wallet::WalletConfig>> {
|
|
let row: Option<(String, Vec<u8>, i64)> = self
|
|
.conn
|
|
.query_row(
|
|
"SELECT rpc_url, sealed_login, no_spend FROM wallet_config WHERE id = 1",
|
|
[],
|
|
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
|
|
)
|
|
.optional()?;
|
|
let Some((rpc_url, sealed, no_spend)) = row else {
|
|
return Ok(None);
|
|
};
|
|
let login = crate::backup::aead_decrypt(&self.msg_key, &sealed, WALLET_CONFIG_AAD)
|
|
.map_err(|_| Error("wallet config decrypt failed".into()))?;
|
|
// The login is a secret: it must not survive in a bare `String`.
|
|
let login = Zeroizing::new(
|
|
String::from_utf8(login).map_err(|_| Error("wallet config is not utf-8".into()))?,
|
|
);
|
|
Ok(Some(crate::wallet::WalletConfig {
|
|
rpc_url,
|
|
rpc_login: login,
|
|
no_spend: no_spend != 0,
|
|
}))
|
|
}
|
|
|
|
pub fn replace_identity_keys(
|
|
&self,
|
|
identity_sk: &[u8],
|
|
identity_pk: &[u8],
|
|
prekey_sk: &[u8],
|
|
prekey_pk: &[u8],
|
|
) -> Result<()> {
|
|
if identity_sk.len() != 32
|
|
|| identity_pk.len() != 32
|
|
|| prekey_sk.len() != 32
|
|
|| prekey_pk.len() != 32
|
|
{
|
|
return Err(Error("identity key length".into()));
|
|
}
|
|
self.conn.execute(
|
|
"UPDATE self SET identity_sk = ?1, identity_pk = ?2, prekey_sk = ?3, prekey_pk = ?4 WHERE id = 1",
|
|
params![identity_sk, identity_pk, prekey_sk, prekey_pk],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
fn migrate(&self) -> Result<()> {
|
|
self.add_column_if_missing(
|
|
"friends",
|
|
"last_connect_ok",
|
|
"ALTER TABLE friends ADD COLUMN last_connect_ok INTEGER NOT NULL DEFAULT 1",
|
|
)?;
|
|
self.add_column_if_missing(
|
|
"friends",
|
|
"prekey",
|
|
"ALTER TABLE friends ADD COLUMN prekey BLOB NOT NULL DEFAULT x''",
|
|
)?;
|
|
self.add_column_if_missing(
|
|
"self",
|
|
"prekey_sk",
|
|
"ALTER TABLE self ADD COLUMN prekey_sk BLOB NOT NULL DEFAULT x''",
|
|
)?;
|
|
self.add_column_if_missing(
|
|
"self",
|
|
"prekey_pk",
|
|
"ALTER TABLE self ADD COLUMN prekey_pk BLOB NOT NULL DEFAULT x''",
|
|
)?;
|
|
self.add_column_if_missing(
|
|
"self",
|
|
"hs_nickname",
|
|
"ALTER TABLE self ADD COLUMN hs_nickname TEXT NOT NULL DEFAULT 'ow0'",
|
|
)?;
|
|
// Opaque send payload for rows that cannot re-derive their bytes (a
|
|
// chat send's ratchet frame). NULL means "send the message body", the
|
|
// pre-payload behaviour, so locator/profile/payment rows are unchanged.
|
|
self.add_column_if_missing(
|
|
"outbox",
|
|
"payload",
|
|
"ALTER TABLE outbox ADD COLUMN payload BLOB",
|
|
)?;
|
|
// `insert_payment` has accepted `kind = "tip"` since the tip path
|
|
// landed, but the table's CHECK only allowed invoice/receipt, so every
|
|
// tip insert (inbound *and* outbound) failed the constraint and the
|
|
// frame was dropped. SQLite cannot alter a CHECK, so rebuild.
|
|
self.widen_payment_kinds()?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Widen `payments.kind` to accept `'tip'` on stores created before the
|
|
/// tip path. The table is rebuilt in place because SQLite has no
|
|
/// `ALTER TABLE ... DROP CONSTRAINT`; ids and rows are preserved verbatim.
|
|
fn widen_payment_kinds(&self) -> Result<()> {
|
|
let schema: Option<String> = self
|
|
.conn
|
|
.query_row(
|
|
"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'payments'",
|
|
[],
|
|
|row| row.get(0),
|
|
)
|
|
.optional()?;
|
|
let Some(schema) = schema else {
|
|
return Ok(());
|
|
};
|
|
if schema.contains("'tip'") {
|
|
return Ok(());
|
|
}
|
|
self.conn.execute_batch(
|
|
"ALTER TABLE payments RENAME TO payments_pre_tip;
|
|
CREATE TABLE payments (
|
|
id INTEGER PRIMARY KEY,
|
|
friend_id INTEGER NOT NULL REFERENCES friends(id),
|
|
dir TEXT NOT NULL CHECK(dir IN ('in','out')),
|
|
kind TEXT NOT NULL CHECK(kind IN ('invoice','receipt','tip')),
|
|
amount_atomic TEXT NOT NULL,
|
|
address TEXT NOT NULL,
|
|
memo TEXT NOT NULL DEFAULT '',
|
|
txid TEXT,
|
|
verified INTEGER NOT NULL DEFAULT 0,
|
|
created_at INTEGER NOT NULL
|
|
);
|
|
INSERT INTO payments (id, friend_id, dir, kind, amount_atomic, address, memo, txid, verified, created_at)
|
|
SELECT id, friend_id, dir, kind, amount_atomic, address, memo, txid, verified, created_at
|
|
FROM payments_pre_tip;
|
|
DROP TABLE payments_pre_tip;",
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
fn unlock_messages(&mut self, passphrase: &str) -> Result<()> {
|
|
let row: Option<(Vec<u8>, Vec<u8>)> = self
|
|
.conn
|
|
.query_row(
|
|
"SELECT kdf_salt, wrapped_key FROM store_meta WHERE id = 1",
|
|
[],
|
|
|r| Ok((r.get(0)?, r.get(1)?)),
|
|
)
|
|
.optional()?;
|
|
match row {
|
|
Some((salt, wrapped)) => {
|
|
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
|
|
// The unwrapped data key lands in a Zeroizing buffer immediately.
|
|
let raw = Zeroizing::new(
|
|
crate::backup::aead_decrypt(&wrap_key, &wrapped, b"")
|
|
.map_err(|_| Error("wrong passphrase".into()))?,
|
|
);
|
|
if raw.len() != 32 {
|
|
return Err(Error("wrapped message key length".into()));
|
|
}
|
|
self.msg_key.copy_from_slice(&raw);
|
|
self.rewrap_empty_aad_messages()?;
|
|
Ok(())
|
|
}
|
|
None => {
|
|
let mut data_key = Zeroizing::new([0u8; 32]);
|
|
OsRng.fill_bytes(&mut data_key[..]);
|
|
let mut salt = [0u8; 16];
|
|
OsRng.fill_bytes(&mut salt);
|
|
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
|
|
let wrapped = crate::backup::aead_encrypt(&wrap_key, &data_key[..], b"")?;
|
|
self.conn.execute(
|
|
"INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)",
|
|
params![salt.as_slice(), wrapped],
|
|
)?;
|
|
self.msg_key = data_key;
|
|
self.reencrypt_legacy_messages()?;
|
|
Ok(())
|
|
}
|
|
}
|
|
}
|
|
|
|
fn reencrypt_legacy_messages(&self) -> Result<()> {
|
|
let mut stmt = self
|
|
.conn
|
|
.prepare("SELECT id, friend_id, dir, plaintext FROM messages")?;
|
|
let rows: Vec<(i64, i64, String, Vec<u8>)> = stmt
|
|
.query_map([], |row| {
|
|
Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
|
|
})?
|
|
.collect::<std::result::Result<_, _>>()?;
|
|
drop(stmt);
|
|
if rows.is_empty() {
|
|
return Ok(());
|
|
}
|
|
let tx = self.conn.unchecked_transaction()?;
|
|
for (id, friend_id, dir, plain) in rows {
|
|
let aad = message_aad(friend_id, &dir, id);
|
|
let blob = crate::backup::aead_encrypt(&self.msg_key, &plain, &aad)?;
|
|
tx.execute(
|
|
"UPDATE messages SET plaintext = ?1 WHERE id = ?2",
|
|
params![blob, id],
|
|
)?;
|
|
}
|
|
tx.commit()?;
|
|
let _ = self.conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
Ok(())
|
|
}
|
|
|
|
/// One-shot: empty-AAD v0.2 blobs → row-bound AAD. list_messages never falls back.
|
|
fn rewrap_empty_aad_messages(&self) -> Result<()> {
|
|
let mut stmt = self
|
|
.conn
|
|
.prepare("SELECT id, friend_id, dir, plaintext FROM messages")?;
|
|
let rows: Vec<(i64, i64, String, Vec<u8>)> = stmt
|
|
.query_map([], |row| {
|
|
Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
|
|
})?
|
|
.collect::<std::result::Result<_, _>>()?;
|
|
drop(stmt);
|
|
let mut updates = Vec::new();
|
|
for (id, friend_id, dir, blob) in rows {
|
|
let aad = message_aad(friend_id, &dir, id);
|
|
if crate::backup::aead_decrypt(&self.msg_key, &blob, &aad).is_ok() {
|
|
continue;
|
|
}
|
|
if let Ok(pt) = crate::backup::aead_decrypt(&self.msg_key, &blob, b"") {
|
|
let new_blob = crate::backup::aead_encrypt(&self.msg_key, &pt, &aad)?;
|
|
updates.push((id, new_blob));
|
|
}
|
|
}
|
|
if updates.is_empty() {
|
|
return Ok(());
|
|
}
|
|
let tx = self.conn.unchecked_transaction()?;
|
|
for (id, blob) in updates {
|
|
tx.execute(
|
|
"UPDATE messages SET plaintext = ?1 WHERE id = ?2",
|
|
params![blob, id],
|
|
)?;
|
|
}
|
|
tx.commit()?;
|
|
let _ = self.conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
Ok(())
|
|
}
|
|
|
|
fn add_column_if_missing(&self, table: &str, column: &str, ddl: &str) -> Result<()> {
|
|
let sql =
|
|
format!("SELECT COUNT(*) FROM pragma_table_info('{table}') WHERE name = '{column}'");
|
|
let has: i64 = self.conn.query_row(&sql, [], |row| row.get(0))?;
|
|
if has == 0 {
|
|
self.conn.execute(ddl, [])?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn ensure_self(&self) -> Result<()> {
|
|
let exists: i64 =
|
|
self.conn
|
|
.query_row("SELECT COUNT(*) FROM self WHERE id = 1", [], |row| {
|
|
row.get(0)
|
|
})?;
|
|
if exists == 0 {
|
|
let signing = SigningKey::generate(&mut OsRng);
|
|
let sk = Zeroizing::new(signing.to_bytes().to_vec());
|
|
let pk = signing.verifying_key().to_bytes().to_vec();
|
|
let (psk, ppk) = gen_prekey();
|
|
self.conn.execute(
|
|
"INSERT INTO self (id, identity_sk, identity_pk, onion, onion_rotated_at, prekey_sk, prekey_pk, hs_nickname)
|
|
VALUES (1, ?1, ?2, '', 0, ?3, ?4, 'ow0')",
|
|
params![&sk[..], pk, &psk[..], ppk],
|
|
)?;
|
|
} else {
|
|
let empty: i64 = self.conn.query_row(
|
|
"SELECT CASE WHEN length(prekey_sk) = 32 AND length(prekey_pk) = 32 THEN 0 ELSE 1 END FROM self WHERE id = 1",
|
|
[],
|
|
|row| row.get(0),
|
|
)?;
|
|
if empty != 0 {
|
|
let (psk, ppk) = gen_prekey();
|
|
self.conn.execute(
|
|
"UPDATE self SET prekey_sk = ?1, prekey_pk = ?2 WHERE id = 1",
|
|
params![&psk[..], ppk],
|
|
)?;
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn self_identity(&self) -> Result<SelfIdentity> {
|
|
self.conn
|
|
.query_row(
|
|
"SELECT identity_sk, identity_pk, onion, prekey_sk, prekey_pk FROM self WHERE id = 1",
|
|
[],
|
|
|row| {
|
|
Ok(SelfIdentity {
|
|
identity_sk: Zeroizing::new(row.get(0)?),
|
|
identity_pk: row.get(1)?,
|
|
onion: row.get(2)?,
|
|
prekey_sk: Zeroizing::new(row.get(3)?),
|
|
prekey_pk: row.get(4)?,
|
|
})
|
|
},
|
|
)
|
|
.map_err(Into::into)
|
|
}
|
|
|
|
pub fn friend_count(&self) -> Result<i64> {
|
|
self.conn
|
|
.query_row("SELECT COUNT(*) FROM friends", [], |row| row.get(0))
|
|
.map_err(Into::into)
|
|
}
|
|
|
|
/// Display fingerprint of our own identity key (identity = pubkey).
|
|
pub fn self_fingerprint(&self) -> Result<String> {
|
|
Ok(fingerprint(&self.self_identity()?.identity_pk))
|
|
}
|
|
|
|
/// Local petname only. Never part of the wire protocol.
|
|
pub fn set_petname(&self, pubkey: &[u8], petname: Option<&str>) -> Result<()> {
|
|
let n = self.conn.execute(
|
|
"UPDATE friends SET petname = ?1 WHERE pubkey = ?2",
|
|
params![petname, pubkey],
|
|
)?;
|
|
if n == 0 {
|
|
return Err(Error("friend not found".into()));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn upsert_friend(&self, pubkey: &[u8], onion: &str, petname: Option<&str>) -> Result<()> {
|
|
let now = unix_now();
|
|
let fp = fingerprint(pubkey);
|
|
self.conn.execute(
|
|
"INSERT INTO friends (pubkey, fingerprint, petname, onion, onion_updated_at, added_at)
|
|
VALUES (?1, ?2, ?3, ?4, ?5, ?5)
|
|
ON CONFLICT(pubkey) DO UPDATE SET
|
|
onion = excluded.onion,
|
|
onion_updated_at = excluded.onion_updated_at,
|
|
petname = COALESCE(excluded.petname, friends.petname)",
|
|
params![pubkey, fp, petname, onion, now],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn get_friend(&self, pubkey: &[u8]) -> Result<Option<Friend>> {
|
|
self.conn
|
|
.query_row(
|
|
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE pubkey = ?1",
|
|
params![pubkey],
|
|
friend_from_row,
|
|
)
|
|
.optional()
|
|
.map_err(Into::into)
|
|
}
|
|
|
|
/// Locator → friend. Onions are not unique in the schema (a stale row can
|
|
/// hold a rotated address), so the first match wins; the outbox uses this
|
|
/// only to pick which queue to flush early.
|
|
pub fn friend_by_onion(&self, onion: &str) -> Result<Option<Friend>> {
|
|
self.conn
|
|
.query_row(
|
|
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE onion = ?1 ORDER BY id LIMIT 1",
|
|
params![onion],
|
|
friend_from_row,
|
|
)
|
|
.optional()
|
|
.map_err(Into::into)
|
|
}
|
|
|
|
pub fn list_friends(&self) -> Result<Vec<Friend>> {
|
|
let mut stmt = self.conn.prepare(
|
|
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends
|
|
ORDER BY COALESCE(petname, fingerprint) COLLATE NOCASE",
|
|
)?;
|
|
let rows = stmt.query_map([], friend_from_row)?;
|
|
let mut out = Vec::new();
|
|
for row in rows {
|
|
out.push(row?);
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
pub fn hs_nickname(&self) -> Result<String> {
|
|
self.conn
|
|
.query_row("SELECT hs_nickname FROM self WHERE id = 1", [], |row| {
|
|
row.get(0)
|
|
})
|
|
.map_err(Into::into)
|
|
}
|
|
|
|
pub fn set_hs_nickname(&self, nickname: &str) -> Result<()> {
|
|
self.conn.execute(
|
|
"UPDATE self SET hs_nickname = ?1 WHERE id = 1",
|
|
params![nickname],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn set_onion(&self, onion: &str) -> Result<()> {
|
|
let now = unix_now();
|
|
self.conn.execute(
|
|
"UPDATE self SET onion = ?1, onion_rotated_at = ?2 WHERE id = 1",
|
|
params![onion, now],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Apply a signed locator update. Bad sig / stale ts / unknown friend → no change.
|
|
pub fn apply_loc(&self, pubkey: &[u8], onion: &str, ts: i64, sig: &[u8]) -> Result<bool> {
|
|
let loc = crate::loc::Loc {
|
|
onion: onion.to_string(),
|
|
ts,
|
|
sig: sig.to_vec(),
|
|
};
|
|
if !crate::loc::verify(pubkey, &loc) {
|
|
return Ok(false);
|
|
}
|
|
let Some(updated_at) = self
|
|
.conn
|
|
.query_row(
|
|
"SELECT onion_updated_at FROM friends WHERE pubkey = ?1",
|
|
params![pubkey],
|
|
|row| row.get::<_, i64>(0),
|
|
)
|
|
.optional()?
|
|
else {
|
|
return Ok(false);
|
|
};
|
|
if ts <= updated_at {
|
|
return Ok(false);
|
|
}
|
|
let n = self.conn.execute(
|
|
"UPDATE friends SET onion = ?1, onion_updated_at = ?2 WHERE pubkey = ?3",
|
|
params![onion, ts, pubkey],
|
|
)?;
|
|
Ok(n > 0)
|
|
}
|
|
|
|
pub fn set_self_profile(&self, display_name: &str, bio: &str, xmr_addr: &str) -> Result<()> {
|
|
crate::profile::validate(display_name, bio, xmr_addr).map_err(|e| Error(e.to_string()))?;
|
|
let prev: i64 = self.conn.query_row(
|
|
"SELECT updated_at FROM self_profile WHERE id = 1",
|
|
[],
|
|
|row| row.get(0),
|
|
)?;
|
|
let now = unix_now().max(prev + 1);
|
|
self.conn.execute(
|
|
"UPDATE self_profile SET display_name = ?1, bio = ?2, xmr_addr = ?3, updated_at = ?4 WHERE id = 1",
|
|
params![display_name, bio, xmr_addr, now],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn self_profile(&self) -> Result<FriendProfile> {
|
|
self.conn
|
|
.query_row(
|
|
"SELECT display_name, bio, xmr_addr, updated_at FROM self_profile WHERE id = 1",
|
|
[],
|
|
profile_from_row,
|
|
)
|
|
.map_err(Into::into)
|
|
}
|
|
|
|
/// Apply a signed profile. Unknown friend / bad sig / stale ts → no change, no insert.
|
|
pub fn apply_profile(&self, pubkey: &[u8], prf: &crate::profile::Profile) -> Result<bool> {
|
|
if !crate::profile::verify(pubkey, prf) {
|
|
return Ok(false);
|
|
}
|
|
let exists: i64 = self.conn.query_row(
|
|
"SELECT COUNT(*) FROM friends WHERE pubkey = ?1",
|
|
params![pubkey],
|
|
|row| row.get(0),
|
|
)?;
|
|
if exists == 0 {
|
|
return Ok(false);
|
|
}
|
|
let prev: Option<i64> = self
|
|
.conn
|
|
.query_row(
|
|
"SELECT updated_at FROM friend_profiles WHERE pubkey = ?1",
|
|
params![pubkey],
|
|
|row| row.get(0),
|
|
)
|
|
.optional()?;
|
|
if prev.is_some_and(|t| prf.ts <= t) {
|
|
return Ok(false);
|
|
}
|
|
self.conn.execute(
|
|
"INSERT INTO friend_profiles (pubkey, display_name, bio, xmr_addr, updated_at)
|
|
VALUES (?1, ?2, ?3, ?4, ?5)
|
|
ON CONFLICT(pubkey) DO UPDATE SET
|
|
display_name = excluded.display_name,
|
|
bio = excluded.bio,
|
|
xmr_addr = excluded.xmr_addr,
|
|
updated_at = excluded.updated_at",
|
|
params![pubkey, prf.display_name, prf.bio, prf.xmr_addr, prf.ts],
|
|
)?;
|
|
Ok(true)
|
|
}
|
|
|
|
pub fn friend_profile(&self, pubkey: &[u8]) -> Result<Option<FriendProfile>> {
|
|
self.conn
|
|
.query_row(
|
|
"SELECT display_name, bio, xmr_addr, updated_at FROM friend_profiles WHERE pubkey = ?1",
|
|
params![pubkey],
|
|
profile_from_row,
|
|
)
|
|
.optional()
|
|
.map_err(Into::into)
|
|
}
|
|
|
|
pub fn set_friend_prekey(&self, pubkey: &[u8], prekey: &[u8]) -> Result<()> {
|
|
let n = self.conn.execute(
|
|
"UPDATE friends SET prekey = ?1 WHERE pubkey = ?2",
|
|
params![prekey, pubkey],
|
|
)?;
|
|
if n == 0 {
|
|
return Err(Error("friend not found".into()));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn get_friend_by_prekey(&self, prekey: &[u8]) -> Result<Option<Friend>> {
|
|
self.conn
|
|
.query_row(
|
|
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE prekey = ?1",
|
|
params![prekey],
|
|
friend_from_row,
|
|
)
|
|
.optional()
|
|
.map_err(Into::into)
|
|
}
|
|
|
|
pub fn insert_payment(&self, friend_pk: &[u8], p: PaymentWrite<'_>) -> Result<i64> {
|
|
if p.dir != "in" && p.dir != "out" {
|
|
return Err(Error("dir must be in or out".into()));
|
|
}
|
|
if p.kind != "invoice" && p.kind != "receipt" && p.kind != "tip" {
|
|
return Err(Error("kind must be invoice, receipt, or tip".into()));
|
|
}
|
|
crate::pay::parse_atomic(p.amount_atomic).map_err(|e| Error(e.to_string()))?;
|
|
crate::pay::check_address(p.address).map_err(|e| Error(e.to_string()))?;
|
|
let friend_id: i64 = self
|
|
.conn
|
|
.query_row(
|
|
"SELECT id FROM friends WHERE pubkey = ?1",
|
|
params![friend_pk],
|
|
|row| row.get(0),
|
|
)
|
|
.map_err(|_| Error("friend not found".into()))?;
|
|
self.conn.execute(
|
|
"INSERT INTO payments (friend_id, dir, kind, amount_atomic, address, memo, txid, verified, created_at)
|
|
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
|
|
params![
|
|
friend_id,
|
|
p.dir,
|
|
p.kind,
|
|
p.amount_atomic,
|
|
p.address,
|
|
p.memo,
|
|
p.txid,
|
|
i64::from(p.verified),
|
|
unix_now()
|
|
],
|
|
)?;
|
|
Ok(self.conn.last_insert_rowid())
|
|
}
|
|
|
|
pub fn list_payments(&self, friend_pk: &[u8]) -> Result<Vec<Payment>> {
|
|
let mut stmt = self.conn.prepare(
|
|
"SELECT p.id, p.dir, p.kind, p.amount_atomic, p.address, p.memo, p.txid, p.verified, p.created_at
|
|
FROM payments p
|
|
JOIN friends f ON f.id = p.friend_id
|
|
WHERE f.pubkey = ?1
|
|
ORDER BY p.id",
|
|
)?;
|
|
let rows = stmt.query_map(params![friend_pk], payment_from_row)?;
|
|
let mut out = Vec::new();
|
|
for row in rows {
|
|
out.push(row?);
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
pub fn mark_verified(&self, id: i64) -> Result<bool> {
|
|
let n = self.conn.execute(
|
|
"UPDATE payments SET verified = 1 WHERE id = ?1",
|
|
params![id],
|
|
)?;
|
|
Ok(n > 0)
|
|
}
|
|
|
|
pub fn append_message(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<()> {
|
|
self.append_message_id(friend_pk, dir, plaintext)
|
|
.map(|_| ())
|
|
}
|
|
|
|
/// Same as `append_message`, returning the row id so an outbox row can
|
|
/// point at the body instead of storing a second copy.
|
|
pub fn append_message_id(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<i64> {
|
|
if dir != "in" && dir != "out" {
|
|
return Err(Error("dir must be in or out".into()));
|
|
}
|
|
let friend_id: i64 = self
|
|
.conn
|
|
.query_row(
|
|
"SELECT id FROM friends WHERE pubkey = ?1",
|
|
params![friend_pk],
|
|
|row| row.get(0),
|
|
)
|
|
.map_err(|_| Error("friend not found".into()))?;
|
|
let tx = self.conn.unchecked_transaction()?;
|
|
tx.execute(
|
|
"INSERT INTO messages (friend_id, dir, plaintext, created_at) VALUES (?1, ?2, x'', ?3)",
|
|
params![friend_id, dir, unix_now()],
|
|
)?;
|
|
let row_id = tx.last_insert_rowid();
|
|
let aad = message_aad(friend_id, dir, row_id);
|
|
let blob = crate::backup::aead_encrypt(&self.msg_key, plaintext, &aad)?;
|
|
tx.execute(
|
|
"UPDATE messages SET plaintext = ?1 WHERE id = ?2",
|
|
params![blob, row_id],
|
|
)?;
|
|
tx.commit()?;
|
|
Ok(row_id)
|
|
}
|
|
|
|
pub fn list_messages(&self, friend_pk: &[u8]) -> Result<Vec<Message>> {
|
|
let mut stmt = self.conn.prepare(
|
|
"SELECT m.id, m.friend_id, m.dir, m.plaintext FROM messages m
|
|
JOIN friends f ON f.id = m.friend_id
|
|
WHERE f.pubkey = ?1
|
|
ORDER BY m.id",
|
|
)?;
|
|
let rows = stmt.query_map(params![friend_pk], |row| {
|
|
Ok((
|
|
row.get::<_, i64>(0)?,
|
|
row.get::<_, i64>(1)?,
|
|
row.get::<_, String>(2)?,
|
|
row.get::<_, Vec<u8>>(3)?,
|
|
))
|
|
})?;
|
|
let mut out = Vec::new();
|
|
for row in rows {
|
|
let (id, friend_id, dir, blob) = row?;
|
|
let aad = message_aad(friend_id, &dir, id);
|
|
let plaintext = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad)
|
|
.map_err(|_| Error("message decrypt failed".into()))?;
|
|
out.push(Message { id, dir, plaintext });
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
/// Queue one already-stored chat message for retry. `next_attempt_at` is an
|
|
/// absolute unix second; `now` is used for created_at/updated_at so the
|
|
/// caller and the row agree on the clock.
|
|
pub fn enqueue_outbox(
|
|
&self,
|
|
friend_pk: &[u8],
|
|
message_id: i64,
|
|
attempts: u32,
|
|
next_attempt_at: i64,
|
|
last_error: &str,
|
|
now: i64,
|
|
) -> Result<i64> {
|
|
let friend_id: i64 = self
|
|
.conn
|
|
.query_row(
|
|
"SELECT id FROM friends WHERE pubkey = ?1",
|
|
params![friend_pk],
|
|
|row| row.get(0),
|
|
)
|
|
.map_err(|_| Error("friend not found".into()))?;
|
|
self.conn.execute(
|
|
"INSERT INTO outbox (friend_id, message_id, attempts, next_attempt_at, status, last_error, created_at, updated_at)
|
|
VALUES (?1, ?2, ?3, ?4, 'queued', ?5, ?6, ?6)",
|
|
params![friend_id, message_id, attempts, next_attempt_at, last_error, now],
|
|
)?;
|
|
Ok(self.conn.last_insert_rowid())
|
|
}
|
|
|
|
/// Queue one already-stored chat message for retry, with the exact bytes to
|
|
/// put on the wire. Chat uses this: the frame is encoded once, before the
|
|
/// first attempt, and every retry re-sends these bytes, so a retried
|
|
/// message cannot arrive as a second chat line under a new key.
|
|
///
|
|
/// Narrower than [`Self::enqueue_outbox`] on purpose: a payload row is only
|
|
/// ever queued by the first attempt failing, so it is created at
|
|
/// `attempts = 1` and takes no attempt count.
|
|
pub fn enqueue_outbox_payload(
|
|
&self,
|
|
friend_pk: &[u8],
|
|
message_id: i64,
|
|
payload: &[u8],
|
|
next_attempt_at: i64,
|
|
last_error: &str,
|
|
now: i64,
|
|
) -> Result<i64> {
|
|
let friend_id: i64 = self
|
|
.conn
|
|
.query_row(
|
|
"SELECT id FROM friends WHERE pubkey = ?1",
|
|
params![friend_pk],
|
|
|row| row.get(0),
|
|
)
|
|
.map_err(|_| Error("friend not found".into()))?;
|
|
self.conn.execute(
|
|
"INSERT INTO outbox (friend_id, message_id, attempts, next_attempt_at, status, last_error, created_at, updated_at, payload)
|
|
VALUES (?1, ?2, 1, ?3, 'queued', ?4, ?5, ?5, ?6)",
|
|
params![friend_id, message_id, next_attempt_at, last_error, now, payload],
|
|
)?;
|
|
Ok(self.conn.last_insert_rowid())
|
|
}
|
|
|
|
/// Rows whose backoff has elapsed: the timer trigger for the worker.
|
|
pub fn due_outbox(&self, now: i64, limit: i64) -> Result<Vec<OutboxEntry>> {
|
|
self.outbox_query(
|
|
&format!(
|
|
"{OUTBOX_SELECT} WHERE o.status = 'queued' AND o.next_attempt_at <= ?1
|
|
ORDER BY o.next_attempt_at, o.id LIMIT ?2"
|
|
),
|
|
params![now, limit],
|
|
)
|
|
}
|
|
|
|
/// Unscheduleable rows for one friend (queued or mid-attempt): the
|
|
/// "we just heard from this peer" trigger, which ignores the backoff.
|
|
pub fn outbox_for_friend(&self, friend_pk: &[u8]) -> Result<Vec<OutboxEntry>> {
|
|
self.outbox_query(
|
|
&format!(
|
|
"{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending')
|
|
ORDER BY o.id"
|
|
),
|
|
params![friend_pk],
|
|
)
|
|
}
|
|
|
|
/// Every row the worker may still try: the unlock/foreground trigger.
|
|
pub fn all_pending_outbox(&self, limit: i64) -> Result<Vec<OutboxEntry>> {
|
|
self.outbox_query(
|
|
&format!(
|
|
"{OUTBOX_SELECT} WHERE o.status IN ('queued','sending')
|
|
ORDER BY o.next_attempt_at, o.id LIMIT ?1"
|
|
),
|
|
params![limit],
|
|
)
|
|
}
|
|
|
|
/// Pending and failed rows for one friend — what a UI shows as not-yet-sent.
|
|
/// Delivered rows are deleted, so absence means "sent".
|
|
pub fn pending_outbox(&self, friend_pk: &[u8]) -> Result<Vec<OutboxEntry>> {
|
|
self.outbox_query(
|
|
&format!(
|
|
"{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending','failed')
|
|
ORDER BY o.id"
|
|
),
|
|
params![friend_pk],
|
|
)
|
|
}
|
|
|
|
pub fn outbox_status_of_message(&self, message_id: i64) -> Result<Option<OutboxStatus>> {
|
|
let row: Option<(String, Option<String>)> = self
|
|
.conn
|
|
.query_row(
|
|
"SELECT status, last_error FROM outbox WHERE message_id = ?1 ORDER BY id DESC LIMIT 1",
|
|
params![message_id],
|
|
|r| Ok((r.get(0)?, r.get(1)?)),
|
|
)
|
|
.optional()?;
|
|
Ok(row.map(|(s, e)| OutboxStatus::from_db(&s, e.as_deref())))
|
|
}
|
|
|
|
pub fn mark_outbox_sending(&self, id: i64, now: i64) -> Result<()> {
|
|
self.conn.execute(
|
|
"UPDATE outbox SET status = 'sending', updated_at = ?1 WHERE id = ?2",
|
|
params![now, id],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Delivered. The row is dropped — the chat history is the record, and a
|
|
/// per-message status table would grow without bound.
|
|
pub fn mark_outbox_sent(&self, id: i64) -> Result<()> {
|
|
self.conn
|
|
.execute("DELETE FROM outbox WHERE id = ?1", params![id])?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn mark_outbox_failed(&self, id: i64, now: i64, why: &str) -> Result<()> {
|
|
self.conn.execute(
|
|
"UPDATE outbox SET status = 'failed', last_error = ?1, updated_at = ?2 WHERE id = ?3",
|
|
params![why, now, id],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn mark_outbox_retry(
|
|
&self,
|
|
id: i64,
|
|
attempts: u32,
|
|
next_attempt_at: i64,
|
|
now: i64,
|
|
why: &str,
|
|
) -> Result<()> {
|
|
self.conn.execute(
|
|
"UPDATE outbox SET status = 'queued', attempts = ?1, next_attempt_at = ?2, last_error = ?3, updated_at = ?4 WHERE id = ?5",
|
|
params![attempts, next_attempt_at, why, now, id],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// A row left in 'sending' means we died mid-attempt. Requeue on unlock.
|
|
pub fn reset_sending_outbox(&self) -> Result<usize> {
|
|
let n = self.conn.execute(
|
|
"UPDATE outbox SET status = 'queued' WHERE status = 'sending'",
|
|
[],
|
|
)?;
|
|
Ok(n)
|
|
}
|
|
|
|
/// The persisted Double Ratchet state for one peer, exactly as
|
|
/// `RatchetState::to_bytes` wrote it. Opaque here: the store never parses or
|
|
/// re-serializes it, so a state-format change stays a `src/ratchet.rs`
|
|
/// concern. `Ok(None)` means no session yet, not a failure.
|
|
pub fn load_ratchet(&self, friend_pk: &[u8]) -> Result<Option<Vec<u8>>> {
|
|
let state = self
|
|
.conn
|
|
.query_row(
|
|
"SELECT r.state FROM ratchet_sessions r
|
|
JOIN friends f ON f.id = r.friend_id
|
|
WHERE f.pubkey = ?1",
|
|
params![friend_pk],
|
|
|row| row.get::<_, Vec<u8>>(0),
|
|
)
|
|
.optional()?;
|
|
Ok(state)
|
|
}
|
|
|
|
/// Upsert the session blob for one peer, stamping `updated_at`.
|
|
pub fn save_ratchet(&self, friend_pk: &[u8], state: &[u8]) -> Result<()> {
|
|
let friend_id: i64 = self
|
|
.conn
|
|
.query_row(
|
|
"SELECT id FROM friends WHERE pubkey = ?1",
|
|
params![friend_pk],
|
|
|row| row.get(0),
|
|
)
|
|
.map_err(|_| Error("friend not found".into()))?;
|
|
self.conn.execute(
|
|
"INSERT INTO ratchet_sessions (friend_id, state, updated_at) VALUES (?1, ?2, ?3)
|
|
ON CONFLICT(friend_id) DO UPDATE SET
|
|
state = excluded.state, updated_at = excluded.updated_at",
|
|
params![friend_id, state, unix_now()],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Forget the session: a peer prekey change or an explicit reset. A missing
|
|
/// row is a no-op.
|
|
pub fn clear_ratchet(&self, friend_pk: &[u8]) -> Result<()> {
|
|
self.conn.execute(
|
|
"DELETE FROM ratchet_sessions WHERE friend_id IN
|
|
(SELECT id FROM friends WHERE pubkey = ?1)",
|
|
params![friend_pk],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
fn outbox_query(&self, sql: &str, args: &[&dyn rusqlite::ToSql]) -> Result<Vec<OutboxEntry>> {
|
|
let mut stmt = self.conn.prepare(sql)?;
|
|
let rows = stmt.query_map(args, |row| {
|
|
Ok((
|
|
row.get::<_, i64>(0)?,
|
|
row.get::<_, Vec<u8>>(1)?,
|
|
row.get::<_, i64>(2)?,
|
|
row.get::<_, i64>(3)?,
|
|
row.get::<_, i64>(4)?,
|
|
row.get::<_, String>(5)?,
|
|
row.get::<_, Option<String>>(6)?,
|
|
row.get::<_, i64>(7)?,
|
|
row.get::<_, i64>(8)?,
|
|
row.get::<_, String>(9)?,
|
|
row.get::<_, Vec<u8>>(10)?,
|
|
row.get::<_, Option<Vec<u8>>>(11)?,
|
|
))
|
|
})?;
|
|
let mut out = Vec::new();
|
|
for row in rows {
|
|
let (
|
|
id,
|
|
friend_pk,
|
|
message_id,
|
|
attempts,
|
|
next_attempt_at,
|
|
status,
|
|
last_error,
|
|
created_at,
|
|
m_friend_id,
|
|
dir,
|
|
blob,
|
|
payload,
|
|
) = row?;
|
|
let aad = message_aad(m_friend_id, &dir, message_id);
|
|
let body = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad)
|
|
.map_err(|_| Error("outbox body decrypt failed".into()))?;
|
|
out.push(OutboxEntry {
|
|
id,
|
|
friend_pk,
|
|
message_id,
|
|
body,
|
|
payload,
|
|
attempts: attempts as u32,
|
|
next_attempt_at,
|
|
created_at,
|
|
status: OutboxStatus::from_db(&status, last_error.as_deref()),
|
|
last_error,
|
|
});
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
/// Fold the WAL into the main db file and truncate it.
|
|
///
|
|
/// Runs on this store's own keyed connection: a second, unkeyed connection
|
|
/// cannot even read a SQLCipher store (`SQLITE_NOTADB`), so the checkpoint
|
|
/// has to happen here, not from `node.rs`.
|
|
///
|
|
/// Best effort on purpose: WAL replay on open recovers everything committed,
|
|
/// so this is about leaving less to replay (and less on disk) if the process
|
|
/// is killed right after teardown — not about correctness.
|
|
pub fn checkpoint_wal(&self) -> Result<()> {
|
|
let (busy, log, checkpointed): (i64, i64, i64) =
|
|
self.conn
|
|
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
|
|
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
|
|
})?;
|
|
if busy != 0 {
|
|
// Another connection is reading/writing: pages are still safe in the
|
|
// WAL, they just were not moved this time.
|
|
return Err(Error(format!(
|
|
"busy ({checkpointed}/{log} pages moved, another connection active)"
|
|
)));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Drop chat + payments history. Identity + friends stay.
|
|
///
|
|
/// Ratchet sessions are deliberately left alone: wiping chat history is not
|
|
/// a session reset, and silently resetting would break decryption against a
|
|
/// peer that still holds the old state.
|
|
/// Not a forensic erase: SSD wear-leveling can keep copies.
|
|
pub fn wipe_messages(&self) -> Result<()> {
|
|
self.conn.execute("DELETE FROM outbox", [])?;
|
|
self.conn.execute(
|
|
"UPDATE messages SET plaintext = zeroblob(length(plaintext))",
|
|
[],
|
|
)?;
|
|
self.conn.execute("DELETE FROM messages", [])?;
|
|
self.conn.execute("DELETE FROM payments", [])?;
|
|
self.conn.execute_batch("VACUUM")?;
|
|
self.checkpoint_wal()?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Delete the data dir. Next `open_at` is a new identity. Caller must drop Store first.
|
|
pub fn wipe_all(home: &Path) -> Result<()> {
|
|
if home.exists() {
|
|
fs::remove_dir_all(home)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
fn payment_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Payment> {
|
|
Ok(Payment {
|
|
id: row.get(0)?,
|
|
dir: row.get(1)?,
|
|
kind: row.get(2)?,
|
|
amount_atomic: row.get(3)?,
|
|
address: row.get(4)?,
|
|
memo: row.get(5)?,
|
|
txid: row.get(6)?,
|
|
verified: row.get::<_, i64>(7)? != 0,
|
|
created_at: row.get(8)?,
|
|
})
|
|
}
|
|
|
|
fn profile_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<FriendProfile> {
|
|
Ok(FriendProfile {
|
|
display_name: row.get(0)?,
|
|
bio: row.get(1)?,
|
|
xmr_addr: row.get(2)?,
|
|
updated_at: row.get(3)?,
|
|
})
|
|
}
|
|
|
|
fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Friend> {
|
|
Ok(Friend {
|
|
pubkey: row.get(0)?,
|
|
fingerprint: row.get(1)?,
|
|
petname: row.get(2)?,
|
|
onion: row.get(3)?,
|
|
last_connect_ok: row.get::<_, i64>(4)? != 0,
|
|
prekey: row.get(5)?,
|
|
})
|
|
}
|
|
|
|
fn gen_prekey() -> (Zeroizing<Vec<u8>>, Vec<u8>) {
|
|
let sk = StaticSecret::random_from_rng(OsRng);
|
|
let pk = X25519Public::from(&sk);
|
|
(
|
|
Zeroizing::new(sk.to_bytes().to_vec()),
|
|
pk.to_bytes().to_vec(),
|
|
)
|
|
}
|
|
|
|
/// Per-install KDF salt for the whole-database key. Not secret (a salt never
|
|
/// is); kept in the data dir so the db key never has to live inside the db it
|
|
/// opens.
|
|
const SALT_FILE: &str = "store_salt";
|
|
const SQLITE_HEADER: &[u8] = b"SQLite format 3\0";
|
|
|
|
enum DbState {
|
|
Missing,
|
|
Empty,
|
|
Plaintext,
|
|
Encrypted,
|
|
}
|
|
|
|
fn db_state(path: &Path) -> Result<DbState> {
|
|
let meta = match fs::metadata(path) {
|
|
Ok(m) => m,
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(DbState::Missing),
|
|
Err(e) => return Err(e.into()),
|
|
};
|
|
if meta.len() == 0 {
|
|
return Ok(DbState::Empty);
|
|
}
|
|
let mut head = [0u8; 16];
|
|
let mut f = fs::File::open(path)?;
|
|
match f.read_exact(&mut head) {
|
|
Ok(()) if head.as_slice() == SQLITE_HEADER => Ok(DbState::Plaintext),
|
|
Ok(()) => Ok(DbState::Encrypted),
|
|
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(DbState::Encrypted),
|
|
Err(e) => Err(e.into()),
|
|
}
|
|
}
|
|
|
|
fn read_salt(path: &Path) -> Result<Option<[u8; 16]>> {
|
|
match fs::read(path) {
|
|
Ok(b) if b.len() == 16 => Ok(Some(b.try_into().expect("len checked"))),
|
|
Ok(b) => Err(Error(format!("{SALT_FILE} has {} bytes, want 16", b.len()))),
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
|
Err(e) => Err(e.into()),
|
|
}
|
|
}
|
|
|
|
fn write_salt(path: &Path, salt: &[u8; 16]) -> Result<()> {
|
|
fs::write(path, salt)?;
|
|
let mut perms = fs::metadata(path)?.permissions();
|
|
perms.set_mode(0o600);
|
|
fs::set_permissions(path, perms)?;
|
|
Ok(())
|
|
}
|
|
|
|
fn random_salt() -> [u8; 16] {
|
|
let mut salt = [0u8; 16];
|
|
OsRng.fill_bytes(&mut salt);
|
|
salt
|
|
}
|
|
|
|
/// Opens the store, creating it encrypted and upgrading a v0.2.1 plaintext
|
|
/// file in place. Any failure before the swap leaves the old file untouched.
|
|
fn open_store_db(home: &Path, db_path: &Path, passphrase: &str) -> Result<Connection> {
|
|
let salt_path = home.join(SALT_FILE);
|
|
let mut salt = read_salt(&salt_path)?;
|
|
match db_state(db_path)? {
|
|
DbState::Plaintext => {
|
|
let conn = Connection::open(db_path)?;
|
|
let ok = wrapped_key_opens(&conn, passphrase)?;
|
|
drop(conn);
|
|
if !ok {
|
|
return Err(Error("wrong passphrase".into()));
|
|
}
|
|
let s = salt.unwrap_or_else(random_salt);
|
|
let key = crate::backup::kdf(passphrase, &s)?;
|
|
write_salt(&salt_path, &s)?;
|
|
migrate_plaintext_to_encrypted(db_path, &key, passphrase)?;
|
|
salt = Some(s);
|
|
}
|
|
DbState::Missing | DbState::Empty => {
|
|
if salt.is_none() {
|
|
let s = random_salt();
|
|
write_salt(&salt_path, &s)?;
|
|
salt = Some(s);
|
|
}
|
|
}
|
|
DbState::Encrypted => {}
|
|
}
|
|
let Some(salt) = salt else {
|
|
return Err(Error(format!(
|
|
"{SALT_FILE} is missing next to an encrypted onionwire.db; restore it from \
|
|
your backup, or restore the db from backup and re-import"
|
|
)));
|
|
};
|
|
let key = crate::backup::kdf(passphrase, &salt)?;
|
|
open_keyed(db_path, &key)
|
|
}
|
|
|
|
/// SQLCipher `PRAGMA key` with the raw-key form: the 32-byte Argon2id output is
|
|
/// the key, with no second KDF pass over it.
|
|
fn open_keyed(db_path: &Path, key: &[u8; 32]) -> Result<Connection> {
|
|
let conn = Connection::open(db_path)?;
|
|
conn.execute_batch(pragma_key(key).as_str())?;
|
|
// A rejected key otherwise logs SQLCipher's internal "hmac check failed"
|
|
// at ERROR to stderr. A wrong passphrase is a normal user error here.
|
|
let _ = conn.execute_batch("PRAGMA cipher_log_level = NONE");
|
|
// Force a read so a wrong key fails here, not on the first later query.
|
|
conn.query_row("SELECT count(*) FROM sqlite_master", [], |r| {
|
|
r.get::<_, i64>(0)
|
|
})
|
|
.map_err(|_| Error("wrong passphrase or corrupt store".into()))?;
|
|
Ok(conn)
|
|
}
|
|
|
|
/// SQLCipher's key material as hex inside the pragma text. The `String` holds
|
|
/// the database key, so it wipes on drop.
|
|
fn pragma_key(key: &[u8; 32]) -> Zeroizing<String> {
|
|
Zeroizing::new(format!("PRAGMA key = \"x'{hex}'\"", hex = fingerprint(key)))
|
|
}
|
|
|
|
/// True when `passphrase` unwraps `store_meta`. An empty `store_meta` (fresh
|
|
/// store) accepts any passphrase, matching the v0.2.1 behaviour.
|
|
fn wrapped_key_opens(conn: &Connection, passphrase: &str) -> Result<bool> {
|
|
let row: Option<(Vec<u8>, Vec<u8>)> = conn
|
|
.query_row(
|
|
"SELECT kdf_salt, wrapped_key FROM store_meta WHERE id = 1",
|
|
[],
|
|
|r| Ok((r.get(0)?, r.get(1)?)),
|
|
)
|
|
.optional()?;
|
|
let Some((salt, wrapped)) = row else {
|
|
return Ok(true);
|
|
};
|
|
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
|
|
Ok(crate::backup::aead_decrypt(&wrap_key, &wrapped, b"").is_ok())
|
|
}
|
|
|
|
/// Rewrites a plaintext sqlite store as an encrypted one and swaps it in.
|
|
/// The source file is only replaced after the new file opens, passes
|
|
/// `integrity_check` and unlocks with this passphrase.
|
|
fn migrate_plaintext_to_encrypted(db_path: &Path, key: &[u8; 32], passphrase: &str) -> Result<()> {
|
|
let mut tmp_name = db_path.as_os_str().to_owned();
|
|
tmp_name.push(".migrating");
|
|
let tmp = PathBuf::from(tmp_name);
|
|
let _ = fs::remove_file(&tmp);
|
|
let mode = fs::metadata(db_path)?.permissions().mode() & 0o777;
|
|
|
|
{
|
|
// Fold the WAL in so the export sees every committed row.
|
|
let conn = Connection::open(db_path)?;
|
|
let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
let target = tmp.to_string_lossy().replace('\'', "''");
|
|
let attach = Zeroizing::new(format!(
|
|
"ATTACH DATABASE '{target}' AS enc KEY \"x'{hex}'\";",
|
|
hex = fingerprint(key)
|
|
));
|
|
conn.execute_batch(attach.as_str())?;
|
|
conn.execute_batch("SELECT sqlcipher_export('enc');")?;
|
|
conn.execute_batch("DETACH DATABASE enc;")?;
|
|
}
|
|
|
|
let verified = (|| -> Result<()> {
|
|
let conn = open_keyed(&tmp, key)?;
|
|
let check: String = conn.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
|
|
if check != "ok" {
|
|
return Err(Error(format!("migration integrity_check: {check}")));
|
|
}
|
|
if !wrapped_key_opens(&conn, passphrase)? {
|
|
return Err(Error("migrated store failed to unlock".into()));
|
|
}
|
|
Ok(())
|
|
})();
|
|
if let Err(e) = verified {
|
|
let _ = fs::remove_file(&tmp);
|
|
return Err(e);
|
|
}
|
|
|
|
fs::rename(&tmp, db_path)?;
|
|
let mut perms = fs::metadata(db_path)?.permissions();
|
|
perms.set_mode(mode);
|
|
fs::set_permissions(db_path, perms)?;
|
|
for suffix in ["-wal", "-shm"] {
|
|
let mut stale = db_path.as_os_str().to_owned();
|
|
stale.push(suffix);
|
|
let _ = fs::remove_file(PathBuf::from(stale));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn home_dir() -> Result<PathBuf> {
|
|
if let Some(p) = std::env::var_os("ONIONWIRE_HOME") {
|
|
return Ok(PathBuf::from(p));
|
|
}
|
|
let home = std::env::var_os("HOME").ok_or_else(|| Error("HOME not set".into()))?;
|
|
Ok(PathBuf::from(home).join(".local/share/onionwire"))
|
|
}
|
|
|
|
fn passphrase_from_env() -> Result<Zeroizing<String>> {
|
|
match std::env::var("ONIONWIRE_STORE_PASSPHRASE") {
|
|
Ok(p) if p.is_empty() => Err(Error("empty passphrase".into())),
|
|
Ok(p) => Ok(Zeroizing::new(p)),
|
|
Err(_) => Err(Error("ONIONWIRE_STORE_PASSPHRASE required".into())),
|
|
}
|
|
}
|
|
|
|
/// Env `ONIONWIRE_STORE_PASSPHRASE` if set (non-empty). Otherwise `read_secret`
|
|
/// (TTY, no echo). Empty values fail closed. The passphrase is wiped on drop.
|
|
pub fn resolve_store_passphrase(
|
|
read_secret: impl FnOnce(&str) -> std::io::Result<String>,
|
|
) -> Result<Zeroizing<String>> {
|
|
match std::env::var("ONIONWIRE_STORE_PASSPHRASE") {
|
|
Ok(p) if p.is_empty() => Err(Error("empty passphrase".into())),
|
|
Ok(p) => Ok(Zeroizing::new(p)),
|
|
Err(_) => {
|
|
let s = read_secret("onionwire: store passphrase: ")?;
|
|
let s = s.trim_end_matches(['\n', '\r']).to_string();
|
|
if s.is_empty() {
|
|
Err(Error("empty passphrase".into()))
|
|
} else {
|
|
Ok(Zeroizing::new(s))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn mkdir_700(path: &Path) -> Result<()> {
|
|
fs::create_dir_all(path)?;
|
|
let mut perms = fs::metadata(path)?.permissions();
|
|
perms.set_mode(0o700);
|
|
fs::set_permissions(path, perms)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Base projection for outbox rows: the body comes from the `messages` row the
|
|
/// outbox row points at, so it stays under that row's AEAD + AAD.
|
|
const OUTBOX_SELECT: &str = "SELECT o.id, f.pubkey, o.message_id, o.attempts, o.next_attempt_at, \
|
|
o.status, o.last_error, o.created_at, m.friend_id, m.dir, m.plaintext, o.payload \
|
|
FROM outbox o JOIN friends f ON f.id = o.friend_id JOIN messages m ON m.id = o.message_id";
|
|
|
|
/// AAD: `owmsg1` || friend_id_le64 || dir || 0x00 || row_id_le64
|
|
fn message_aad(friend_id: i64, dir: &str, row_id: i64) -> Vec<u8> {
|
|
let mut aad = Vec::with_capacity(6 + 8 + dir.len() + 1 + 8);
|
|
aad.extend_from_slice(b"owmsg1");
|
|
aad.extend_from_slice(&friend_id.to_le_bytes());
|
|
aad.extend_from_slice(dir.as_bytes());
|
|
aad.push(0);
|
|
aad.extend_from_slice(&row_id.to_le_bytes());
|
|
aad
|
|
}
|
|
|
|
fn unix_now() -> i64 {
|
|
SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.map(|d| d.as_secs() as i64)
|
|
.unwrap_or(0)
|
|
}
|
|
|
|
/// 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";
|
|
|
|
/// AAD for the sealed remote-mode wallet config row. Same reasoning as the
|
|
/// wallet-child AAD: one store key, many domains.
|
|
const WALLET_CONFIG_AAD: &[u8] = b"onionwire/wallet-config/v1";
|
|
|
|
fn fingerprint(pubkey: &[u8]) -> String {
|
|
pubkey.iter().map(|b| format!("{b:02x}")).collect()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod at_rest {
|
|
use super::*;
|
|
use zeroize::Zeroize;
|
|
|
|
/// `Node::shutdown`/`flush` checkpoint the WAL through this method, so it has
|
|
/// to run on the store's own keyed connection: a second, unkeyed one cannot
|
|
/// read a SQLCipher file at all (`SQLITE_NOTADB`) and the truncation silently
|
|
/// never happened.
|
|
#[test]
|
|
fn checkpoint_wal_truncates_an_encrypted_store_wal() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let store = Store::open_at_with_passphrase(dir.path(), "checkpoint-pass").unwrap();
|
|
let pk = [3u8; 32];
|
|
store.upsert_friend(&pk, "peer.onion", None).unwrap();
|
|
for _ in 0..64 {
|
|
store.append_message(&pk, "out", &[7u8; 512]).unwrap();
|
|
}
|
|
|
|
let wal = dir.path().join("onionwire.db-wal");
|
|
let before = std::fs::metadata(&wal).expect("wal file").len();
|
|
assert!(before > 0, "expected pending WAL frames, got {before}");
|
|
|
|
store.checkpoint_wal().expect("checkpoint");
|
|
|
|
let after = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0);
|
|
assert_eq!(after, 0, "WAL not truncated ({before} bytes before)");
|
|
|
|
// A checkpoint moves pages into the db; it never drops committed data.
|
|
assert_eq!(store.list_messages(&pk).unwrap().len(), 64);
|
|
}
|
|
|
|
#[test]
|
|
fn store_data_key_is_a_zeroizing_wrapper_that_wipes() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let mut store = Store::open_at_with_passphrase(dir.path(), "zeroize-pass").unwrap();
|
|
|
|
// Type-level: the field is `Zeroizing<[u8; 32]>`, so its Drop wipes it.
|
|
let _: &Zeroizing<[u8; 32]> = &store.msg_key;
|
|
let before = *store.msg_key;
|
|
assert_ne!(before, [0u8; 32], "store has no data key");
|
|
|
|
store.msg_key.zeroize();
|
|
assert_eq!(*store.msg_key, [0u8; 32], "store data key not wiped");
|
|
}
|
|
|
|
#[test]
|
|
fn swapped_ciphertext_does_not_show_other_friends_body() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let store = Store::open_at_with_passphrase(dir.path(), "aad-pass").unwrap();
|
|
let alice = [1u8; 32];
|
|
let bob = [2u8; 32];
|
|
store.upsert_friend(&alice, "a.onion", None).unwrap();
|
|
store.upsert_friend(&bob, "b.onion", None).unwrap();
|
|
store
|
|
.append_message(&alice, "out", b"secret-for-alice")
|
|
.unwrap();
|
|
store
|
|
.append_message(&bob, "out", b"secret-for-bob")
|
|
.unwrap();
|
|
|
|
let blobs: Vec<(i64, Vec<u8>)> = {
|
|
let mut stmt = store
|
|
.conn
|
|
.prepare("SELECT id, plaintext FROM messages ORDER BY id")
|
|
.unwrap();
|
|
stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))
|
|
.unwrap()
|
|
.collect::<rusqlite::Result<Vec<_>>>()
|
|
.unwrap()
|
|
};
|
|
assert_eq!(blobs.len(), 2);
|
|
store
|
|
.conn
|
|
.execute(
|
|
"UPDATE messages SET plaintext = ?1 WHERE id = ?2",
|
|
params![&blobs[1].1, blobs[0].0],
|
|
)
|
|
.unwrap();
|
|
store
|
|
.conn
|
|
.execute(
|
|
"UPDATE messages SET plaintext = ?1 WHERE id = ?2",
|
|
params![&blobs[0].1, blobs[1].0],
|
|
)
|
|
.unwrap();
|
|
|
|
if let Ok(msgs) = store.list_messages(&alice) {
|
|
assert!(
|
|
msgs.iter()
|
|
.all(|m| m.plaintext.as_slice() != b"secret-for-bob"),
|
|
"alice saw bob's body after ciphertext swap"
|
|
);
|
|
}
|
|
if let Ok(msgs) = store.list_messages(&bob) {
|
|
assert!(
|
|
msgs.iter()
|
|
.all(|m| m.plaintext.as_slice() != b"secret-for-alice"),
|
|
"bob saw alice's body after ciphertext swap"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn empty_aad_rows_rewrap_on_unlock_then_swap_fails() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let store = Store::open_at_with_passphrase(dir.path(), "rewrap-pass").unwrap();
|
|
let alice = [1u8; 32];
|
|
let bob = [2u8; 32];
|
|
store.upsert_friend(&alice, "a.onion", None).unwrap();
|
|
store.upsert_friend(&bob, "b.onion", None).unwrap();
|
|
store
|
|
.append_message(&alice, "out", b"secret-for-alice")
|
|
.unwrap();
|
|
store
|
|
.append_message(&bob, "out", b"secret-for-bob")
|
|
.unwrap();
|
|
let ids: Vec<i64> = {
|
|
let mut stmt = store
|
|
.conn
|
|
.prepare("SELECT id FROM messages ORDER BY id")
|
|
.unwrap();
|
|
stmt.query_map([], |r| r.get(0))
|
|
.unwrap()
|
|
.collect::<rusqlite::Result<Vec<_>>>()
|
|
.unwrap()
|
|
};
|
|
let a_blob = crate::backup::aead_encrypt(&store.msg_key, b"secret-for-alice", b"").unwrap();
|
|
let b_blob = crate::backup::aead_encrypt(&store.msg_key, b"secret-for-bob", b"").unwrap();
|
|
store
|
|
.conn
|
|
.execute(
|
|
"UPDATE messages SET plaintext = ?1 WHERE id = ?2",
|
|
params![a_blob, ids[0]],
|
|
)
|
|
.unwrap();
|
|
store
|
|
.conn
|
|
.execute(
|
|
"UPDATE messages SET plaintext = ?1 WHERE id = ?2",
|
|
params![b_blob, ids[1]],
|
|
)
|
|
.unwrap();
|
|
drop(store);
|
|
|
|
let store = Store::open_at_with_passphrase(dir.path(), "rewrap-pass").unwrap();
|
|
assert_eq!(
|
|
store.list_messages(&alice).unwrap()[0].plaintext,
|
|
b"secret-for-alice"
|
|
);
|
|
assert_eq!(
|
|
store.list_messages(&bob).unwrap()[0].plaintext,
|
|
b"secret-for-bob"
|
|
);
|
|
|
|
let blobs: Vec<(i64, Vec<u8>)> = {
|
|
let mut stmt = store
|
|
.conn
|
|
.prepare("SELECT id, plaintext FROM messages ORDER BY id")
|
|
.unwrap();
|
|
stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))
|
|
.unwrap()
|
|
.collect::<rusqlite::Result<Vec<_>>>()
|
|
.unwrap()
|
|
};
|
|
store
|
|
.conn
|
|
.execute(
|
|
"UPDATE messages SET plaintext = ?1 WHERE id = ?2",
|
|
params![&blobs[1].1, blobs[0].0],
|
|
)
|
|
.unwrap();
|
|
store
|
|
.conn
|
|
.execute(
|
|
"UPDATE messages SET plaintext = ?1 WHERE id = ?2",
|
|
params![&blobs[0].1, blobs[1].0],
|
|
)
|
|
.unwrap();
|
|
if let Ok(msgs) = store.list_messages(&alice) {
|
|
assert!(
|
|
msgs.iter()
|
|
.all(|m| m.plaintext.as_slice() != b"secret-for-bob"),
|
|
"alice saw bob's body after post-rewrap swap"
|
|
);
|
|
}
|
|
}
|
|
|
|
/// The exact v0.2.1 on-disk layout, hand-built: a plaintext sqlite file with
|
|
/// the identity row in the clear, a `store_meta` row holding the
|
|
/// Argon2id-wrapped message key and ChaCha20-Poly1305 message rows bound to
|
|
/// their row AAD. Pin it here so the migration test cannot drift with the
|
|
/// production schema.
|
|
const LEGACY_SCHEMA: &str = "
|
|
CREATE TABLE friends (
|
|
id INTEGER PRIMARY KEY,
|
|
pubkey BLOB NOT NULL UNIQUE,
|
|
fingerprint TEXT NOT NULL,
|
|
petname TEXT,
|
|
onion TEXT NOT NULL,
|
|
onion_updated_at INTEGER NOT NULL,
|
|
added_at INTEGER NOT NULL,
|
|
last_connect_ok INTEGER NOT NULL DEFAULT 1,
|
|
prekey BLOB NOT NULL DEFAULT x''
|
|
);
|
|
CREATE TABLE messages (
|
|
id INTEGER PRIMARY KEY,
|
|
friend_id INTEGER NOT NULL REFERENCES friends(id),
|
|
dir TEXT NOT NULL CHECK(dir IN ('in','out')),
|
|
plaintext BLOB NOT NULL,
|
|
created_at INTEGER NOT NULL
|
|
);
|
|
CREATE TABLE self (
|
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
identity_sk BLOB NOT NULL,
|
|
identity_pk BLOB NOT NULL,
|
|
onion TEXT NOT NULL,
|
|
onion_rotated_at INTEGER NOT NULL,
|
|
prekey_sk BLOB NOT NULL,
|
|
prekey_pk BLOB NOT NULL,
|
|
hs_nickname TEXT NOT NULL DEFAULT 'ow0'
|
|
);
|
|
CREATE TABLE self_profile (
|
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
display_name TEXT NOT NULL DEFAULT '',
|
|
bio TEXT NOT NULL DEFAULT '',
|
|
xmr_addr TEXT NOT NULL DEFAULT '',
|
|
updated_at INTEGER NOT NULL DEFAULT 0
|
|
);
|
|
CREATE TABLE friend_profiles (
|
|
pubkey BLOB PRIMARY KEY,
|
|
display_name TEXT NOT NULL,
|
|
bio TEXT NOT NULL,
|
|
xmr_addr TEXT NOT NULL DEFAULT '',
|
|
updated_at INTEGER NOT NULL
|
|
);
|
|
CREATE TABLE store_meta (
|
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
kdf_salt BLOB NOT NULL,
|
|
wrapped_key BLOB NOT NULL
|
|
);
|
|
CREATE TABLE payments (
|
|
id INTEGER PRIMARY KEY,
|
|
friend_id INTEGER NOT NULL REFERENCES friends(id),
|
|
dir TEXT NOT NULL CHECK(dir IN ('in','out')),
|
|
kind TEXT NOT NULL CHECK(kind IN ('invoice','receipt')),
|
|
amount_atomic TEXT NOT NULL,
|
|
address TEXT NOT NULL,
|
|
memo TEXT NOT NULL DEFAULT '',
|
|
txid TEXT,
|
|
verified INTEGER NOT NULL DEFAULT 0,
|
|
created_at INTEGER NOT NULL
|
|
);
|
|
INSERT OR IGNORE INTO self_profile (id) VALUES (1);
|
|
";
|
|
|
|
const LEGACY_IDENTITY_SK: [u8; 32] = [0x11; 32];
|
|
const LEGACY_FRIEND_PK: [u8; 32] = [0x55; 32];
|
|
|
|
/// Writes a v0.2.1 store at `db_path` with no encryption at all.
|
|
fn write_legacy_plaintext_store(db_path: &Path, passphrase: &str) {
|
|
let conn = Connection::open(db_path).unwrap();
|
|
conn.execute_batch(LEGACY_SCHEMA).unwrap();
|
|
conn.execute(
|
|
"INSERT INTO self (id, identity_sk, identity_pk, onion, onion_rotated_at, prekey_sk, prekey_pk, hs_nickname)
|
|
VALUES (1, ?1, ?2, 'legacy.onion', 7, ?3, ?4, 'ow0')",
|
|
params![
|
|
LEGACY_IDENTITY_SK.to_vec(),
|
|
vec![0x22u8; 32],
|
|
vec![0x33u8; 32],
|
|
vec![0x44u8; 32]
|
|
],
|
|
)
|
|
.unwrap();
|
|
conn.execute(
|
|
"INSERT INTO friends (pubkey, fingerprint, petname, onion, onion_updated_at, added_at, last_connect_ok, prekey)
|
|
VALUES (?1, ?2, 'legacy-friend', 'legacy-friend.onion', 7, 7, 1, x'')",
|
|
params![LEGACY_FRIEND_PK.as_slice(), fingerprint(&LEGACY_FRIEND_PK)],
|
|
)
|
|
.unwrap();
|
|
let mut salt = [0u8; 16];
|
|
OsRng.fill_bytes(&mut salt);
|
|
let mut data_key = Zeroizing::new([0u8; 32]);
|
|
OsRng.fill_bytes(&mut data_key[..]);
|
|
let wrap = crate::backup::kdf(passphrase, &salt).unwrap();
|
|
let wrapped = crate::backup::aead_encrypt(&wrap, &data_key[..], b"").unwrap();
|
|
conn.execute(
|
|
"INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)",
|
|
params![salt.as_slice(), wrapped],
|
|
)
|
|
.unwrap();
|
|
for (dir, body) in [("in", "legacy-body-xyz"), ("out", "legacy-reply-xyz")] {
|
|
conn.execute(
|
|
"INSERT INTO messages (friend_id, dir, plaintext, created_at) VALUES (1, ?1, x'', 7)",
|
|
params![dir],
|
|
)
|
|
.unwrap();
|
|
let id = conn.last_insert_rowid();
|
|
let blob =
|
|
crate::backup::aead_encrypt(&data_key, body.as_bytes(), &message_aad(1, dir, id))
|
|
.unwrap();
|
|
conn.execute(
|
|
"UPDATE messages SET plaintext = ?1 WHERE id = ?2",
|
|
params![blob, id],
|
|
)
|
|
.unwrap();
|
|
}
|
|
conn.close().unwrap();
|
|
}
|
|
|
|
fn file_has(path: &Path, needle: &[u8]) -> bool {
|
|
let Ok(bytes) = std::fs::read(path) else {
|
|
return false;
|
|
};
|
|
bytes.windows(needle.len()).any(|w| w == needle)
|
|
}
|
|
|
|
#[test]
|
|
fn plaintext_v0_2_1_store_is_encrypted_in_place_and_keeps_history() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("onionwire.db");
|
|
write_legacy_plaintext_store(&db_path, "legacy-pass");
|
|
let raw = std::fs::read(&db_path).unwrap();
|
|
assert!(
|
|
raw.starts_with(b"SQLite format 3\0"),
|
|
"fixture must be a plaintext sqlite file"
|
|
);
|
|
|
|
let store =
|
|
Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("open+upgrade");
|
|
assert_eq!(
|
|
store.self_identity().unwrap().identity_sk[..],
|
|
LEGACY_IDENTITY_SK[..]
|
|
);
|
|
let msgs = store.list_messages(&LEGACY_FRIEND_PK).unwrap();
|
|
assert_eq!(msgs.len(), 2, "history must survive the upgrade");
|
|
assert_eq!(msgs[0].plaintext, b"legacy-body-xyz");
|
|
assert_eq!(msgs[1].plaintext, b"legacy-reply-xyz");
|
|
assert_eq!(
|
|
store.get_friend(&LEGACY_FRIEND_PK).unwrap().unwrap().onion,
|
|
"legacy-friend.onion"
|
|
);
|
|
drop(store);
|
|
|
|
let enc = std::fs::read(&db_path).unwrap();
|
|
assert!(
|
|
!enc.starts_with(b"SQLite format 3\0"),
|
|
"db header must be encrypted after the in-place upgrade"
|
|
);
|
|
for (needle, what) in [
|
|
(b"legacy-body-xyz".to_vec(), "message body"),
|
|
(
|
|
fingerprint(&LEGACY_FRIEND_PK).into_bytes(),
|
|
"friend pubkey hex",
|
|
),
|
|
(LEGACY_IDENTITY_SK.to_vec(), "identity secret"),
|
|
(b"legacy-friend.onion".to_vec(), "locator"),
|
|
] {
|
|
assert!(
|
|
!file_has(&db_path, &needle),
|
|
"upgraded db still contains the {what}"
|
|
);
|
|
}
|
|
|
|
let store = Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("reopen");
|
|
assert_eq!(store.list_messages(&LEGACY_FRIEND_PK).unwrap().len(), 2);
|
|
}
|
|
|
|
#[test]
|
|
fn legacy_plaintext_store_with_wrong_passphrase_is_left_untouched() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("onionwire.db");
|
|
write_legacy_plaintext_store(&db_path, "legacy-pass");
|
|
let before = std::fs::read(&db_path).unwrap();
|
|
|
|
let err = match Store::open_at_with_passphrase(dir.path(), "wrong-pass") {
|
|
Ok(_) => panic!("wrong passphrase must not open a legacy store"),
|
|
Err(e) => e,
|
|
};
|
|
assert!(
|
|
err.to_string().to_ascii_lowercase().contains("passphrase"),
|
|
"got {err}"
|
|
);
|
|
assert_eq!(
|
|
std::fs::read(&db_path).unwrap(),
|
|
before,
|
|
"a failed legacy upgrade must not modify the plaintext db"
|
|
);
|
|
assert!(
|
|
!dir.path().join("store_salt").exists(),
|
|
"a failed legacy upgrade must not leave a salt file behind"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn first_unlock_reencrypts_legacy_plaintext_rows() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let store = Store::open_at_with_passphrase(dir.path(), "migrate-pass").unwrap();
|
|
let pk = [1u8; 32];
|
|
store.upsert_friend(&pk, "a.onion", None).unwrap();
|
|
store
|
|
.append_message(&pk, "out", b"legacy-plain-xyz")
|
|
.unwrap();
|
|
store.conn.execute("DELETE FROM store_meta", []).unwrap();
|
|
store
|
|
.conn
|
|
.execute(
|
|
"UPDATE messages SET plaintext = ?1",
|
|
params![b"legacy-plain-xyz".as_slice()],
|
|
)
|
|
.unwrap();
|
|
let _ = store.conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
drop(store);
|
|
|
|
let store = Store::open_at_with_passphrase(dir.path(), "migrate-pass").unwrap();
|
|
let msgs = store.list_messages(&pk).unwrap();
|
|
assert_eq!(msgs[0].plaintext, b"legacy-plain-xyz");
|
|
drop(store);
|
|
let needle = b"legacy-plain-xyz";
|
|
for name in ["onionwire.db", "onionwire.db-wal", "onionwire.db-shm"] {
|
|
let path = dir.path().join(name);
|
|
let Ok(bytes) = std::fs::read(&path) else {
|
|
continue;
|
|
};
|
|
assert!(
|
|
!bytes.windows(needle.len()).any(|w| w == needle),
|
|
"{name} still contains legacy plaintext"
|
|
);
|
|
}
|
|
}
|
|
|
|
/// The old `payments.kind` CHECK allowed only invoice/receipt, so every
|
|
/// `kind = "tip"` insert (inbound and outbound) failed the constraint.
|
|
/// Opening an existing store must widen it without losing the rows in it.
|
|
#[test]
|
|
fn a_store_predating_tip_payments_is_widened_on_open() {
|
|
const ADDR: &str = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge";
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("onionwire.db");
|
|
write_legacy_plaintext_store(&db_path, "tip-pass");
|
|
{
|
|
let conn = Connection::open(&db_path).unwrap();
|
|
let schema: String = conn
|
|
.query_row(
|
|
"SELECT sql FROM sqlite_master WHERE name = 'payments'",
|
|
[],
|
|
|r| r.get(0),
|
|
)
|
|
.unwrap();
|
|
assert!(!schema.contains("'tip'"), "fixture is the pre-tip table");
|
|
conn.execute(
|
|
"INSERT INTO payments (friend_id, dir, kind, amount_atomic, address, memo, txid, verified, created_at)
|
|
VALUES (1, 'out', 'invoice', '1000000000000', ?1, 'm', NULL, 0, 7)",
|
|
params![ADDR],
|
|
)
|
|
.unwrap();
|
|
}
|
|
|
|
let store = Store::open_at_with_passphrase(dir.path(), "tip-pass").expect("open+upgrade");
|
|
let rows = store.list_payments(&LEGACY_FRIEND_PK).unwrap();
|
|
assert_eq!(rows.len(), 1, "the pre-tip row survives the rebuild");
|
|
assert_eq!(rows[0].kind, "invoice");
|
|
assert_eq!(rows[0].amount_atomic, "1000000000000");
|
|
assert_eq!(rows[0].created_at, 7, "rows are copied verbatim");
|
|
|
|
store
|
|
.insert_payment(
|
|
&LEGACY_FRIEND_PK,
|
|
PaymentWrite {
|
|
dir: "in",
|
|
kind: "tip",
|
|
amount_atomic: "500000000000",
|
|
address: ADDR,
|
|
memo: "lunch",
|
|
txid: Some("abc123"),
|
|
verified: false,
|
|
},
|
|
)
|
|
.expect("a migrated store accepts the tip kind");
|
|
}
|
|
|
|
/// `ratchet_sessions` keys on `friend_id`, and nothing in the crate deletes
|
|
/// friends yet, so the cascade is exercised with the raw statement a future
|
|
/// friend-removal path would run.
|
|
#[test]
|
|
fn removing_a_friend_cascades_to_its_ratchet_row_and_wipe_messages_keeps_it() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let store = Store::open_at_with_passphrase(dir.path(), "cascade-pass").unwrap();
|
|
let foreign_keys: i64 = store
|
|
.conn
|
|
.query_row("PRAGMA foreign_keys", [], |row| row.get(0))
|
|
.unwrap();
|
|
assert_eq!(foreign_keys, 1, "ON DELETE CASCADE needs foreign_keys ON");
|
|
|
|
let pk = [0x21u8; 32];
|
|
store.upsert_friend(&pk, "peer.onion", None).unwrap();
|
|
store.save_ratchet(&pk, b"ratchet-state-blob").unwrap();
|
|
store.append_message(&pk, "out", b"hi").unwrap();
|
|
|
|
// Wiping chat history is not a session reset: the peer still holds the
|
|
// old ratchet state, so dropping ours would break its next frame.
|
|
store.wipe_messages().unwrap();
|
|
assert_eq!(
|
|
store.load_ratchet(&pk).unwrap().as_deref(),
|
|
Some(&b"ratchet-state-blob"[..]),
|
|
"wipe_messages must not clear ratchet state"
|
|
);
|
|
|
|
store
|
|
.conn
|
|
.execute(
|
|
"DELETE FROM friends WHERE pubkey = ?1",
|
|
params![pk.as_slice()],
|
|
)
|
|
.unwrap();
|
|
assert_eq!(
|
|
store.load_ratchet(&pk).unwrap(),
|
|
None,
|
|
"deleting the friend must take its ratchet row with it"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn ratchet_save_overwrites_the_row_and_bumps_updated_at() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let store = Store::open_at_with_passphrase(dir.path(), "upsert-pass").unwrap();
|
|
let pk = [0x22u8; 32];
|
|
store.upsert_friend(&pk, "peer.onion", None).unwrap();
|
|
store.save_ratchet(&pk, b"first-state").unwrap();
|
|
// Park the clock so the assertion cannot pass on an untouched row.
|
|
store
|
|
.conn
|
|
.execute("UPDATE ratchet_sessions SET updated_at = 0", [])
|
|
.unwrap();
|
|
|
|
store.save_ratchet(&pk, b"second-state-longer").unwrap();
|
|
|
|
assert_eq!(
|
|
store.load_ratchet(&pk).unwrap().as_deref(),
|
|
Some(&b"second-state-longer"[..])
|
|
);
|
|
let rows: i64 = store
|
|
.conn
|
|
.query_row("SELECT count(*) FROM ratchet_sessions", [], |row| {
|
|
row.get(0)
|
|
})
|
|
.unwrap();
|
|
assert_eq!(rows, 1, "save_ratchet upserts, it does not insert twice");
|
|
let updated_at: i64 = store
|
|
.conn
|
|
.query_row("SELECT updated_at FROM ratchet_sessions", [], |row| {
|
|
row.get(0)
|
|
})
|
|
.unwrap();
|
|
assert!(updated_at > 0, "save_ratchet must set updated_at");
|
|
}
|
|
|
|
/// The table is additive: a store written before this card existed gains it
|
|
/// from `CREATE TABLE IF NOT EXISTS` on the next open, with no data loss.
|
|
#[test]
|
|
fn store_predating_the_ratchet_table_gains_it_on_reopen() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let pk = [0x23u8; 32];
|
|
{
|
|
let store = Store::open_at_with_passphrase(dir.path(), "old-pass").unwrap();
|
|
store.upsert_friend(&pk, "peer.onion", None).unwrap();
|
|
store.append_message(&pk, "in", b"written-before").unwrap();
|
|
store
|
|
.conn
|
|
.execute_batch("DROP TABLE ratchet_sessions")
|
|
.unwrap();
|
|
}
|
|
|
|
let store = Store::open_at_with_passphrase(dir.path(), "old-pass").unwrap();
|
|
assert_eq!(
|
|
store.list_messages(&pk).unwrap()[0].plaintext,
|
|
b"written-before"
|
|
);
|
|
assert_eq!(store.load_ratchet(&pk).unwrap(), None);
|
|
store.save_ratchet(&pk, b"fresh-state").unwrap();
|
|
assert_eq!(
|
|
store.load_ratchet(&pk).unwrap().as_deref(),
|
|
Some(&b"fresh-state"[..])
|
|
);
|
|
}
|
|
|
|
/// The wallet-child RPC creds grant spend authority, so they are stored
|
|
/// sealed in the encrypted store — never as a plaintext file next to the
|
|
/// wallet, and never as a plaintext row.
|
|
#[test]
|
|
fn wallet_child_creds_round_trip_sealed_and_load_none_before_first_start() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let store = Store::open_at_with_passphrase(dir.path(), "child-pass").unwrap();
|
|
assert!(
|
|
store.load_wallet_child().unwrap().is_none(),
|
|
"a fresh store has no wallet-child config"
|
|
);
|
|
let cfg = r#"{"user":"owuser","pass":"ow-secret-pass-xyz","wallet_filename":"onionwire"}"#;
|
|
store.save_wallet_child(cfg).unwrap();
|
|
assert_eq!(store.load_wallet_child().unwrap().as_deref(), Some(cfg));
|
|
|
|
let sealed: Vec<u8> = store
|
|
.conn
|
|
.query_row("SELECT sealed FROM wallet_child WHERE id = 1", [], |r| {
|
|
r.get(0)
|
|
})
|
|
.unwrap();
|
|
assert_ne!(
|
|
sealed.as_slice(),
|
|
cfg.as_bytes(),
|
|
"row stored the creds as plaintext"
|
|
);
|
|
assert!(
|
|
!sealed.windows(11).any(|w| w == b"ow-secret-p".as_slice()),
|
|
"sealed row leaked the password"
|
|
);
|
|
|
|
// Re-sealing replaces the single row instead of stacking rows.
|
|
let cfg2 = r#"{"user":"owuser","pass":"second-pass-abc","wallet_filename":"onionwire"}"#;
|
|
store.save_wallet_child(cfg2).unwrap();
|
|
assert_eq!(store.load_wallet_child().unwrap().as_deref(), Some(cfg2));
|
|
let rows: i64 = store
|
|
.conn
|
|
.query_row("SELECT count(*) FROM wallet_child", [], |r| r.get(0))
|
|
.unwrap();
|
|
assert_eq!(rows, 1, "wallet_child must hold exactly one row");
|
|
|
|
store.checkpoint_wal().unwrap();
|
|
drop(store);
|
|
for name in ["onionwire.db", "onionwire.db-wal", "onionwire.db-shm"] {
|
|
let path = dir.path().join(name);
|
|
let Ok(bytes) = std::fs::read(&path) else {
|
|
continue;
|
|
};
|
|
for needle in [
|
|
b"second-pass-abc".as_slice(),
|
|
b"ow-secret-pass-xyz".as_slice(),
|
|
] {
|
|
assert!(
|
|
!bytes.windows(needle.len()).any(|w| w == needle),
|
|
"{name} contains the wallet-child password in the clear"
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|