Skip to main content

moonproof_runtime/ir/
witnesses.rs

1//! Host-supplied witnesses callback.
2//!
3//! When a circuit calls a witness function (e.g. `localCount()` in the
4//! registry contract), the runtime needs the host to supply the
5//! current value AND a (possibly mutated) next private state. This
6//! trait is the contract.
7//!
8//! The shape mirrors the FFI `SigningProvider` — `Send + Sync`
9//! always (Schnorr-nonce-reuse defense), payloads cross via JSON so
10//! the same trait works through every FFI binding (`UniFFI` / NAPI /
11//! `PyO3`).
12
13use moonproof_runtime_ir::RuntimeValue as Value;
14
15use super::error::Result;
16
17/// A witness invocation result: the value the circuit observes, plus
18/// the rotated private state to thread into the next call.
19#[derive(Debug, Clone)]
20pub struct WitnessResult {
21    /// The value returned to the circuit (used in expressions, written
22    /// to the private transcript output, etc.).
23    pub observed: Value,
24    /// The new private-state value after this witness fired.
25    pub next_private_state: Value,
26}
27
28/// Host-side witness callback. Implementations decode the JSON-shaped
29/// args + private-state and produce a [`WitnessResult`].
30///
31/// `Send + Sync` is **load-bearing** — the runtime may invoke witness
32/// callbacks from worker threads (proof generation pools, async
33/// runtimes). Implementations that hold mutable host state must
34/// internally synchronize.
35pub trait Witnesses: Send + Sync + std::fmt::Debug {
36    /// Invoke the named witness with JSON-shaped args + the current
37    /// private state. Returns the observed value + the rotated
38    /// private state.
39    ///
40    /// `witness_name` is the entry from the IR's `witnesses[]` array
41    /// (e.g. `"localCount"`). `args` is the JSON encoding of the
42    /// circuit-call arguments forwarded into the witness call (most
43    /// witnesses take no args from the circuit; the JSON value is
44    /// `[]` in that case). `private_state` is the current host-side
45    /// private state.
46    fn invoke(
47        &self,
48        witness_name: &str,
49        args: &Value,
50        private_state: &Value,
51    ) -> Result<WitnessResult>;
52}
53
54/// A no-op witnesses provider — for contracts that have no witnesses
55/// (counter, mint, vault). Returns an error if any witness is
56/// invoked, surfacing the misconfiguration loudly rather than
57/// silently producing zero values.
58#[derive(Debug, Clone, Copy, Default)]
59pub struct NoWitnesses;
60
61impl Witnesses for NoWitnesses {
62    fn invoke(
63        &self,
64        witness_name: &str,
65        _args: &Value,
66        _private_state: &Value,
67    ) -> Result<WitnessResult> {
68        Err(super::error::IrDriverError::Witness(format!(
69            "contract invoked witness '{witness_name}' but NoWitnesses was supplied; \
70             pass a real Witnesses impl when constructing IrExecutable"
71        )))
72    }
73}
74
75type ScriptedHandler =
76    std::sync::Arc<dyn Fn(&Value, &Value) -> Result<WitnessResult> + Send + Sync>;
77type FallbackHandler =
78    std::sync::Arc<dyn Fn(&str, &Value, &Value) -> Result<WitnessResult> + Send + Sync>;
79
80/// Scripted-witnesses test helper. Register per-witness callbacks with
81/// [`Self::with`] / [`Self::with_const`]; unscripted witnesses fall through to
82/// the registered fallback (or error).
83#[derive(Clone, Default)]
84pub struct ScriptedWitnesses {
85    scripts: std::collections::HashMap<String, ScriptedHandler>,
86    fallback: Option<FallbackHandler>,
87}
88
89impl std::fmt::Debug for ScriptedWitnesses {
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        f.debug_struct("ScriptedWitnesses")
92            .field("scripts", &self.scripts.keys().collect::<Vec<_>>())
93            .field("has_fallback", &self.fallback.is_some())
94            .finish()
95    }
96}
97
98impl ScriptedWitnesses {
99    /// Construct an empty mock — every witness invocation errors until scripted.
100    #[must_use]
101    pub fn new() -> Self {
102        Self::default()
103    }
104
105    /// Register a callback for `witness_name`.
106    #[must_use]
107    pub fn with<F>(mut self, witness_name: impl Into<String>, f: F) -> Self
108    where
109        F: Fn(&Value, &Value) -> Result<WitnessResult> + Send + Sync + 'static,
110    {
111        self.scripts
112            .insert(witness_name.into(), std::sync::Arc::new(f));
113        self
114    }
115
116    /// Register a constant-value callback for `witness_name`.
117    #[must_use]
118    pub fn with_const(
119        self,
120        witness_name: impl Into<String>,
121        observed: Value,
122        next_private_state: Value,
123    ) -> Self {
124        self.with(witness_name, move |_args, _ps| {
125            Ok(WitnessResult {
126                observed: observed.clone(),
127                next_private_state: next_private_state.clone(),
128            })
129        })
130    }
131
132    /// Register a fallback for any unscripted witness invocation.
133    #[must_use]
134    pub fn with_fallback<F>(mut self, f: F) -> Self
135    where
136        F: Fn(&str, &Value, &Value) -> Result<WitnessResult> + Send + Sync + 'static,
137    {
138        self.fallback = Some(std::sync::Arc::new(f));
139        self
140    }
141}
142
143impl Witnesses for ScriptedWitnesses {
144    fn invoke(
145        &self,
146        witness_name: &str,
147        args: &Value,
148        private_state: &Value,
149    ) -> Result<WitnessResult> {
150        if let Some(f) = self.scripts.get(witness_name) {
151            return f(args, private_state);
152        }
153        if let Some(f) = self.fallback.as_ref() {
154            return f(witness_name, args, private_state);
155        }
156        Err(super::error::IrDriverError::Witness(format!(
157            "mock witnesses received invocation for '{witness_name}' but no script \
158             or fallback was registered; call `.with(\"{witness_name}\", ...)` \
159             before deploy"
160        )))
161    }
162}