use std::path::PathBuf;
use std::sync::Arc;
use moonproof_macros::async_trait;
use moonproof_wallet::tx_history::{TransactionHistoryEntry, TransactionHistoryStorage};
use moonproof_wallet::WalletError;
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:tx_history");
pub struct DiskTransactionHistoryConfig {
pub db_path: PathBuf,
pub account_id: String,
pub password: Arc<dyn PrivateStoragePassword>,
}
impl std::fmt::Debug for DiskTransactionHistoryConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DiskTransactionHistoryConfig")
.field("db_path", &self.db_path)
.field("account_id", &self.account_id)
.finish_non_exhaustive()
}
}
#[derive(Clone)]
pub struct DiskTransactionHistoryStorage {
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 DiskTransactionHistoryStorage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DiskTransactionHistoryStorage")
.field("account_hash", &hex::encode(self.inner.account_hash))
.finish_non_exhaustive()
}
}
impl DiskTransactionHistoryStorage {
pub fn open(config: DiskTransactionHistoryConfig) -> 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| into_wallet_err(&e))?;
let write = db
.begin_write()
.map_err(|e| WalletError::Serialization(format!("begin_write tx_history init: {e}")))?;
{
let _ = write
.open_table(TABLE)
.map_err(|e| WalletError::Serialization(format!("open tx_history: {e}")))?;
}
write
.commit()
.map_err(|e| WalletError::Serialization(format!("commit tx_history 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),
}),
})
}
}
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| into_wallet_err(&e))?;
let (cipher, salt) =
crate::providers::disk_private_state::account_cipher(&self.db, &self.account_hash, &pw)
.map_err(|e| into_wallet_err(&e))?;
let copy = CachedCipher {
cipher: cipher.clone(),
salt,
};
*cache = Some(CachedCipher { cipher, salt });
Ok(copy)
}
}
#[async_trait]
impl TransactionHistoryStorage for DiskTransactionHistoryStorage {
async fn upsert(&self, entry: TransactionHistoryEntry) -> Result<(), WalletError> {
let inner = self.inner.clone();
let merged = match self.get(&entry.hash).await? {
Some(mut existing) => {
existing.merge(entry);
existing
}
None => entry,
};
let key_bytes = key_for(&inner.account_hash, &merged.hash);
let json = serde_json::to_vec(&merged)
.map_err(|e| WalletError::Serialization(format!("encode entry: {e}")))?;
run_blocking(move || {
let cached = inner.cipher_for_read_write()?;
let envelope = encrypt_value(&cached.cipher, &json);
let write = inner
.db
.begin_write()
.map_err(|e| WalletError::Serialization(format!("begin_write upsert: {e}")))?;
{
let mut table = write
.open_table(TABLE)
.map_err(|e| WalletError::Serialization(format!("open table upsert: {e}")))?;
table
.insert(key_bytes.as_slice(), envelope.as_bytes())
.map_err(|e| WalletError::Serialization(format!("insert upsert: {e}")))?;
}
write
.commit()
.map_err(|e| WalletError::Serialization(format!("commit upsert: {e}")))?;
Ok(())
})
.await
}
async fn get(&self, hash: &str) -> Result<Option<TransactionHistoryEntry>, WalletError> {
let inner = self.inner.clone();
let hash = hash.to_owned();
run_blocking(move || {
let cached = inner.cipher_for_read_write()?;
let key_bytes = key_for(&inner.account_hash, &hash);
let read = inner
.db
.begin_read()
.map_err(|e| WalletError::Serialization(format!("begin_read: {e}")))?;
let table = read
.open_table(TABLE)
.map_err(|e| WalletError::Serialization(format!("open table read: {e}")))?;
let Some(value) = table
.get(key_bytes.as_slice())
.map_err(|e| WalletError::Serialization(format!("lookup: {e}")))?
else {
return Ok(None);
};
let envelope = std::str::from_utf8(value.value())
.map_err(|_| WalletError::Serialization("non-utf8 envelope".to_owned()))?;
let bytes = decrypt(&cached, envelope)?;
let entry: TransactionHistoryEntry = serde_json::from_slice(&bytes)
.map_err(|e| WalletError::Serialization(format!("decode entry: {e}")))?;
Ok(Some(entry))
})
.await
}
async fn get_all(&self) -> Result<Vec<TransactionHistoryEntry>, WalletError> {
let inner = self.inner.clone();
run_blocking(move || {
let cached = inner.cipher_for_read_write()?;
let read = inner
.db
.begin_read()
.map_err(|e| WalletError::Serialization(format!("begin_read: {e}")))?;
let table = read
.open_table(TABLE)
.map_err(|e| WalletError::Serialization(format!("open table read: {e}")))?;
let prefix = inner.account_hash.to_vec();
let mut out = Vec::new();
for entry in table
.iter()
.map_err(|e| WalletError::Serialization(format!("iter: {e}")))?
{
let (k, v) =
entry.map_err(|e| WalletError::Serialization(format!("iter entry: {e}")))?;
let kb = k.value();
if !kb.starts_with(&prefix) {
continue;
}
let envelope = std::str::from_utf8(v.value())
.map_err(|_| WalletError::Serialization("non-utf8 envelope".to_owned()))?;
let bytes = decrypt(&cached, envelope)?;
let parsed: TransactionHistoryEntry = serde_json::from_slice(&bytes)
.map_err(|e| WalletError::Serialization(format!("decode entry: {e}")))?;
out.push(parsed);
}
Ok(out)
})
.await
}
async fn remove(&self, hash: &str) -> Result<(), WalletError> {
let inner = self.inner.clone();
let hash = hash.to_owned();
run_blocking(move || {
let key_bytes = key_for(&inner.account_hash, &hash);
let write = inner
.db
.begin_write()
.map_err(|e| WalletError::Serialization(format!("begin_write remove: {e}")))?;
{
let mut table = write
.open_table(TABLE)
.map_err(|e| WalletError::Serialization(format!("open table remove: {e}")))?;
table
.remove(key_bytes.as_slice())
.map_err(|e| WalletError::Serialization(format!("delete: {e}")))?;
}
write
.commit()
.map_err(|e| WalletError::Serialization(format!("commit remove: {e}")))?;
Ok(())
})
.await
}
async fn clear(&self) -> Result<(), WalletError> {
let inner = self.inner.clone();
run_blocking(move || {
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}")))?;
let prefix = inner.account_hash.to_vec();
let mut keys: Vec<Vec<u8>> = Vec::new();
for entry in table
.iter()
.map_err(|e| WalletError::Serialization(format!("iter clear: {e}")))?
{
let (k, _) = entry
.map_err(|e| WalletError::Serialization(format!("iter entry: {e}")))?;
let kb = k.value();
if kb.starts_with(&prefix) {
keys.push(kb.to_vec());
}
}
for k in keys {
table
.remove(k.as_slice())
.map_err(|e| WalletError::Serialization(format!("delete: {e}")))?;
}
}
write
.commit()
.map_err(|e| WalletError::Serialization(format!("commit clear: {e}")))?;
Ok(())
})
.await
}
}
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], hash: &str) -> Vec<u8> {
let mut k = Vec::with_capacity(16 + hash.len());
k.extend_from_slice(account_hash);
k.extend_from_slice(hash.as_bytes());
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()))
}
fn into_wallet_err(e: &crate::error::ContractRuntimeError) -> WalletError {
WalletError::Serialization(format!("disk tx history: {e}"))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::providers::disk_private_state::StaticPassword;
use moonproof_wallet::tx_history::TransactionHistoryStatus;
use std::sync::Arc;
use tempfile::TempDir;
fn config(dir: &TempDir, account: &str) -> DiskTransactionHistoryConfig {
DiskTransactionHistoryConfig {
db_path: dir.path().join("tx-hist.redb"),
account_id: account.to_owned(),
password: Arc::new(StaticPassword::new("TheQuickBrownFox-12345!")),
}
}
fn entry(hash: &str) -> TransactionHistoryEntry {
TransactionHistoryEntry {
hash: hash.to_owned(),
protocol_version: moonproof_wallet::ProtocolVersion(8),
status: TransactionHistoryStatus::Success,
identifiers: None,
timestamp_ms: None,
fees: None,
shielded: None,
unshielded: None,
dust: None,
extra: serde_json::Value::Null,
}
}
#[tokio::test]
async fn upsert_then_get_persists_round_trip() {
let dir = TempDir::new().unwrap();
let store = DiskTransactionHistoryStorage::open(config(&dir, "alice")).unwrap();
store.upsert(entry("aa")).await.unwrap();
let got = store.get("aa").await.unwrap().unwrap();
assert_eq!(got.hash, "aa");
}
#[tokio::test]
async fn upsert_merges_field_aware_on_existing_hash() {
let dir = TempDir::new().unwrap();
let store = DiskTransactionHistoryStorage::open(config(&dir, "alice")).unwrap();
let mut a = entry("aa");
a.fees = Some(100);
store.upsert(a).await.unwrap();
let mut b = entry("aa");
b.timestamp_ms = Some(1234);
store.upsert(b).await.unwrap();
let got = store.get("aa").await.unwrap().unwrap();
assert_eq!(got.fees, Some(100));
assert_eq!(got.timestamp_ms, Some(1234));
}
#[tokio::test]
async fn get_all_returns_only_account_scope() {
let dir = TempDir::new().unwrap();
let alice = DiskTransactionHistoryStorage::open(config(&dir, "alice")).unwrap();
let bob = DiskTransactionHistoryStorage::open(config(&dir, "bob")).unwrap();
alice.upsert(entry("aa")).await.unwrap();
bob.upsert(entry("bb")).await.unwrap();
let alice_all = alice.get_all().await.unwrap();
let bob_all = bob.get_all().await.unwrap();
assert_eq!(alice_all.len(), 1);
assert_eq!(alice_all[0].hash, "aa");
assert_eq!(bob_all.len(), 1);
assert_eq!(bob_all[0].hash, "bb");
}
#[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 store = DiskTransactionHistoryStorage::open(cfg).unwrap();
store.upsert(entry("aa")).await.unwrap();
drop(store);
let store2 = DiskTransactionHistoryStorage::open(DiskTransactionHistoryConfig {
db_path: path,
account_id: "alice".to_owned(),
password: pw,
})
.unwrap();
let all = store2.get_all().await.unwrap();
assert_eq!(all.len(), 1);
}
#[tokio::test]
async fn remove_drops_only_target_entry() {
let dir = TempDir::new().unwrap();
let store = DiskTransactionHistoryStorage::open(config(&dir, "alice")).unwrap();
store.upsert(entry("aa")).await.unwrap();
store.upsert(entry("bb")).await.unwrap();
store.remove("aa").await.unwrap();
assert!(store.get("aa").await.unwrap().is_none());
assert!(store.get("bb").await.unwrap().is_some());
}
}