use std::path::PathBuf;
use std::sync::Arc;
use moonproof_macros::async_trait;
use moonproof_wallet::pending_tx::{
PendingTransactionEntry, PendingTransactionResult, PendingTransactionsStorage,
};
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:pending_tx");
pub struct DiskPendingTransactionsConfig {
pub db_path: PathBuf,
pub account_id: String,
pub password: Arc<dyn PrivateStoragePassword>,
}
impl std::fmt::Debug for DiskPendingTransactionsConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DiskPendingTransactionsConfig")
.field("db_path", &self.db_path)
.field("account_id", &self.account_id)
.finish_non_exhaustive()
}
}
#[derive(Clone)]
pub struct DiskPendingTransactionsStorage {
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 DiskPendingTransactionsStorage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DiskPendingTransactionsStorage")
.field("account_hash", &hex::encode(self.inner.account_hash))
.finish_non_exhaustive()
}
}
impl DiskPendingTransactionsStorage {
pub fn open(config: DiskPendingTransactionsConfig) -> 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),
}),
})
}
}
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_trait]
impl PendingTransactionsStorage for DiskPendingTransactionsStorage {
async fn upsert(&self, entry: PendingTransactionEntry) -> Result<(), WalletError> {
let inner = self.inner.clone();
let json = serde_json::to_vec(&entry)
.map_err(|e| WalletError::Serialization(format!("encode entry: {e}")))?;
let key = key_for(&inner.account_hash, &entry.hash);
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: {e}")))?;
{
let mut table = write
.open_table(TABLE)
.map_err(|e| WalletError::Serialization(format!("open table: {e}")))?;
table
.insert(key.as_slice(), envelope.as_bytes())
.map_err(|e| WalletError::Serialization(format!("insert: {e}")))?;
}
write
.commit()
.map_err(|e| WalletError::Serialization(format!("commit: {e}")))?;
Ok(())
})
.await
}
async fn mark_result(
&self,
hash: &str,
result: PendingTransactionResult,
) -> Result<(), WalletError> {
let Some(mut existing) = self.get(hash).await? else {
return Ok(());
};
existing.result = Some(result);
self.upsert(existing).await
}
async fn get(&self, hash: &str) -> Result<Option<PendingTransactionEntry>, WalletError> {
let inner = self.inner.clone();
let hash = hash.to_owned();
run_blocking(move || {
let cached = inner.cipher_for_read_write()?;
let key = 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: {e}")))?;
let Some(value) = table
.get(key.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: PendingTransactionEntry = 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<PendingTransactionEntry>, 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: {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: PendingTransactionEntry = 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 = key_for(&inner.account_hash, &hash);
let write = inner
.db
.begin_write()
.map_err(|e| WalletError::Serialization(format!("begin_write: {e}")))?;
{
let mut table = write
.open_table(TABLE)
.map_err(|e| WalletError::Serialization(format!("open table: {e}")))?;
table
.remove(key.as_slice())
.map_err(|e| WalletError::Serialization(format!("remove: {e}")))?;
}
write
.commit()
.map_err(|e| WalletError::Serialization(format!("commit: {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: {e}")))?;
{
let mut table = write
.open_table(TABLE)
.map_err(|e| WalletError::Serialization(format!("open table: {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: {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!("remove: {e}")))?;
}
}
write
.commit()
.map_err(|e| WalletError::Serialization(format!("commit: {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".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_wallet::pending_tx::{
PendingTransactionEntry, PendingTransactionResult, PendingTransactionStatus,
};
use std::sync::Arc;
use tempfile::TempDir;
fn config(dir: &TempDir, account: &str) -> DiskPendingTransactionsConfig {
DiskPendingTransactionsConfig {
db_path: dir.path().join("pending.redb"),
account_id: account.to_owned(),
password: Arc::new(StaticPassword::new("TheQuickBrownFox-12345!")),
}
}
fn entry(hash: &str) -> PendingTransactionEntry {
PendingTransactionEntry {
hash: hash.to_owned(),
creation_time_ms: 1_700_000_000_000,
segment_ids: vec![0, 1],
ttl_secs: Some(3600),
raw_tx_hex: None,
result: None,
}
}
#[tokio::test]
async fn upsert_then_get_round_trips() {
let dir = TempDir::new().unwrap();
let store = DiskPendingTransactionsStorage::open(config(&dir, "alice")).unwrap();
store.upsert(entry("aa")).await.unwrap();
let got = store.get("aa").await.unwrap().unwrap();
assert!(got.is_pending());
}
#[tokio::test]
async fn mark_result_persists_status() {
let dir = TempDir::new().unwrap();
let store = DiskPendingTransactionsStorage::open(config(&dir, "alice")).unwrap();
store.upsert(entry("aa")).await.unwrap();
store
.mark_result(
"aa",
PendingTransactionResult {
status: PendingTransactionStatus::Success,
segments: vec![],
},
)
.await
.unwrap();
let got = store.get("aa").await.unwrap().unwrap();
assert!(!got.is_pending());
}
#[tokio::test]
async fn get_all_filters_to_account_scope() {
let dir = TempDir::new().unwrap();
let alice = DiskPendingTransactionsStorage::open(config(&dir, "alice")).unwrap();
let bob = DiskPendingTransactionsStorage::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!(bob_all.len(), 1);
}
#[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 = DiskPendingTransactionsStorage::open(cfg).unwrap();
s1.upsert(entry("aa")).await.unwrap();
drop(s1);
let s2 = DiskPendingTransactionsStorage::open(DiskPendingTransactionsConfig {
db_path: path,
account_id: "alice".to_owned(),
password: pw,
})
.unwrap();
assert!(s2.get("aa").await.unwrap().is_some());
}
#[tokio::test]
async fn clear_drops_only_account_rows() {
let dir = TempDir::new().unwrap();
let alice = DiskPendingTransactionsStorage::open(config(&dir, "alice")).unwrap();
let bob = DiskPendingTransactionsStorage::open(config(&dir, "bob")).unwrap();
alice.upsert(entry("aa")).await.unwrap();
bob.upsert(entry("bb")).await.unwrap();
alice.clear().await.unwrap();
assert!(alice.get("aa").await.unwrap().is_none());
assert!(bob.get("bb").await.unwrap().is_some());
}
}