moonproof-contracts 0.2.1

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
//! Shared helpers for opening the wallet's per-account redb stores
//! ([`super::DiskPendingTransactionsStorage`],
//! [`super::DiskTransactionHistoryStorage`],
//! [`super::wallet_store::WalletStore`]) from an unlocked
//! [`moonproof_wallet::session::WalletSession`].
//!
//! Both the CLI and the Flutter SDK need the same recipe: derive a
//! stable per-wallet password from the signing key, compute a
//! per-(owner, network) `account_id`, and open the disk artefacts under
//! that scope. Centralising the recipe here keeps the two surfaces
//! byte-compatible — same redb file written by either binary opens
//! cleanly under the other.

use std::sync::Arc;

use anyhow::{bail, Result};
use moonproof_ledger::serialize::Serializable;
use moonproof_wallet::session::{NetworkConfig, WalletSession};
use moonproof_wallet::testing::Wallet;

use super::disk_private_state::PrivateStoragePassword;

/// File name of the per-wallet redb database. Holds wallet snapshot,
/// pending tx, and tx history rows scoped per-account.
pub const WALLET_DB_FILENAME: &str = "wallet.redb";

/// Magic prefix every valid redb file starts with, per the redb v4
/// on-disk format. Inspired by PNG's magic number.
const REDB_MAGIC: [u8; 9] = [b'r', b'e', b'd', b'b', 0x1A, 0x0A, 0xA9, 0x0D, 0x0A];

/// Minimum size of a sane redb v4 file: 9-byte magic + the two
/// 128-byte commit slots plus their leading header bytes
/// (`DB_HEADER_SIZE = 320`). We use 1 KiB as a safety floor — any
/// smaller is conclusively a torn write.
const REDB_MIN_BYTES: u64 = 1024;

/// Validate that `path` looks like a real redb v4 file. If it
/// exists but the magic is missing or the file is shorter than the
/// minimum sane header layout, the file is **deleted** so the
/// caller's `redb::Database::open` doesn't panic on truncated state.
///
/// Used by all wallet-snapshot / pending-tx / tx-history disk
/// stores to recover from abrupt OS-level kills (Android pulling
/// the rug mid-commit, power loss between the redb commit and the
/// filesystem fsync, etc.) without falling back to a
/// `catch_unwind` workaround.
///
/// Returns `true` if the file was deleted (caller should treat as
/// fresh DB), `false` otherwise.
pub fn validate_or_clear(path: &std::path::Path) -> Result<bool> {
    use std::io::Read as _;

    let meta = match std::fs::metadata(path) {
        Ok(m) => m,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
        Err(e) => bail!("stat {}: {e}", path.display()),
    };
    if !meta.is_file() {
        return Ok(false);
    }
    let len = meta.len();
    if len < REDB_MIN_BYTES {
        tracing::warn!(
            "redb file too small ({len} bytes < {REDB_MIN_BYTES}) — deleting {}",
            path.display()
        );
        std::fs::remove_file(path).ok();
        return Ok(true);
    }
    let mut head = [0u8; 9];
    let mut f = match std::fs::File::open(path) {
        Ok(f) => f,
        Err(e) => {
            tracing::warn!(
                "redb open for validation failed: {e} — deleting {}",
                path.display()
            );
            std::fs::remove_file(path).ok();
            return Ok(true);
        }
    };
    if let Err(e) = f.read_exact(&mut head) {
        tracing::warn!("redb header read failed: {e} — deleting {}", path.display());
        std::fs::remove_file(path).ok();
        return Ok(true);
    }
    if head != REDB_MAGIC {
        tracing::warn!(
            "redb magic mismatch (got {head:02x?}) — deleting {}",
            path.display()
        );
        std::fs::remove_file(path).ok();
        return Ok(true);
    }
    Ok(false)
}

#[cfg(test)]
mod validate_tests {
    use super::*;

    #[test]
    fn missing_file_is_a_noop() {
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("wallet.redb");
        assert!(!validate_or_clear(&p).unwrap());
    }

    #[test]
    fn too_small_file_is_deleted() {
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("wallet.redb");
        std::fs::write(&p, b"small").unwrap();
        assert!(validate_or_clear(&p).unwrap());
        assert!(!p.exists());
    }

    #[test]
    fn missing_magic_is_deleted() {
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("wallet.redb");
        std::fs::write(&p, vec![0u8; 4096]).unwrap();
        assert!(validate_or_clear(&p).unwrap());
        assert!(!p.exists());
    }

    #[test]
    fn valid_magic_is_kept() {
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("wallet.redb");
        let mut bytes = REDB_MAGIC.to_vec();
        bytes.resize(usize::try_from(REDB_MIN_BYTES).unwrap() + 16, 0);
        std::fs::write(&p, &bytes).unwrap();
        assert!(!validate_or_clear(&p).unwrap());
        assert!(p.exists());
    }
}

/// Account id for wallet-side disk stores. Combines the
/// network-independent `owner_bytes` (BIP44-derived ed25519
/// verifying key) with the active network id label so wallet
/// snapshot, tx history, and pending-tx rows live in distinct redb
/// keyspaces per network.
#[must_use]
pub fn default_account_id_for(wallet: &Wallet, network: &NetworkConfig) -> String {
    format!(
        "{}:{}",
        hex::encode(wallet.owner_bytes()),
        network.network_id,
    )
}

/// Convenience wrapper for callers that already hold a
/// [`WalletSession`]. Equivalent to
/// [`default_account_id_for`]`(&session.wallet, &session.network)`.
#[must_use]
pub fn default_session_account_id(session: &WalletSession) -> String {
    default_account_id_for(&session.wallet, &session.network)
}

/// Derive a stable per-wallet disk password from `wallet`'s signing
/// key. Two unlocks of the same keystore produce the same password —
/// the property the disk store depends on for round-tripping.
///
/// The password tied to the signing key (rather than the user's
/// password) means anyone who steals the redb file still needs the
/// unlocked wallet to read it.
pub fn derive_password_for(wallet: &Wallet) -> Result<Arc<dyn PrivateStoragePassword>> {
    let mut signing_key_bytes = Vec::new();
    Serializable::serialize(&wallet.signing_key, &mut signing_key_bytes)
        .map_err(|e| anyhow::anyhow!("serialize signing key: {e}"))?;
    if signing_key_bytes.is_empty() {
        bail!("wallet signing key is empty — cannot derive disk-store password");
    }
    let pw = moonproof_utils::Sha256Builder::new()
        .add(b"moonproof:disk-private-state-v1")
        .add(&signing_key_bytes)
        .add(wallet.owner_bytes())
        .finalize_hex();
    if pw.len() < 16 {
        bail!("derived disk password has unexpected length");
    }
    Ok(Arc::new(WalletDerivedPassword(pw)))
}

/// Convenience wrapper for callers that already hold a
/// [`WalletSession`]. Equivalent to
/// [`derive_password_for`]`(&session.wallet)`.
pub fn derive_session_password(session: &WalletSession) -> Result<Arc<dyn PrivateStoragePassword>> {
    derive_password_for(&session.wallet)
}

#[derive(Debug, Clone)]
struct WalletDerivedPassword(String);

impl PrivateStoragePassword for WalletDerivedPassword {
    fn password(&self) -> crate::Result<String> {
        Ok(self.0.clone())
    }
}