moonproof-runtime 0.2.1

Wasm-friendly Compact contract runtime core — IR walker, IR-driven circuit executor, contract state, runtime values
Documentation
//! Host-supplied witnesses callback.
//!
//! When a circuit calls a witness function (e.g. `localCount()` in the
//! registry contract), the runtime needs the host to supply the
//! current value AND a (possibly mutated) next private state. This
//! trait is the contract.
//!
//! The shape mirrors the FFI `SigningProvider` — `Send + Sync`
//! always (Schnorr-nonce-reuse defense), payloads cross via JSON so
//! the same trait works through every FFI binding (`UniFFI` / NAPI /
//! `PyO3`).

use moonproof_runtime_ir::RuntimeValue as Value;

use super::error::Result;

/// A witness invocation result: the value the circuit observes, plus
/// the rotated private state to thread into the next call.
#[derive(Debug, Clone)]
pub struct WitnessResult {
    /// The value returned to the circuit (used in expressions, written
    /// to the private transcript output, etc.).
    pub observed: Value,
    /// The new private-state value after this witness fired.
    pub next_private_state: Value,
}

/// Host-side witness callback. Implementations decode the JSON-shaped
/// args + private-state and produce a [`WitnessResult`].
///
/// `Send + Sync` is **load-bearing** — the runtime may invoke witness
/// callbacks from worker threads (proof generation pools, async
/// runtimes). Implementations that hold mutable host state must
/// internally synchronize.
pub trait Witnesses: Send + Sync + std::fmt::Debug {
    /// Invoke the named witness with JSON-shaped args + the current
    /// private state. Returns the observed value + the rotated
    /// private state.
    ///
    /// `witness_name` is the entry from the IR's `witnesses[]` array
    /// (e.g. `"localCount"`). `args` is the JSON encoding of the
    /// circuit-call arguments forwarded into the witness call (most
    /// witnesses take no args from the circuit; the JSON value is
    /// `[]` in that case). `private_state` is the current host-side
    /// private state.
    fn invoke(
        &self,
        witness_name: &str,
        args: &Value,
        private_state: &Value,
    ) -> Result<WitnessResult>;
}

/// A no-op witnesses provider — for contracts that have no witnesses
/// (counter, mint, vault). Returns an error if any witness is
/// invoked, surfacing the misconfiguration loudly rather than
/// silently producing zero values.
#[derive(Debug, Clone, Copy, Default)]
pub struct NoWitnesses;

impl Witnesses for NoWitnesses {
    fn invoke(
        &self,
        witness_name: &str,
        _args: &Value,
        _private_state: &Value,
    ) -> Result<WitnessResult> {
        Err(super::error::IrDriverError::Witness(format!(
            "contract invoked witness '{witness_name}' but NoWitnesses was supplied; \
             pass a real Witnesses impl when constructing IrExecutable"
        )))
    }
}

type ScriptedHandler =
    std::sync::Arc<dyn Fn(&Value, &Value) -> Result<WitnessResult> + Send + Sync>;
type FallbackHandler =
    std::sync::Arc<dyn Fn(&str, &Value, &Value) -> Result<WitnessResult> + Send + Sync>;

/// Scripted-witnesses test helper. Register per-witness callbacks with
/// [`Self::with`] / [`Self::with_const`]; unscripted witnesses fall through to
/// the registered fallback (or error).
#[derive(Clone, Default)]
pub struct ScriptedWitnesses {
    scripts: std::collections::HashMap<String, ScriptedHandler>,
    fallback: Option<FallbackHandler>,
}

impl std::fmt::Debug for ScriptedWitnesses {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ScriptedWitnesses")
            .field("scripts", &self.scripts.keys().collect::<Vec<_>>())
            .field("has_fallback", &self.fallback.is_some())
            .finish()
    }
}

impl ScriptedWitnesses {
    /// Construct an empty mock — every witness invocation errors until scripted.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a callback for `witness_name`.
    #[must_use]
    pub fn with<F>(mut self, witness_name: impl Into<String>, f: F) -> Self
    where
        F: Fn(&Value, &Value) -> Result<WitnessResult> + Send + Sync + 'static,
    {
        self.scripts
            .insert(witness_name.into(), std::sync::Arc::new(f));
        self
    }

    /// Register a constant-value callback for `witness_name`.
    #[must_use]
    pub fn with_const(
        self,
        witness_name: impl Into<String>,
        observed: Value,
        next_private_state: Value,
    ) -> Self {
        self.with(witness_name, move |_args, _ps| {
            Ok(WitnessResult {
                observed: observed.clone(),
                next_private_state: next_private_state.clone(),
            })
        })
    }

    /// Register a fallback for any unscripted witness invocation.
    #[must_use]
    pub fn with_fallback<F>(mut self, f: F) -> Self
    where
        F: Fn(&str, &Value, &Value) -> Result<WitnessResult> + Send + Sync + 'static,
    {
        self.fallback = Some(std::sync::Arc::new(f));
        self
    }
}

impl Witnesses for ScriptedWitnesses {
    fn invoke(
        &self,
        witness_name: &str,
        args: &Value,
        private_state: &Value,
    ) -> Result<WitnessResult> {
        if let Some(f) = self.scripts.get(witness_name) {
            return f(args, private_state);
        }
        if let Some(f) = self.fallback.as_ref() {
            return f(witness_name, args, private_state);
        }
        Err(super::error::IrDriverError::Witness(format!(
            "mock witnesses received invocation for '{witness_name}' but no script \
             or fallback was registered; call `.with(\"{witness_name}\", ...)` \
             before deploy"
        )))
    }
}