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
//! Private-state provider trait — port of
//! `@midnight-ntwrk/midnight-js-types/src/private-state-provider.ts`.
//!
//! Manages two parallel stores:
//!
//! 1. Per-`PrivateStateId` blobs of private state (contract-defined,
//!    opaque to the runtime).
//! 2. Per-contract-address signing keys — each deployed contract has
//!    a single maintenance-authority signing key that the owner holds
//!    locally.
//!
//! The TS interface uses `any` for the private-state payload; Rust
//! uses `Vec<u8>` (the caller serialises their private state before
//! storing it — moonproof doesn't tie the store to a specific
//! serialisation format).

use moonproof_macros::async_trait;

use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::signatures::SigningKey;

use crate::error::Result;
use crate::types::PrivateStateId;

/// Upper bound on batch export / import sizes. Matches TS
/// `MAX_EXPORT_STATES` (10000). Exceeding this is an error — the
/// limit exists to prevent memory-exhaustion attacks.
pub const MAX_EXPORT_STATES: usize = 10_000;

/// Upper bound on batch export / import sizes for signing keys. Matches
/// TS `MAX_EXPORT_SIGNING_KEYS`.
pub const MAX_EXPORT_SIGNING_KEYS: usize = 10_000;

/// Encrypted export of zero-or-more private states, matching the TS
/// `PrivateStateExport` shape. Callers round-trip this through their
/// own storage — file, cloud, etc. The `format` field is a magic
/// string the importer verifies.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrivateStateExport {
    /// Format identifier — must be
    /// `"midnight-private-state-export"`.
    pub format: String,
    /// Encrypted payload (base64-encoded AES-256-GCM JSON).
    pub encrypted_payload: String,
    /// Salt used for key derivation (32 bytes, hex-encoded = 64
    /// chars).
    pub salt: String,
}

/// Encrypted export of signing keys, mirroring
/// [`PrivateStateExport`]. Separate type so the magic string can
/// differ (`"midnight-signing-key-export"`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SigningKeyExport {
    pub format: String,
    pub encrypted_payload: String,
    pub salt: String,
}

/// Policy for resolving conflicts during import. Port of TS
/// `'skip' | 'overwrite' | 'error'`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ImportConflictStrategy {
    /// Keep existing, drop incoming.
    Skip,
    /// Replace existing with incoming.
    Overwrite,
    /// Return an error if any conflict is seen. TS default.
    #[default]
    Error,
}

/// Options for [`PrivateStateProvider::export_private_states`].
#[derive(Debug, Clone, Default)]
pub struct ExportPrivateStatesOptions {
    /// Override password; if `None`, the provider's storage password
    /// is used.
    pub password: Option<String>,
    /// Cap the number of exported entries. `None` = use
    /// [`MAX_EXPORT_STATES`].
    pub max_states: Option<usize>,
}

/// Options for [`PrivateStateProvider::import_private_states`].
#[derive(Debug, Clone, Default)]
pub struct ImportPrivateStatesOptions {
    pub password: Option<String>,
    pub conflict_strategy: ImportConflictStrategy,
    pub max_states: Option<usize>,
}

/// Result of [`PrivateStateProvider::import_private_states`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ImportPrivateStatesResult {
    pub imported: usize,
    pub skipped: usize,
    pub overwritten: usize,
}

/// Options for [`PrivateStateProvider::export_signing_keys`].
#[derive(Debug, Clone, Default)]
pub struct ExportSigningKeysOptions {
    pub password: Option<String>,
    pub max_keys: Option<usize>,
}

/// Options for [`PrivateStateProvider::import_signing_keys`].
#[derive(Debug, Clone, Default)]
pub struct ImportSigningKeysOptions {
    pub password: Option<String>,
    pub conflict_strategy: ImportConflictStrategy,
    pub max_keys: Option<usize>,
}

/// Result of [`PrivateStateProvider::import_signing_keys`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ImportSigningKeysResult {
    pub imported: usize,
    pub skipped: usize,
    pub overwritten: usize,
}

