newton-core 0.4.16

newton protocol core sdk
#![cfg(feature = "rpc")]

use crate::{
    generated::rego_verifier::IRegoVerifier::RegoContext,
    newton_prover_task_manager::INewtonProverTaskManager::{Task, TaskResponse},
    zk::Proof,
};
use tokio::task;

use risc0_ethereum_contracts::groth16;
use risc0_zkvm::{compute_image_id, default_prover, ExecutorEnv, InnerReceipt::Groth16, ProverOpts};

/// Proves the policy evaluation result using RISC0
/// # Arguments
/// * `elf` - The ELF binary to prove
/// * `task` - The task to prove
/// * `task_response` - The task response to prove
/// * `entrypoint` - The entrypoint to prove
/// # Returns
/// A `Result` containing the proof, or an error if the proof fails
pub async fn prove(elf: Vec<u8>, task: Task, task_response: TaskResponse, entrypoint: String) -> eyre::Result<Proof> {
    tracing::info!("Begin uploading input to Bonsai...");

    // Set RISC0_PROVER env to bonsai
    std::env::set_var("RISC0_PROVER", "bonsai");

    // BonsaiProver uses the reqwest blocking client as the default (and only option).
    // It will cause issues when running in async contexts unless explicitly ran in a task that can block (context)
    let (receipt, image_id) = task::spawn_blocking(move || {
        let mut builder = ExecutorEnv::builder();
        builder.write(&task).unwrap();
        builder.write(&task_response).unwrap();
        builder.write(&entrypoint).unwrap();
        let env = builder.build().unwrap();
        let receipt = default_prover()
            .prove_with_opts(env, &elf, &ProverOpts::groth16())
            .unwrap()
            .receipt;
        (receipt, compute_image_id(&elf).unwrap())
    })
    .await?;

    receipt.verify(image_id)?;

    let Groth16(snark_receipt) = receipt.clone().inner else {
        return Err(eyre::eyre!("Proof system is not Groth16, which is not supported yet"));
    };
    let journal = receipt.journal.bytes.clone();
    let seal = groth16::encode(snark_receipt.seal).map_err(|e| eyre::eyre!("Failed to encode seal: {}", e))?;

    tracing::info!("Journal: {}", crate::hex!(&journal));
    tracing::info!("Seal: {}", crate::hex!(&seal));

    Ok(Proof::Risc0 {
        receipt,
        image_id,
        seal,
    })
}