risc0_zkvm/host/client/prove/
external.rs

1// Copyright 2024 RISC Zero, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::path::{Path, PathBuf};
16
17use anyhow::{ensure, Result};
18
19use super::{Executor, Prover, ProverOpts};
20use crate::{
21    compute_image_id, host::api::AssetRequest, is_dev_mode, ApiClient, Asset, ExecutorEnv,
22    InnerReceipt, ProveInfo, Receipt, ReceiptKind, SessionInfo, VerifierContext,
23};
24
25/// An implementation of a [Prover] that runs proof workloads via an external
26/// `r0vm` process.
27pub struct ExternalProver {
28    name: String,
29    r0vm_path: PathBuf,
30}
31
32impl ExternalProver {
33    /// Construct an [ExternalProver].
34    pub fn new<P: AsRef<Path>>(name: &str, r0vm_path: P) -> Self {
35        Self {
36            name: name.to_string(),
37            r0vm_path: r0vm_path.as_ref().to_path_buf(),
38        }
39    }
40}
41
42impl Prover for ExternalProver {
43    fn prove_with_ctx(
44        &self,
45        env: ExecutorEnv<'_>,
46        ctx: &VerifierContext,
47        elf: &[u8],
48        opts: &ProverOpts,
49    ) -> Result<ProveInfo> {
50        tracing::debug!("Launching {}", &self.r0vm_path.to_string_lossy());
51
52        let image_id = compute_image_id(elf)?;
53        let client = ApiClient::new_sub_process(&self.r0vm_path)?;
54        let binary = Asset::Inline(elf.to_vec().into());
55        let prove_info = client.prove(&env, opts, binary)?;
56        if opts.prove_guest_errors {
57            prove_info.receipt.verify_integrity_with_context(ctx)?;
58        } else {
59            prove_info.receipt.verify_with_context(ctx, image_id)?;
60        }
61
62        Ok(prove_info)
63    }
64
65    fn get_name(&self) -> String {
66        self.name.clone()
67    }
68
69    fn compress(&self, opts: &ProverOpts, receipt: &Receipt) -> Result<Receipt> {
70        match (&receipt.inner, opts.receipt_kind) {
71            // Compression is a no-op when the requested kind is at least as large as the current.
72            (InnerReceipt::Composite(_), ReceiptKind::Composite)
73            | (InnerReceipt::Succinct(_), ReceiptKind::Composite | ReceiptKind::Succinct)
74            | (
75                InnerReceipt::Groth16(_),
76                ReceiptKind::Composite | ReceiptKind::Succinct | ReceiptKind::Groth16,
77            ) => Ok(receipt.clone()),
78            // Compression is always a no-op in dev mode
79            (InnerReceipt::Fake { .. }, _) => {
80                ensure!(
81                    is_dev_mode(),
82                    "dev mode must be enabled to compress fake receipts"
83                );
84                Ok(receipt.clone())
85            }
86            (_, _) => {
87                let client = ApiClient::new_sub_process(&self.r0vm_path)?;
88                client.compress(opts, receipt.clone().try_into()?, AssetRequest::Inline)
89            }
90        }
91    }
92}
93
94impl Executor for ExternalProver {
95    fn execute(&self, env: ExecutorEnv<'_>, elf: &[u8]) -> Result<SessionInfo> {
96        let binary = Asset::Inline(elf.to_vec().into());
97        let client = ApiClient::new_sub_process(&self.r0vm_path)?;
98        let segments_out = AssetRequest::Inline;
99        client.execute(&env, binary, segments_out, |_, _| Ok(()))
100    }
101}