/// Rust port of TS `PrivateStateProvider<PSI, PS>`.
///
/// The TS interface is generic in `PSI` (id type) and `PS` (state
/// type); the Rust port fixes `PSI = PrivateStateId` and `PS = Vec<u8>`
/// (opaque payload) because:
///
/// - The id type is always `string` in practice (TS generic only
///   exists to allow literal-type narrowing).
/// - The payload type is user-chosen but the provider stores it
///   opaquely; callers that want structured access wrap this trait
///   with a typed adapter at their boundary.
#[async_trait]
pub trait PrivateStateProvider: Send + Sync + std::fmt::Debug {
    // --- Scoping -----------------------------------------------------

    /// Set the contract address that subsequent operations are scoped
    /// to. Port of TS `setContractAddress(address)`. Providers that
    /// don't care about scoping can implement this as a no-op.
    async fn set_contract_address(&self, address: &ContractAddress) -> Result<()>;

    // --- Private-state blob CRUD ------------------------------------

    /// Store `state` at `private_state_id`.
    async fn set(&self, private_state_id: &PrivateStateId, state: Vec<u8>) -> Result<()>;

    /// Retrieve the blob at `private_state_id`. Returns `Ok(None)` if
    /// nothing is stored (TS convention returns `null`).
    async fn get(&self, private_state_id: &PrivateStateId) -> Result<Option<Vec<u8>>>;

    /// Remove the blob at `private_state_id`. No-op if none was
    /// stored.
    async fn remove(&self, private_state_id: &PrivateStateId) -> Result<()>;

    /// Remove every stored private-state blob.
    async fn clear(&self) -> Result<()>;

    // --- Signing-key CRUD -------------------------------------------

    /// Store `signing_key` under `address`.
    async fn set_signing_key(
        &self,
        address: &ContractAddress,
        signing_key: SigningKey,
    ) -> Result<()>;

    /// Retrieve the signing key for `address`, if stored.
    async fn get_signing_key(&self, address: &ContractAddress) -> Result<Option<SigningKey>>;

    /// Remove the signing key for `address`. No-op if none was stored.
    async fn remove_signing_key(&self, address: &ContractAddress) -> Result<()>;

    /// Remove every stored signing key.
    async fn clear_signing_keys(&self) -> Result<()>;

    // --- Export / import --------------------------------------------

    /// Export all stored private-state blobs as an encrypted bundle.
    /// Signing keys are NOT included — see
    /// [`Self::export_signing_keys`].
    async fn export_private_states(
        &self,
        options: &ExportPrivateStatesOptions,
    ) -> Result<PrivateStateExport>;

    /// Import a previously-exported bundle.
    async fn import_private_states(
        &self,
        export: &PrivateStateExport,
        options: &ImportPrivateStatesOptions,
    ) -> Result<ImportPrivateStatesResult>;

    /// Export all stored signing keys as an encrypted bundle.
    async fn export_signing_keys(
        &self,
        options: &ExportSigningKeysOptions,
    ) -> Result<SigningKeyExport>;

    /// Import a previously-exported signing-key bundle.
    async fn import_signing_keys(
        &self,
        export: &SigningKeyExport,
        options: &ImportSigningKeysOptions,
    ) -> Result<ImportSigningKeysResult>;
}

#[async_trait]
impl<T: PrivateStateProvider + ?Sized> PrivateStateProvider for std::sync::Arc<T> {
    async fn set_contract_address(&self, address: &ContractAddress) -> Result<()> {
        (**self).set_contract_address(address).await
    }
    async fn set(&self, private_state_id: &PrivateStateId, state: Vec<u8>) -> Result<()> {
        (**self).set(private_state_id, state).await
    }
    async fn get(&self, private_state_id: &PrivateStateId) -> Result<Option<Vec<u8>>> {
        (**self).get(private_state_id).await
    }
    async fn remove(&self, private_state_id: &PrivateStateId) -> Result<()> {
        (**self).remove(private_state_id).await
    }
    async fn clear(&self) -> Result<()> {
        (**self).clear().await
    }
    async fn set_signing_key(
        &self,
        address: &ContractAddress,
        signing_key: SigningKey,
    ) -> Result<()> {
        (**self).set_signing_key(address, signing_key).await
    }
    async fn get_signing_key(&self, address: &ContractAddress) -> Result<Option<SigningKey>> {
        (**self).get_signing_key(address).await
    }
    async fn remove_signing_key(&self, address: &ContractAddress) -> Result<()> {
        (**self).remove_signing_key(address).await
    }
    async fn clear_signing_keys(&self) -> Result<()> {
        (**self).clear_signing_keys().await
    }
    async fn export_private_states(
        &self,
        options: &ExportPrivateStatesOptions,
    ) -> Result<PrivateStateExport> {
        (**self).export_private_states(options).await
    }
    async fn import_private_states(
        &self,
        export: &PrivateStateExport,
        options: &ImportPrivateStatesOptions,
    ) -> Result<ImportPrivateStatesResult> {
        (**self).import_private_states(export, options).await
    }
    async fn export_signing_keys(
        &self,
        options: &ExportSigningKeysOptions,
    ) -> Result<SigningKeyExport> {
        (**self).export_signing_keys(options).await
    }
    async fn import_signing_keys(
        &self,
        export: &SigningKeyExport,
        options: &ImportSigningKeysOptions,
    ) -> Result<ImportSigningKeysResult> {
        (**self).import_signing_keys(export, options).await
    }
}

