risc0_zkvm/
lib.rs

1// Copyright 2025 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
15#![cfg_attr(not(feature = "std"), no_std)]
16#![deny(rustdoc::broken_intra_doc_links)]
17#![deny(missing_docs)]
18#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
19
20//! The RISC Zero zkVM is a RISC-V virtual machine that produces [zero-knowledge
21//! proofs] of code it executes. By using the zkVM, a cryptographic [receipt] is
22//! produced which anyone can [verify][receipt-verify] was produced by the
23//! zkVM's guest code. No additional information about the code execution (such
24//! as, for example, the inputs provided) is revealed by publishing the
25//! [receipt].
26//!
27//! Additional (non-reference) resources for using our zkVM that you may also
28//! find helpful, especially if you're new to the RISC Zero zkVM. These include:
29//!
30//! * Our [zkVM Tutorial], which walks you through writing your first zkVM
31//!   project.
32//! * The [`cargo risczero` tool]. It includes a `new` command which generates
33//!   code for building and launching a zkVM guest and guidance on where
34//!   projects most commonly modify host and guest code.
35//! * The [examples], which contains various examples using our zkVM.
36//! * [This clip][zkHack] from our presentation at ZK Hack III gives an overview
37//!   of the RISC Zero zkVM. [Our YouTube channel][YouTube] has many more videos
38//!   as well.
39//! * We track zkVM issues with known workarounds using the [rust guest
40//!   workarounds] GitHub tag. If you're having problems running your code in
41//!   the zkVM, you can see if there's a workaround, and if you're using a
42//!   workaround, you can track when it gets resolved to a permanent solution.
43//! * And more on [the RISC Zero developer website][dev-docs]!
44//!
45//! # Crate Feature Flags
46//!
47//! The following feature flags are supported.
48//!
49//! Note that in order to use `risc0-zkvm` in the guest, you must disable the
50//! default features by setting `default-features = false`.
51//!
52//! | Feature          | Target(s)         | Implies    | Description                                                                                                                                                  |
53//! | ---------------- | ----------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
54//! | client           | all except rv32im | std        | Enables the client API.                                                                                                                                      |
55//! | cuda             |                   | prove, std | Enables CUDA GPU acceleration for the prover. Requires CUDA toolkit to be installed.                                                                         |
56//! | disable-dev-mode | all except rv32im |            | Disables dev mode so that proving and verifying may not be faked. Used to prevent a misplaced `RISC0_DEV_MODE` from breaking security in production systems. |
57//! | metal            | macos             | prove, std | Deprecated - Metal GPU acceleration for the prover is now enabled by default on Apple Silicon.                                                               |
58//! | prove            | all except rv32im | std        | Enables the prover, incompatible within the zkvm guest.                                                                                                      |
59//! | std              | all               |            | Support for the Rust stdlib.                                                                                                                                 |
60//!
61//! [`cargo risczero` tool]: https://crates.io/crates/cargo-risczero
62//! [dev-docs]: https://dev.risczero.com
63//! [examples]: https://dev.risczero.com/api/zkvm/examples
64//! [receipt]: crate::receipt::Receipt
65//! [receipt-verify]: crate::receipt::Receipt::verify
66//! [rust guest workarounds]:
67//!     https://github.com/risc0/risc0/issues?q=is%3Aissue+is%3Aopen+label%3A%22rust+guest+workarounds%22
68//! [YouTube]: https://www.youtube.com/@risczero
69//! [zero-knowledge proofs]: https://en.wikipedia.org/wiki/Zero-knowledge_proof
70//! [zkHack]: https://youtu.be/cLqFvhmXiD0
71//! [zkVM Tutorial]: https://dev.risczero.com/api/zkvm/tutorials/hello-world
72
73extern crate alloc;
74
75mod claim;
76pub mod guest;
77#[cfg(not(target_os = "zkvm"))]
78mod host;
79mod mmr;
80mod receipt;
81pub mod serde;
82pub mod sha;
83
84pub use ::serde::de::DeserializeOwned;
85pub use anyhow::Result;
86pub use risc0_binfmt::{ExitCode, InvalidExitCodeError, SystemState};
87pub use risc0_zkp::core::digest::{digest, Digest};
88pub use risc0_zkvm_platform::{align_up, declare_syscall, memory::GUEST_MAX_MEM, PAGE_SIZE};
89
90#[cfg(not(target_os = "zkvm"))]
91#[cfg(any(feature = "client", feature = "prove"))]
92pub use bytes::Bytes;
93
94#[cfg(not(target_os = "zkvm"))]
95#[cfg(feature = "prove")]
96pub use self::host::{
97    api::server::Server as ApiServer,
98    client::prove::{local::LocalProver, local_executor},
99    recursion::{
100        self,
101        prove::{prove_registered_zkr, prove_zkr, register_zkr},
102        RECURSION_PO2,
103    },
104    server::{
105        exec::executor::ExecutorImpl,
106        prove::{
107            dev_mode::{DevModeDelay, DevModeProver},
108            get_prover_server, HalPair, ProverServer,
109        },
110        session::{
111            FileSegmentRef, NullSegmentRef, PreflightResults, Segment, SegmentRef, Session,
112            SessionEvents, SimpleSegmentRef,
113        },
114    },
115};
116
117#[cfg(not(target_os = "zkvm"))]
118#[cfg(feature = "bonsai")]
119pub use self::host::client::prove::bonsai::BonsaiProver;
120
121#[cfg(not(target_os = "zkvm"))]
122#[cfg(feature = "client")]
123pub use {
124    self::host::{
125        api::{
126            client::Client as ApiClient, Asset, AssetRequest, Connector, RedisParams, SegmentInfo,
127            SessionInfo,
128        },
129        client::{
130            env::{ExecutorEnv, ExecutorEnvBuilder},
131            prove::{
132                default::DefaultProver,
133                default_executor, default_prover,
134                external::ExternalProver,
135                opts::{ProverOpts, ReceiptKind},
136                Executor, Prover,
137            },
138        },
139    },
140    risc0_circuit_rv32im::trace::{TraceCallback, TraceEvent},
141};
142
143/// TODO
144#[cfg(not(target_os = "zkvm"))]
145#[cfg(feature = "client")]
146pub mod rpc {
147    pub use super::host::rpc::*;
148}
149
150#[cfg(not(target_os = "zkvm"))]
151#[cfg(feature = "client")]
152pub use self::host::client::env::{CoprocessorCallback, ProveKeccakRequest};
153
154#[cfg(not(target_os = "zkvm"))]
155pub use {
156    self::host::{
157        prove_info::{ProveInfo, SessionStats},
158        recursion::{ALLOWED_CONTROL_IDS, ALLOWED_CONTROL_ROOT},
159    },
160    risc0_binfmt::compute_image_id,
161    risc0_groth16::Seal as Groth16Seal,
162};
163
164pub use self::{
165    claim::{
166        maybe_pruned::{MaybePruned, PrunedValueError},
167        receipt::{Assumption, Assumptions, Input, Output, ReceiptClaim, UnionClaim},
168        work::{Work, WorkClaim},
169        Unknown,
170    },
171    receipt::{
172        AssumptionReceipt, CompositeReceipt, CompositeReceiptVerifierParameters, FakeReceipt,
173        GenericReceipt, Groth16Receipt, Groth16ReceiptVerifierParameters, InnerAssumptionReceipt,
174        InnerReceipt, Journal, Receipt, ReceiptMetadata, SegmentReceipt,
175        SegmentReceiptVerifierParameters, SuccinctReceipt, SuccinctReceiptVerifierParameters,
176        VerifierContext, DEFAULT_MAX_PO2,
177    },
178};
179
180use semver::Version;
181
182/// Reports the current version of this crate.
183pub const VERSION: &str = env!("CARGO_PKG_VERSION");
184
185/// Reports the current version of this crate as represented by a
186/// [semver::Version].
187pub fn get_version() -> Result<Version, semver::Error> {
188    Version::parse(VERSION)
189}
190
191/// Returns `true` if dev mode is enabled.
192#[cfg(feature = "std")]
193#[deprecated(
194    note = "dev-mode can be enabled programatically, so this function is no longer authoritative. \
195            Use `ProverOpts::is_dev_mode` or `VerifierContext::is_dev_mode`"
196)]
197pub fn is_dev_mode() -> bool {
198    is_dev_mode_enabled_via_environment()
199}
200
201/// Returns `true` if the dev mode environment variable is enabled, the `disable-dev-mode` cfg flag
202/// is not set, and we are not being compiled as a guest inside the zkvm.
203#[cfg(all(feature = "std", not(target_os = "zkvm")))]
204fn is_dev_mode_enabled_via_environment() -> bool {
205    let is_env_set = std::env::var("RISC0_DEV_MODE")
206        .ok()
207        .map(|x| x.to_lowercase())
208        .filter(|x| x == "1" || x == "true" || x == "yes")
209        .is_some();
210
211    let dev_mode_disabled = cfg!(feature = "disable-dev-mode");
212
213    if dev_mode_disabled && is_env_set {
214        panic!("zkVM: Inconsistent settings -- please resolve. \
215            The RISC0_DEV_MODE environment variable is set but dev mode has been disabled by feature flag.");
216    }
217
218    !dev_mode_disabled && is_env_set
219}
220
221/// Returns `true` if the dev mode environment variable is enabled, the `disable-dev-mode` cfg flag
222/// is not set, and we are not being compiled as a guest inside the zkvm.
223#[cfg(any(not(feature = "std"), target_os = "zkvm"))]
224fn is_dev_mode_enabled_via_environment() -> bool {
225    false
226}
227
228#[cfg(feature = "metal")]
229#[test]
230fn metal_implies_prove() {
231    // we should be able to access prove feature items when metal has been enabled
232    let _prover = get_prover_server(&ProverOpts::default());
233}