use std::path::PathBuf;
use std::sync::Arc;
use moonproof_wallet::WalletError;
use moonproof_wallet::WalletSnapshot;
use redb::{Database, ReadableDatabase, ReadableTable, TableDefinition};
use tokio::sync::RwLock;
use crate::providers::disk_private_state::{open_or_share_database, PrivateStoragePassword};
use crate::providers::storage_encryption::{parse_envelope, Cipher, Salt};
pub(crate) const TABLE: TableDefinition<&[u8], &[u8]> =
TableDefinition::new("moonproof:wallet_snapshots");
const KEY_TAG_SNAPSHOT: &[u8] = b"snapshot";
pub struct WalletStoreConfig {
pub db_path: PathBuf,
pub account_id: String,
pub password: Arc<dyn PrivateStoragePassword>,
}
impl std::fmt::Debug for WalletStoreConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WalletStoreConfig")
.field("db_path", &self.db_path)
.field("account_id", &self.account_id)
.finish_non_exhaustive()
}
}
#[derive(Clone)]
pub struct WalletStore {
inner: Arc<Inner>,
}
struct Inner {
db: Arc<Database>,
account_hash: [u8; 16],
password: Arc<dyn PrivateStoragePassword>,
cipher_cache: RwLock<Option<CachedCipher>>,
}
#[derive(Clone)]
struct CachedCipher {
cipher: Cipher,
salt: Salt,
}
impl std::fmt::Debug for WalletStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WalletStore")
.field("account_hash", &hex::encode(self.inner.account_hash))
.finish_non_exhaustive()
}
}
impl WalletStore {
pub fn open(config: WalletStoreConfig) -> Result<Self, WalletError> {
if let Some(parent) = config.db_path.parent() {
if !parent.as_os_str().is_empty() {
std::fs::create_dir_all(parent)
.map_err(|e| WalletError::Serialization(format!("create_dir_all: {e}")))?;
}
}
let db = open_or_share_database(&config.db_path)
.map_err(|e| WalletError::Serialization(format!("open db: {e}")))?;
let write = db
.begin_write()
.map_err(|e| WalletError::Serialization(format!("begin_write init: {e}")))?;
{
let _ = write
.open_table(TABLE)
.map_err(|e| WalletError::Serialization(format!("open table init: {e}")))?;
}
write
.commit()
.map_err(|e| WalletError::Serialization(format!("commit init: {e}")))?;
let account_hash = hash_account_id(&config.account_id);
Ok(Self {
inner: Arc::new(Inner {
db,
account_hash,
password: config.password,
cipher_cache: RwLock::new(None),
}),
})
}
pub async fn save(&self, snapshot: &WalletSnapshot) -> Result<usize, WalletError> {
let inner = self.inner.clone();
let bytes = snapshot.to_bytes_compact()?;
run_blocking(move || {
let cached = inner.cipher_for_read_write()?;
let envelope = encrypt_value(&cached.cipher, &bytes);
let envelope_len = envelope.len();
let key = key_for(&inner.account_hash);
let write = inner
.db
.begin_write()
.map_err(|e| WalletError::Serialization(format!("begin_write save: {e}")))?;
{
let mut table = write
.open_table(TABLE)
.map_err(|e| WalletError::Serialization(format!("open table save: {e}")))?;
table
.insert(key.as_slice(), envelope.as_bytes())
.map_err(|e| WalletError::Serialization(format!("insert save: {e}")))?;
}
write
.commit()
.map_err(|e| WalletError::Serialization(format!("commit save: {e}")))?;
Ok(envelope_len)
})
.await
}
pub async fn load(&self) -> Result<Option<WalletSnapshot>, WalletError> {
let inner = self.inner.clone();
run_blocking(move || {
let cached = inner.cipher_for_read_write()?;
let key = key_for(&inner.account_hash);
let read = inner
.db
.begin_read()
.map_err(|e| WalletError::Serialization(format!("begin_read load: {e}")))?;
let table = read
.open_table(TABLE)
.map_err(|e| WalletError::Serialization(format!("open table load: {e}")))?;
let Some(value) = table
.get(key.as_slice())
.map_err(|e| WalletError::Serialization(format!("lookup load: {e}")))?
else {
return Ok(None);
};
let envelope = std::str::from_utf8(value.value())
.map_err(|_| WalletError::Serialization("non-utf8 envelope".to_owned()))?;
let plain = decrypt(&cached, envelope)?;
let snapshot = WalletSnapshot::from_bytes(&plain)?;
Ok(Some(snapshot))
})
.await
}
pub async fn clear(&self) -> Result<(), WalletError> {
let inner = self.inner.clone();
run_blocking(move || {
let key = key_for(&inner.account_hash);
let write = inner
.db
.begin_write()
.map_err(|e| WalletError::Serialization(format!("begin_write clear: {e}")))?;
{
let mut table = write
.open_table(TABLE)
.map_err(|e| WalletError::Serialization(format!("open table clear: {e}")))?;
table
.remove(key.as_slice())
.map_err(|e| WalletError::Serialization(format!("remove clear: {e}")))?;
}
write
.commit()
.map_err(|e| WalletError::Serialization(format!("commit clear: {e}")))?;
Ok(())
})
.await
}
}
impl Inner {
fn cipher_for_read_write(&self) -> Result<CachedCipher, WalletError> {
let current = |c: &CachedCipher| {
crate::providers::disk_private_state::salt_is_current(
&self.db,
&self.account_hash,
&c.salt,
)
.map_err(|e| WalletError::Serialization(format!("account salt: {e}")))
};
if let Some(c) = self.cipher_cache.blocking_read().as_ref() {
if current(c)? {
return Ok(c.clone());
}
}
let mut cache = self.cipher_cache.blocking_write();
if let Some(c) = cache.as_ref() {
if current(c)? {
return Ok(c.clone());
}
}
let pw = self
.password
.password()
.map_err(|e| WalletError::Serialization(format!("password provider: {e}")))?;
let (cipher, salt) =
crate::providers::disk_private_state::account_cipher(&self.db, &self.account_hash, &pw)
.map_err(|e| WalletError::Serialization(format!("account cipher: {e}")))?;
let copy = CachedCipher {
cipher: cipher.clone(),
salt,
};
*cache = Some(CachedCipher { cipher, salt });
Ok(copy)
}
}
async fn run_blocking<T, F>(f: F) -> Result<T, WalletError>
where
T: Send + 'static,
F: FnOnce() -> Result<T, WalletError> + Send + 'static,
{
tokio::task::spawn_blocking(f)
.await
.map_err(|e| WalletError::Serialization(format!("blocking task panic: {e}")))?
}
fn hash_account_id(s: &str) -> [u8; 16] {
use sha2::{Digest, Sha256};
let digest = Sha256::digest(s.as_bytes());
let mut out = [0u8; 16];
out.copy_from_slice(&digest[..16]);
out
}
fn key_for(account_hash: &[u8; 16]) -> Vec<u8> {
let mut k = Vec::with_capacity(16 + KEY_TAG_SNAPSHOT.len());
k.extend_from_slice(account_hash);
k.extend_from_slice(KEY_TAG_SNAPSHOT);
k
}
fn encrypt_value(cipher: &Cipher, plain_bytes: &[u8]) -> String {
let mut rng = rand::thread_rng();
let hex_payload = hex::encode(plain_bytes);
cipher.encrypt(&mut rng, &hex_payload)
}
fn decrypt(cached: &CachedCipher, envelope: &str) -> Result<Vec<u8>, WalletError> {
let parts = parse_envelope(envelope)
.map_err(|e| WalletError::Serialization(format!("envelope: {e}")))?;
let cipher = if parts.salt == cached.salt {
cached.cipher.clone()
} else {
return Err(WalletError::Serialization(
"envelope salt diverges from cached cipher (DB rotation in progress?)".to_owned(),
));
};
let plain_hex = cipher
.decrypt(envelope)
.map_err(|e| WalletError::Serialization(format!("decrypt: {e}")))?;
hex::decode(&plain_hex).map_err(|_| WalletError::Serialization("non-hex plaintext".to_owned()))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::providers::disk_private_state::StaticPassword;
use moonproof_ledger::base_crypto::time::Duration;
use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};
use moonproof_ledger::zswap::keys::{SecretKeys as ZswapSecretKeys, Seed as ZswapSeed};
use moonproof_wallet::abstractions::NetworkId;
use moonproof_wallet::dust::DustState;
use moonproof_wallet::facade::FacadeState;
use moonproof_wallet::shielded::ShieldedState;
use moonproof_wallet::unshielded::UnshieldedState;
use moonproof_wallet::WalletSnapshot;
use tempfile::TempDir;
fn dust_params() -> DustParameters {
DustParameters {
night_dust_ratio: 1_000,
generation_decay_rate: 1,
dust_grace_period: Duration::from_secs(60),
}
}
fn empty_facade() -> FacadeState {
let zswap = ZswapSecretKeys::from(ZswapSeed::from([0x01u8; 32]));
let dust = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
FacadeState::new(
ShieldedState::init_empty(&zswap, NetworkId::Undeployed),
UnshieldedState::empty(),
DustState::init_empty(dust_params(), &dust, NetworkId::Undeployed),
NetworkId::Undeployed,
)
}
fn config(dir: &TempDir, account: &str) -> WalletStoreConfig {
WalletStoreConfig {
db_path: dir.path().join("wallet.redb"),
account_id: account.to_owned(),
password: Arc::new(StaticPassword::new("TheQuickBrownFox-12345!")),
}
}
#[tokio::test]
async fn save_then_load_round_trips_an_empty_facade() {
let dir = TempDir::new().unwrap();
let store = WalletStore::open(config(&dir, "alice")).unwrap();
let snap = WalletSnapshot::capture(&empty_facade()).unwrap();
let written = store.save(&snap).await.unwrap();
assert!(written > 0);
let loaded = store.load().await.unwrap().expect("snapshot present");
assert_eq!(loaded.network_id, snap.network_id);
assert_eq!(loaded.format_version, snap.format_version);
}
#[tokio::test]
async fn load_returns_none_when_nothing_saved() {
let dir = TempDir::new().unwrap();
let store = WalletStore::open(config(&dir, "alice")).unwrap();
assert!(store.load().await.unwrap().is_none());
}
#[tokio::test]
async fn save_overwrites_existing_snapshot() {
let dir = TempDir::new().unwrap();
let store = WalletStore::open(config(&dir, "alice")).unwrap();
let snap1 = WalletSnapshot::capture(&empty_facade()).unwrap();
store.save(&snap1).await.unwrap();
let snap2 = WalletSnapshot::capture(&empty_facade()).unwrap();
store.save(&snap2).await.unwrap();
assert!(store.load().await.unwrap().is_some());
}
#[tokio::test]
async fn account_namespace_keeps_snapshots_isolated() {
let dir = TempDir::new().unwrap();
let alice = WalletStore::open(config(&dir, "alice")).unwrap();
let bob = WalletStore::open(config(&dir, "bob")).unwrap();
let snap = WalletSnapshot::capture(&empty_facade()).unwrap();
alice.save(&snap).await.unwrap();
assert!(alice.load().await.unwrap().is_some());
assert!(bob.load().await.unwrap().is_none());
}
#[tokio::test]
async fn clear_drops_persisted_snapshot() {
let dir = TempDir::new().unwrap();
let store = WalletStore::open(config(&dir, "alice")).unwrap();
let snap = WalletSnapshot::capture(&empty_facade()).unwrap();
store.save(&snap).await.unwrap();
store.clear().await.unwrap();
assert!(store.load().await.unwrap().is_none());
}
#[tokio::test]
async fn data_persists_across_reopen() {
let dir = TempDir::new().unwrap();
let cfg = config(&dir, "alice");
let path = cfg.db_path.clone();
let pw = cfg.password.clone();
let s1 = WalletStore::open(cfg).unwrap();
let snap = WalletSnapshot::capture(&empty_facade()).unwrap();
s1.save(&snap).await.unwrap();
drop(s1);
let s2 = WalletStore::open(WalletStoreConfig {
db_path: path,
account_id: "alice".to_owned(),
password: pw,
})
.unwrap();
assert!(s2.load().await.unwrap().is_some());
}
}