risc0_zkvm/host/server/prove/mod.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
// Copyright 2024 RISC Zero, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Run the zkVM guest and prove its results.
mod dev_mode;
pub(crate) mod keccak;
mod prover_impl;
#[cfg(test)]
mod tests;
use std::rc::Rc;
use anyhow::{anyhow, bail, ensure, Result};
use risc0_core::field::baby_bear::{BabyBear, Elem, ExtElem};
use risc0_zkp::hal::{CircuitHal, Hal};
use self::{dev_mode::DevModeProver, prover_impl::ProverImpl};
use crate::{
host::prove_info::ProveInfo,
is_dev_mode,
receipt::{
CompositeReceipt, Groth16Receipt, Groth16ReceiptVerifierParameters, InnerAssumptionReceipt,
InnerReceipt, SegmentReceipt, SuccinctReceipt,
},
receipt_claim::Unknown,
sha::Digestible,
stark_to_snark, ExecutorEnv, ExecutorImpl, ProverOpts, Receipt, ReceiptClaim, ReceiptKind,
Segment, Session, VerifierContext,
};
/// A ProverServer can execute a given ELF binary and produce a [ProveInfo] which contains a
/// [Receipt][crate::Receipt] that can be used to verify correct computation.
pub trait ProverServer {
/// Prove the specified keccak request
#[cfg(feature = "unstable")]
fn prove_keccak(&self, request: &crate::ProveKeccakRequest)
-> Result<SuccinctReceipt<Unknown>>;
/// Prove the specified ELF binary.
fn prove(&self, env: ExecutorEnv<'_>, elf: &[u8]) -> Result<ProveInfo> {
self.prove_with_ctx(env, &VerifierContext::default(), elf)
}
/// Prove the specified ELF binary using the specified [VerifierContext].
fn prove_with_ctx(
&self,
env: ExecutorEnv<'_>,
ctx: &VerifierContext,
elf: &[u8],
) -> Result<ProveInfo> {
let mut exec = ExecutorImpl::from_elf(env, elf)?;
let session = exec.run()?;
self.prove_session(ctx, &session)
}
/// Prove the specified [Session].
fn prove_session(&self, ctx: &VerifierContext, session: &Session) -> Result<ProveInfo>;
/// Prove the specified [Segment].
fn prove_segment(&self, ctx: &VerifierContext, segment: &Segment) -> Result<SegmentReceipt>;
/// Lift a [SegmentReceipt] into a [SuccinctReceipt]
fn lift(&self, receipt: &SegmentReceipt) -> Result<SuccinctReceipt<ReceiptClaim>>;
/// Join two [SuccinctReceipt] into a [SuccinctReceipt]
fn join(
&self,
a: &SuccinctReceipt<ReceiptClaim>,
b: &SuccinctReceipt<ReceiptClaim>,
) -> Result<SuccinctReceipt<ReceiptClaim>>;
/// Resolve an assumption from a conditional [SuccinctReceipt] by providing a [SuccinctReceipt]
/// proving the validity of the assumption.
fn resolve(
&self,
conditional: &SuccinctReceipt<ReceiptClaim>,
assumption: &SuccinctReceipt<Unknown>,
) -> Result<SuccinctReceipt<ReceiptClaim>>;
/// Convert a [SuccinctReceipt] with a Poseidon hash function that uses a 254-bit field
fn identity_p254(
&self,
a: &SuccinctReceipt<ReceiptClaim>,
) -> Result<SuccinctReceipt<ReceiptClaim>>;
/// Compress a [CompositeReceipt] into a single [SuccinctReceipt].
///
/// A [CompositeReceipt] may contain an arbitrary number of receipts assembled into
/// segments and assumptions. Together, these receipts collectively prove a top-level
/// [ReceiptClaim](crate::ReceiptClaim). This function compresses all of the constituent receipts of a
/// [CompositeReceipt] into a single [SuccinctReceipt] that proves the same top-level claim. It
/// accomplishes this by iterative application of the recursion programs including lift, join,
/// and resolve.
fn composite_to_succinct(
&self,
receipt: &CompositeReceipt,
) -> Result<SuccinctReceipt<ReceiptClaim>> {
// Compress all receipts in the top-level session into one succinct receipt for the session.
let continuation_receipt = receipt
.segments
.iter()
.try_fold(
None,
|left: Option<SuccinctReceipt<ReceiptClaim>>,
right: &SegmentReceipt|
-> Result<_> {
Ok(Some(match left {
Some(left) => self.join(&left, &self.lift(right)?)?,
None => self.lift(right)?,
}))
},
)?
.ok_or(anyhow!(
"malformed composite receipt has no continuation segment receipts"
))?;
// Compress assumptions and resolve them to get the final succinct receipt.
receipt.assumption_receipts.iter().try_fold(
continuation_receipt,
|conditional: SuccinctReceipt<ReceiptClaim>, assumption: &InnerAssumptionReceipt| match assumption {
InnerAssumptionReceipt::Succinct(assumption) => self.resolve(&conditional, assumption),
InnerAssumptionReceipt::Composite(assumption) => {
self.resolve(&conditional, &self.composite_to_succinct(assumption)?.into_unknown())
}
InnerAssumptionReceipt::Fake(_) => bail!(
"compressing composite receipts with fake receipt assumptions is not supported"
),
InnerAssumptionReceipt::Groth16(_) => bail!(
"compressing composite receipts with Groth16 receipt assumptions is not supported"
)
},
)
}
/// Compress a [SuccinctReceipt] into a [Groth16Receipt].
fn succinct_to_groth16(
&self,
receipt: &SuccinctReceipt<ReceiptClaim>,
) -> Result<Groth16Receipt<ReceiptClaim>> {
let ident_receipt = self.identity_p254(receipt).unwrap();
let seal_bytes = ident_receipt.get_seal_bytes();
let seal = stark_to_snark(&seal_bytes)?.to_vec();
Ok(Groth16Receipt {
seal,
claim: receipt.claim.clone(),
verifier_parameters: Groth16ReceiptVerifierParameters::default().digest(),
})
}
/// Compress a receipt into one with a smaller representation.
///
/// The requested target representation is determined by the [ReceiptKind] specified on the
/// provided [ProverOpts]. If the receipt is already at least as compressed as the requested
/// kind, this is a no-op.
fn compress(&self, opts: &ProverOpts, receipt: &Receipt) -> Result<Receipt> {
match &receipt.inner {
InnerReceipt::Composite(inner) => match opts.receipt_kind {
ReceiptKind::Composite => Ok(receipt.clone()),
ReceiptKind::Succinct => {
let succinct_receipt = self.composite_to_succinct(inner)?;
Ok(Receipt::new(
InnerReceipt::Succinct(succinct_receipt),
receipt.journal.bytes.clone(),
))
}
ReceiptKind::Groth16 => {
let succinct_receipt = self.composite_to_succinct(inner)?;
let groth16_receipt = self.succinct_to_groth16(&succinct_receipt)?;
Ok(Receipt::new(
InnerReceipt::Groth16(groth16_receipt),
receipt.journal.bytes.clone(),
))
}
},
InnerReceipt::Succinct(inner) => match opts.receipt_kind {
ReceiptKind::Composite | ReceiptKind::Succinct => Ok(receipt.clone()),
ReceiptKind::Groth16 => {
let groth16_receipt = self.succinct_to_groth16(inner)?;
Ok(Receipt::new(
InnerReceipt::Groth16(groth16_receipt),
receipt.journal.bytes.clone(),
))
}
},
InnerReceipt::Groth16(_) => match opts.receipt_kind {
ReceiptKind::Composite | ReceiptKind::Succinct | ReceiptKind::Groth16 => {
Ok(receipt.clone())
}
},
InnerReceipt::Fake(_) => {
ensure!(
is_dev_mode(),
"dev mode must be enabled to compress fake receipts"
);
Ok(receipt.clone())
}
}
}
}
/// A pair of [Hal] and [CircuitHal].
#[derive(Clone)]
pub struct HalPair<H, C>
where
H: Hal<Field = BabyBear, Elem = Elem, ExtElem = ExtElem>,
C: CircuitHal<H>,
{
/// A [Hal] implementation.
pub hal: Rc<H>,
/// An [CircuitHal] implementation.
pub circuit_hal: Rc<C>,
}
impl Session {
/// For each segment, call [ProverServer::prove_session] and collect the
/// receipts.
pub fn prove(&self) -> Result<ProveInfo> {
let prover = get_prover_server(&ProverOpts::default())?;
prover.prove_session(&VerifierContext::default(), self)
}
}
/// Select a [ProverServer] based on the specified [ProverOpts] and currently
/// compiled features.
pub fn get_prover_server(opts: &ProverOpts) -> Result<Rc<dyn ProverServer>> {
if is_dev_mode() {
eprintln!("WARNING: proving in dev mode. This will not generate valid, secure proofs.");
return Ok(Rc::new(DevModeProver));
}
Ok(Rc::new(ProverImpl::new(opts.clone())))
}