moonproof-contracts 0.2.2

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
//! Typed transaction phase newtypes.
//!
//! The Midnight transaction pipeline runs a value through three
//! distinct shapes:
//!
//! 1. [`UnprovenTx`] — wallet has assembled inputs/outputs and balanced
//!    circuits; ZK proofs are not yet computed. Type-level shape:
//!    `Transaction<Signature, ProofPreimageMarker, PedersenRandomness>`.
//! 2. [`ProvenTx`] — every contract-call segment + every zswap input/
//!    output has a ZK proof; Pedersen commitments are still in
//!    randomness form. Type-level shape: `Transaction<Signature,
//!    ProofMarker, PedersenRandomness>`.
//! 3. [`FinalizedTx`] — sealed wire form with `PureGeneratorPedersen`
//!    randomness committed; this is what the consensus node accepts.
//!
//! Providers exchange these typed values rather than tagged bytes, so
//! handing a transaction of the wrong phase to a provider is a compile
//! error rather than a runtime "`BAD_REQUEST`" from a downstream call.
//!
//! # Lazy bytes cache
//!
//! Each newtype carries a [`OnceCell`] that caches the
//! tagged-serialized form. The first call to [`UnprovenTx::as_bytes`]
//! / [`ProvenTx::as_bytes`] / [`FinalizedTx::as_bytes`] runs
//! `tagged_serialize` once; later calls return the cached slice. The
//! FFI surface is the only place the byte form is constructed
//! eagerly: `from_tagged_bytes` deserializes into the typed value AND
//! seeds the cache so the round-trip is free.

use std::sync::OnceLock;

use moonproof_ledger::ledger::structure::{ProofMarker, ProofPreimageMarker, Transaction};
use moonproof_ledger::serialize::{tagged_deserialize, tagged_serialize};
use moonproof_ledger::signatures::Signature;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::transient_crypto::commitment::{PedersenRandomness, PureGeneratorPedersen};

use crate::error::{ContractRuntimeError, Result};

/// Pre-prove transaction. Wallet has assembled inputs/outputs;
/// circuits have been balanced; nothing is proven yet.
///
/// Construction:
/// - From the typed value: [`UnprovenTx::new`].
/// - From wire bytes (FFI boundary): [`UnprovenTx::from_tagged_bytes`].
///
/// # Phase-mismatch is a compile error
///
/// Wrong-phase tx into the wallet's `balance_tx` is rejected at
/// compile time, not at runtime:
///
/// ```compile_fail
/// use moonproof_runtime::providers::WalletProvider;
/// use moonproof_runtime::tx_phase::UnprovenTx;
///
/// async fn passes_unproven_to_balance<W: WalletProvider>(w: &W, tx: UnprovenTx) {
///     // mismatched types: expected `ProvenTx`, found `UnprovenTx`
///     w.balance_tx(tx, None).await.unwrap();
/// }
/// ```
#[derive(Debug)]
pub struct UnprovenTx {
    inner: Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
    cached_bytes: OnceLock<Vec<u8>>,
}

/// Post-prove, pre-bind transaction. ZK proofs computed for every
/// circuit segment and zswap input/output. Pedersen commitments are
/// still in randomness form; sealing has not happened yet.
#[derive(Debug)]
pub struct ProvenTx {
    inner: Transaction<Signature, ProofMarker, PedersenRandomness, InMemoryDB>,
    cached_bytes: OnceLock<Vec<u8>>,
}

/// Sealed, wire-format transaction. `PureGeneratorPedersen` randomness
/// committed; the node accepts this shape via
/// `pallet_midnight.send_mn_transaction`.
#[derive(Debug)]
pub struct FinalizedTx {
    inner: Transaction<Signature, ProofMarker, PureGeneratorPedersen, InMemoryDB>,
    cached_bytes: OnceLock<Vec<u8>>,
}

// -- Constructors -------------------------------------------------------

impl UnprovenTx {
    /// Wrap a typed unproven transaction.
    #[must_use]
    pub fn new(
        tx: Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
    ) -> Self {
        Self {
            inner: tx,
            cached_bytes: OnceLock::new(),
        }
    }

    /// Construct from tagged-serialized bytes. Used at the FFI
    /// boundary where the caller speaks `Vec<u8>`. Seeds the bytes
    /// cache so a subsequent [`Self::as_bytes`] is free.
    pub fn from_tagged_bytes(bytes: &[u8]) -> Result<Self> {
        let inner = tagged_deserialize(&mut &bytes[..]).map_err(|source| {
            ContractRuntimeError::Deserialize {
                context: "UnprovenTx::from_tagged_bytes",
                source,
            }
        })?;
        let cache = OnceLock::new();
        let _ = cache.set(bytes.to_vec());
        Ok(Self {
            inner,
            cached_bytes: cache,
        })
    }

    /// Borrow the typed inner value.
    #[must_use]
    pub fn as_inner(
        &self,
    ) -> &Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB> {
        &self.inner
    }

    /// Move out the typed inner value.
    #[must_use]
    pub fn into_inner(
        self,
    ) -> Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB> {
        self.inner
    }

    /// Tagged-serialized bytes. Computed lazily on first call;
    /// subsequent calls return the cached slice.
    pub fn as_bytes(&self) -> Result<&[u8]> {
        if let Some(b) = self.cached_bytes.get() {
            return Ok(b.as_slice());
        }
        let mut buf = Vec::new();
        tagged_serialize(&self.inner, &mut buf).map_err(|source| {
            ContractRuntimeError::Serialize {
                context: "UnprovenTx::as_bytes",
                source,
            }
        })?;
        let _ = self.cached_bytes.set(buf);
        Ok(self.cached_bytes.get().expect("just set").as_slice())
    }