#[async_trait]
impl<T: PrivateStateProvider + ?Sized> PrivateStateProvider for Box<T> {
    async fn set_contract_address(&self, address: &ContractAddress) -> Result<()> {
        (**self).set_contract_address(address).await
    }
    async fn set(&self, private_state_id: &PrivateStateId, state: Vec<u8>) -> Result<()> {
        (**self).set(private_state_id, state).await
    }
    async fn get(&self, private_state_id: &PrivateStateId) -> Result<Option<Vec<u8>>> {
        (**self).get(private_state_id).await
    }
    async fn remove(&self, private_state_id: &PrivateStateId) -> Result<()> {
        (**self).remove(private_state_id).await
    }
    async fn clear(&self) -> Result<()> {
        (**self).clear().await
    }
    async fn set_signing_key(
        &self,
        address: &ContractAddress,
        signing_key: SigningKey,
    ) -> Result<()> {
        (**self).set_signing_key(address, signing_key).await
    }
    async fn get_signing_key(&self, address: &ContractAddress) -> Result<Option<SigningKey>> {
        (**self).get_signing_key(address).await
    }
    async fn remove_signing_key(&self, address: &ContractAddress) -> Result<()> {
        (**self).remove_signing_key(address).await
    }
    async fn clear_signing_keys(&self) -> Result<()> {
        (**self).clear_signing_keys().await
    }
    async fn export_private_states(
        &self,
        options: &ExportPrivateStatesOptions,
    ) -> Result<PrivateStateExport> {
        (**self).export_private_states(options).await
    }
    async fn import_private_states(
        &self,
        export: &PrivateStateExport,
        options: &ImportPrivateStatesOptions,
    ) -> Result<ImportPrivateStatesResult> {
        (**self).import_private_states(export, options).await
    }
    async fn export_signing_keys(
        &self,
        options: &ExportSigningKeysOptions,
    ) -> Result<SigningKeyExport> {
        (**self).export_signing_keys(options).await
    }
    async fn import_signing_keys(
        &self,
        export: &SigningKeyExport,
        options: &ImportSigningKeysOptions,
    ) -> Result<ImportSigningKeysResult> {
        (**self).import_signing_keys(export, options).await
    }
}

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

    #[test]
    fn import_conflict_strategy_default_is_error() {
        assert_eq!(
            ImportConflictStrategy::default(),
            ImportConflictStrategy::Error
        );
    }

    #[test]
    fn max_export_constants_match_ts() {
        assert_eq!(MAX_EXPORT_STATES, 10_000);
        assert_eq!(MAX_EXPORT_SIGNING_KEYS, 10_000);
    }

    #[test]
    fn import_result_default_is_zero_imports() {
        let r = ImportPrivateStatesResult::default();
        assert_eq!(r.imported, 0);
        assert_eq!(r.skipped, 0);
        assert_eq!(r.overwritten, 0);
    }

    #[test]
    fn export_options_default_is_none_password_and_max() {
        let o = ExportPrivateStatesOptions::default();
        assert!(o.password.is_none());
        assert!(o.max_states.is_none());
    }
}