moonproof-prover 0.2.2

Core ZK proof engine for Moonproof, dispatching across the Midnight ZKIR v2 + v3 pipelines (mirrors midnight-ledger's proof-server)
Documentation
//! Runs a ledger proving future off the caller's async runtime.
//!
//! Ledger 9 declares `Resolver::resolve_key` as an `async fn` in trait.
//! Such a future carries no `Send` bound, and the ledger awaits it deep
//! inside `Transaction::prove`, so the whole proving future is `!Send`
//! — which would otherwise infect every caller obliged to be `Send`
//! (`#[napi]` exports, `#[async_trait]` provider impls).
//!
//! To avoid spawning a fresh OS thread and constructing a fresh Tokio
//! `current_thread` runtime on every call, native builds dispatch onto a
//! lazily-initialized pool of persistent proving worker threads, each
//! owning a long-lived `current_thread` Tokio runtime.

use std::future::Future;

use crate::error::ProverError;

/// Build the proving future on a dedicated thread and await its result.
///
/// `build` runs on that thread, so the future it returns never has to
/// cross a thread boundary and needs no `Send` bound — only `build`
/// itself and the output do. On `wasm32`, where OS threads are not
/// available and futures are already single-threaded, `build` is awaited
/// directly on the caller's executor.
#[cfg(target_arch = "wasm32")]
pub async fn prove_offthread<T, F, Fut>(build: F) -> Result<T, ProverError>
where
    F: FnOnce() -> Fut + Send + 'static,
    Fut: Future<Output = T>,
    T: Send + 'static,
{
    Ok(build().await)
}

#[cfg(not(target_arch = "wasm32"))]
mod pool {
    use std::collections::VecDeque;
    use std::sync::{Arc, Condvar, Mutex, OnceLock};

    type Job = Box<dyn FnOnce(&tokio::runtime::Runtime) + Send + 'static>;

    struct Queue {
        jobs: Mutex<VecDeque<Job>>,
        ready: Condvar,
    }

    pub struct ProvingPool {
        queue: Arc<Queue>,
    }

    impl ProvingPool {
        fn global() -> Result<&'static Self, String> {
            static POOL: OnceLock<Result<ProvingPool, String>> = OnceLock::new();
            POOL.get_or_init(Self::start).as_ref().map_err(Clone::clone)
        }

        fn start() -> Result<Self, String> {
            let workers = num_cpus::get().clamp(2, 8);
            let queue = Arc::new(Queue {
                jobs: Mutex::new(VecDeque::new()),
                ready: Condvar::new(),
            });
            for idx in 0..workers {
                let q = Arc::clone(&queue);
                std::thread::Builder::new()
                    .name(format!("moonproof-prove-{idx}"))
                    .spawn(move || {
                        let rt = match tokio::runtime::Builder::new_current_thread()
                            .enable_all()
                            .build()
                        {
                            Ok(rt) => rt,
                            Err(e) => {
                                tracing::error!(
                                    worker = idx,
                                    error = %e,
                                    "proving worker could not build tokio runtime"
                                );
                                return;
                            }
                        };
                        loop {
                            let job = {
                                let mut guard = q.jobs.lock().expect("proving pool mutex poisoned");
                                loop {
                                    if let Some(job) = guard.pop_front() {
                                        break job;
                                    }
                                    guard =
                                        q.ready.wait(guard).expect("proving pool condvar poisoned");
                                }
                            };
                            job(&rt);
                        }
                    })
                    .map_err(|e| format!("spawn proving worker {idx}: {e}"))?;
            }
            Ok(Self { queue })
        }

        pub fn submit(job: Job) -> Result<(), String> {
            let pool = Self::global()?;
            let mut guard = pool
                .queue
                .jobs
                .lock()
                .map_err(|_| "proving pool mutex poisoned".to_owned())?;
            guard.push_back(job);
            drop(guard);
            pool.queue.ready.notify_one();
            Ok(())
        }
    }
}

/// Build the proving future on a persistent proving worker thread and await its
/// result.
///
/// `build` runs on that thread, so the future it returns never has to
/// cross a thread boundary and needs no `Send` bound — only `build`
/// itself and the output do.
#[cfg(not(target_arch = "wasm32"))]
pub async fn prove_offthread<T, F, Fut>(build: F) -> Result<T, ProverError>
where
    F: FnOnce() -> Fut + Send + 'static,
    Fut: Future<Output = T>,
    T: Send + 'static,
{
    let (tx, rx) = tokio::sync::oneshot::channel();
    pool::ProvingPool::submit(Box::new(move |rt| {
        let out = rt.block_on(build());
        // A closed receiver means the caller went away mid-proof.
        let _ = tx.send(out);
    }))
    .map_err(|e| ProverError::Proving(format!("dispatch proving job: {e}")))?;

    rx.await
        .map_err(|_| ProverError::Proving("proving thread ended without a result".to_owned()))
}

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

    #[tokio::test]
    async fn runs_a_non_send_future_and_returns_its_output() {
        // `Rc` is deliberately not `Send`; the future holding it across
        // the await is exactly the shape ledger 9 hands us.
        let out = prove_offthread(|| async {
            let local = std::rc::Rc::new(41);
            tokio::task::yield_now().await;
            *local + 1
        })
        .await
        .unwrap();
        assert_eq!(out, 42);
    }

    #[tokio::test]
    async fn propagates_the_inner_result() {
        let out: Result<u8, String> =
            prove_offthread(|| async { Err("circuit too large".to_owned()) })
                .await
                .unwrap();
        assert_eq!(out, Err("circuit too large".to_owned()));
    }
}