    /// Tagged-serialized bytes as an owned `Vec<u8>` — convenience
    /// for FFI surfaces that need ownership of the buffer.
    pub fn to_tagged_bytes(&self) -> Result<Vec<u8>> {
        Ok(self.as_bytes()?.to_vec())
    }
}

impl Clone for UnprovenTx {
    fn clone(&self) -> Self {
        let cache = OnceLock::new();
        if let Some(b) = self.cached_bytes.get() {
            let _ = cache.set(b.clone());
        }
        Self {
            inner: self.inner.clone(),
            cached_bytes: cache,
        }
    }
}

impl ProvenTx {
    #[must_use]
    pub fn new(tx: Transaction<Signature, ProofMarker, PedersenRandomness, InMemoryDB>) -> Self {
        Self {
            inner: tx,
            cached_bytes: OnceLock::new(),
        }
    }

    pub fn from_tagged_bytes(bytes: &[u8]) -> Result<Self> {
        let inner = tagged_deserialize(&mut &bytes[..]).map_err(|source| {
            ContractRuntimeError::Deserialize {
                context: "ProvenTx::from_tagged_bytes",
                source,
            }
        })?;
        let cache = OnceLock::new();
        let _ = cache.set(bytes.to_vec());
        Ok(Self {
            inner,
            cached_bytes: cache,
        })
    }

    #[must_use]
    pub fn as_inner(&self) -> &Transaction<Signature, ProofMarker, PedersenRandomness, InMemoryDB> {
        &self.inner
    }

    #[must_use]
    pub fn into_inner(self) -> Transaction<Signature, ProofMarker, PedersenRandomness, InMemoryDB> {
        self.inner
    }

    pub fn as_bytes(&self) -> Result<&[u8]> {
        if let Some(b) = self.cached_bytes.get() {
            return Ok(b.as_slice());
        }
        let mut buf = Vec::new();
        tagged_serialize(&self.inner, &mut buf).map_err(|source| {
            ContractRuntimeError::Serialize {
                context: "ProvenTx::as_bytes",
                source,
            }
        })?;
        let _ = self.cached_bytes.set(buf);
        Ok(self.cached_bytes.get().expect("just set").as_slice())
    }

    pub fn to_tagged_bytes(&self) -> Result<Vec<u8>> {
        Ok(self.as_bytes()?.to_vec())
    }
}

impl Clone for ProvenTx {
    fn clone(&self) -> Self {
        let cache = OnceLock::new();
        if let Some(b) = self.cached_bytes.get() {
            let _ = cache.set(b.clone());
        }
        Self {
            inner: self.inner.clone(),
            cached_bytes: cache,
        }
    }
}

impl FinalizedTx {
    #[must_use]
    pub fn new(tx: Transaction<Signature, ProofMarker, PureGeneratorPedersen, InMemoryDB>) -> Self {
        Self {
            inner: tx,
            cached_bytes: OnceLock::new(),
        }
    }

    pub fn from_tagged_bytes(bytes: &[u8]) -> Result<Self> {
        let inner = tagged_deserialize(&mut &bytes[..]).map_err(|source| {
            ContractRuntimeError::Deserialize {
                context: "FinalizedTx::from_tagged_bytes",
                source,
            }
        })?;
        let cache = OnceLock::new();
        let _ = cache.set(bytes.to_vec());
        Ok(Self {
            inner,
            cached_bytes: cache,
        })
    }

    #[must_use]
    pub fn as_inner(
        &self,
    ) -> &Transaction<Signature, ProofMarker, PureGeneratorPedersen, InMemoryDB> {
        &self.inner
    }

    #[must_use]
    pub fn into_inner(
        self,
    ) -> Transaction<Signature, ProofMarker, PureGeneratorPedersen, InMemoryDB> {
        self.inner
    }

    pub fn as_bytes(&self) -> Result<&[u8]> {
        if let Some(b) = self.cached_bytes.get() {
            return Ok(b.as_slice());
        }
        let mut buf = Vec::new();
        tagged_serialize(&self.inner, &mut buf).map_err(|source| {
            ContractRuntimeError::Serialize {
                context: "FinalizedTx::as_bytes",
                source,
            }
        })?;
        let _ = self.cached_bytes.set(buf);
        Ok(self.cached_bytes.get().expect("just set").as_slice())
    }

    pub fn to_tagged_bytes(&self) -> Result<Vec<u8>> {
        Ok(self.as_bytes()?.to_vec())
    }
}

impl Clone for FinalizedTx {
    fn clone(&self) -> Self {
        let cache = OnceLock::new();
        if let Some(b) = self.cached_bytes.get() {
            let _ = cache.set(b.clone());
        }
        Self {
            inner: self.inner.clone(),
            cached_bytes: cache,
        }
    }
}

// Phase round-trip + cache behaviour is exercised end-to-end by the
// runtime's submit-tx integration tests (`submit_tx::tests::*`,
// `submit_deploy_tx::tests::*`) that drive the prove → balance →
// submit pipeline through the typed phases. Standalone unit tests
// would need a fully-formed Transaction value; constructing one from
// scratch pulls in too much ledger-crate setup to be worthwhile when
// the integration tests already cover the behaviour.