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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! # SP1 Proof
//!
//! A library of types and functions for SP1 proofs.
#![allow(missing_docs)]
#![allow(clippy::double_parens)] // For some reason we need this to use EnumTryAs
use std::{collections::BTreeMap, fmt::Debug, fs::File, path::Path};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use slop_algebra::AbstractField;
use slop_alloc::{CpuBackend, GLOBAL_CPU_BACKEND};
use slop_basefold::BasefoldProof;
use slop_commit::Rounds;
use slop_jagged::{JaggedPcsProof, JaggedSumcheckEvalProof};
use slop_multilinear::{Mle, MleEval, Point};
use slop_sumcheck::PartialSumcheckProof;
use slop_tensor::Tensor;
use sp1_hypercube::SP1PcsProof;
use sp1_hypercube::{
LogUpEvaluations, LogUpGkrOutput, LogupGkrProof, MerkleProof, SP1PcsProofInner,
SP1RecursionProof, ShardOpenedValues, ShardProof, DIGEST_SIZE,
};
use sp1_primitives::{io::SP1PublicValues, SP1ExtensionField, SP1Field, SP1GlobalContext};
use sp1_prover::{Groth16Bn254Proof, HashableKey, PlonkBn254Proof, SP1VerifyingKey};
// Re-export the types from the verifier crate in order to avoid importing the verifier crate
// for downstream dependencies.
pub use sp1_verifier::{ProofFromNetwork, SP1Proof, SP1ProofMode};
/// Creates a dummy recursion proof with minimal values for mock proof creation.
///
/// This is used internally for creating mock compressed proofs. The proof contains
/// valid structures but with zero/empty values since the mock verifier doesn't
/// actually verify the proof contents.
fn create_dummy_recursion_proof(
vk: &SP1VerifyingKey,
) -> SP1RecursionProof<SP1GlobalContext, SP1PcsProofInner> {
// Create minimal dummy values for the proof.
// These are the minimum required to satisfy the type system.
// Create dummy basefold proof.
let dummy_query_proof = Vec::new();
let basefold_proof = BasefoldProof::<SP1GlobalContext> {
univariate_messages: vec![],
fri_commitments: vec![],
final_poly: SP1ExtensionField::zero(),
pow_witness: SP1Field::zero(),
component_polynomials_query_openings_and_proofs: vec![],
query_phase_openings_and_proofs: dummy_query_proof,
};
let batch_evaluations: Rounds<MleEval<SP1ExtensionField, CpuBackend>> = Rounds::default();
let stacked_proof = SP1PcsProof { basefold_proof, batch_evaluations };
let jagged_eval_proof =
JaggedSumcheckEvalProof { partial_sumcheck_proof: PartialSumcheckProof::dummy() };
let evaluation_proof = JaggedPcsProof {
pcs_proof: stacked_proof,
jagged_eval_proof,
sumcheck_proof: PartialSumcheckProof::dummy(),
merkle_tree_commitments: Rounds::default(),
row_counts_and_column_counts: Rounds::default(),
expected_eval: SP1ExtensionField::zero(),
max_log_row_count: 1,
log_m: 1,
};
// Create dummy LogupGkrProof.
// Create empty Mle with minimal size using Tensor::zeros_in.
let empty_tensor: Tensor<SP1ExtensionField, CpuBackend> =
Tensor::zeros_in([1], GLOBAL_CPU_BACKEND);
let logup_gkr_proof = LogupGkrProof {
circuit_output: LogUpGkrOutput {
numerator: Mle::new(empty_tensor.clone()),
denominator: Mle::new(empty_tensor),
},
round_proofs: vec![],
logup_evaluations: LogUpEvaluations {
point: Point::from_usize(0, 1),
chip_openings: BTreeMap::new(),
},
};
// Create dummy ShardProof.
let dummy_shard_proof = ShardProof {
public_values: Vec::new(),
main_commitment: [SP1Field::zero(); DIGEST_SIZE],
logup_gkr_proof,
zerocheck_proof: PartialSumcheckProof::dummy(),
opened_values: ShardOpenedValues { chips: BTreeMap::new() },
evaluation_proof,
};
SP1RecursionProof {
vk: vk.vk.clone(),
proof: dummy_shard_proof,
vk_merkle_proof: MerkleProof { index: 0, path: vec![] },
}
}
/// Verify that the mock proof's public inputs match the expected values.
///
/// This is used by both the async and blocking mock provers to verify mock Plonk and Groth16 proofs.
pub(crate) fn verify_mock_public_inputs(
vkey: &SP1VerifyingKey,
public_values: &SP1PublicValues,
public_inputs: &[String; 5],
) -> Result<()> {
// Verify vkey hash matches (public_inputs[0]).
let expected_vkey_hash = vkey.hash_bn254().to_string();
if public_inputs[0] != expected_vkey_hash {
anyhow::bail!(
"vkey hash mismatch: expected {}, got {}",
expected_vkey_hash,
public_inputs[0]
);
}
// Verify public values hash matches (public_inputs[1]).
let expected_pv_hash = public_values.hash_bn254().to_string();
if public_inputs[1] != expected_pv_hash {
anyhow::bail!(
"public values hash mismatch: expected {}, got {}",
expected_pv_hash,
public_inputs[1]
);
}
Ok(())
}
/// A proof generated by the SP1 RISC-V zkVM bundled together with the public values and the
/// version.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SP1ProofWithPublicValues {
/// The raw proof generated by the SP1 RISC-V zkVM.
pub proof: SP1Proof,
/// The public values generated by the SP1 RISC-V zkVM.
pub public_values: SP1PublicValues,
/// The version of the SP1 RISC-V zkVM (not necessary but useful for detecting version
/// mismatches).
pub sp1_version: String,
/// The integrity proof generated by the TEE server.
pub tee_proof: Option<Vec<u8>>,
}
impl From<ProofFromNetwork> for SP1ProofWithPublicValues {
fn from(value: ProofFromNetwork) -> Self {
Self {
proof: value.proof,
public_values: value.public_values,
sp1_version: value.sp1_version,
tee_proof: None,
}
}
}
impl SP1ProofWithPublicValues {
/// Creates a new [`SP1ProofWithPublicValues`] from the proof, public values, and SP1 version.
///
/// If the [`tee`] feature is enabled, the proof field is set to none.
#[must_use]
pub const fn new(proof: SP1Proof, public_values: SP1PublicValues, sp1_version: String) -> Self {
Self { proof, public_values, sp1_version, tee_proof: None }
}
/// Saves the proof to a path.
pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
bincode::serialize_into(
File::create(path.as_ref()).with_context(|| {
format!("failed to create file for saving proof: {}", path.as_ref().display())
})?,
self,
)
.map_err(Into::into)
}
/// Loads a proof from a path.
pub fn load(path: impl AsRef<Path>) -> Result<Self> {
// Try to load a [`Self`] from the file.
let maybe_this: Result<Self> =
bincode::deserialize_from(File::open(path.as_ref()).with_context(|| {
format!("failed to open file for loading proof: {}", path.as_ref().display())
})?)
.map_err(Into::into);
// This may be a proof from the prover network, which lacks the TEE proof field.
match maybe_this {
Ok(this) => Ok(this),
Err(e) => {
// If the file does not contain a [`Self`], try to load a [`ProofFromNetwork`]
// instead.
let maybe_proof_from_network: Result<ProofFromNetwork> =
bincode::deserialize_from(File::open(path.as_ref()).with_context(|| {
format!(
"failed to open file for loading proof: {}",
path.as_ref().display()
)
})?)
.map_err(Into::into);
if let Ok(proof_from_network) = maybe_proof_from_network {
// The file contains a [`ProofFromNetwork`], which lacks the TEE proof field.
Ok(proof_from_network.into())
} else {
// Return the original error from trying to load a [`Self`].
Err(e)
}
}
}
}
/// The proof in the byte encoding the onchain verifiers accepts for [`SP1ProofMode::Groth16`]
/// and [`SP1ProofMode::Plonk`] proofs.
///
/// # Details
/// The bytes consist of the first four bytes of Groth16/Plonk vkey hash followed by the encoded
/// proof, in a form optimized for onchain verification.
#[must_use]
pub fn bytes(&self) -> Vec<u8> {
match &self.proof {
SP1Proof::Plonk(plonk_proof) => {
// If the proof is empty, then this is a mock proof. The mock SP1 verifier
// expects an empty byte array for verification, so return an empty byte array.
if plonk_proof.encoded_proof.is_empty() {
return Vec::new();
}
let proof_bytes =
hex::decode(&plonk_proof.encoded_proof).expect("Invalid Plonk proof");
if let Some(tee_proof) = &self.tee_proof {
return [
tee_proof.clone(),
plonk_proof.plonk_vkey_hash[..4].to_vec(),
proof_bytes,
]
.concat();
}
[plonk_proof.plonk_vkey_hash[..4].to_vec(), proof_bytes].concat()
}
SP1Proof::Groth16(groth16_proof) => {
// If the proof is empty, then this is a mock proof. The mock SP1 verifier
// expects an empty byte array for verification, so return an empty byte array.
if groth16_proof.encoded_proof.is_empty() {
return Vec::new();
}
let proof_bytes =
hex::decode(&groth16_proof.encoded_proof).expect("Invalid Groth16 proof");
if let Some(tee_proof) = &self.tee_proof {
return [
tee_proof.clone(),
groth16_proof.groth16_vkey_hash[..4].to_vec(),
proof_bytes,
]
.concat();
}
[groth16_proof.groth16_vkey_hash[..4].to_vec(), proof_bytes].concat()
}
proof => panic!(
"Proof type {proof} is not supported for onchain verification. \
Only Plonk and Groth16 proofs are verifiable onchain"
),
}
}
/// Creates a mock proof for the specified proof mode from the public values.
///
/// # Example
/// ```rust,no_run
/// use sp1_sdk::{
/// Elf, Prover, ProverClient, ProvingKey, SP1ProofMode, SP1ProofWithPublicValues, SP1Stdin,
/// SP1_CIRCUIT_VERSION,
/// };
///
/// tokio_test::block_on(async {
/// let elf = Elf::Static(&[1, 2, 3]);
/// let stdin = SP1Stdin::new();
///
/// let client = ProverClient::builder().cpu().build().await;
/// let pk = client.setup(elf.clone()).await.unwrap();
/// let (public_values, _) = client.execute(elf, stdin).await.unwrap();
///
/// // Create a mock Plonk proof.
/// let mock_proof = SP1ProofWithPublicValues::create_mock_proof(
/// &pk.verifying_key(),
/// public_values,
/// SP1ProofMode::Plonk,
/// SP1_CIRCUIT_VERSION,
/// );
/// });
/// ```
#[must_use]
#[allow(clippy::needless_pass_by_value)]
pub fn create_mock_proof(
vk: &SP1VerifyingKey,
public_values: SP1PublicValues,
mode: SP1ProofMode,
sp1_version: &str,
) -> Self {
let sp1_version = sp1_version.to_string();
match mode {
SP1ProofMode::Core => SP1ProofWithPublicValues {
proof: SP1Proof::Core(vec![]),
public_values,
sp1_version,
tee_proof: None,
},
SP1ProofMode::Compressed => {
// Create a mock compressed proof with dummy values.
let dummy_proof = create_dummy_recursion_proof(vk);
SP1ProofWithPublicValues {
proof: SP1Proof::Compressed(Box::new(dummy_proof)),
public_values,
sp1_version,
tee_proof: None,
}
}
SP1ProofMode::Plonk => {
// Create mock Plonk proof with correct public inputs.
// public_inputs[0]: vkey_hash
// public_inputs[1]: committed_values_digest (public_values hash)
// public_inputs[2]: exit_code (0 for success)
// public_inputs[3]: vk_root (0 for mock)
// public_inputs[4]: proof_nonce (0 for mock)
let vkey_hash = vk.hash_bn254().to_string();
let committed_values_digest = public_values.hash_bn254().to_string();
SP1ProofWithPublicValues {
proof: SP1Proof::Plonk(PlonkBn254Proof {
public_inputs: [
vkey_hash,
committed_values_digest,
"0".to_string(), // exit_code
"0".to_string(), // vk_root (mock)
"0".to_string(), // proof_nonce (mock)
],
encoded_proof: String::new(),
raw_proof: String::new(),
plonk_vkey_hash: [0; 32],
}),
public_values,
sp1_version,
tee_proof: None,
}
}
SP1ProofMode::Groth16 => {
// Create mock Groth16 proof with correct public inputs.
// public_inputs[0]: vkey_hash
// public_inputs[1]: committed_values_digest (public_values hash)
// public_inputs[2]: exit_code (0 for success)
// public_inputs[3]: vk_root (0 for mock)
// public_inputs[4]: proof_nonce (0 for mock)
let vkey_hash = vk.hash_bn254().to_string();
let committed_values_digest = public_values.hash_bn254().to_string();
SP1ProofWithPublicValues {
proof: SP1Proof::Groth16(Groth16Bn254Proof {
public_inputs: [
vkey_hash,
committed_values_digest,
"0".to_string(), // exit_code
"0".to_string(), // vk_root (mock)
"0".to_string(), // proof_nonce (mock)
],
encoded_proof: String::new(),
raw_proof: String::new(),
groth16_vkey_hash: [0; 32],
}),
public_values,
sp1_version,
tee_proof: None,
}
}
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::print_stdout)]
use sp1_prover::{Groth16Bn254Proof, PlonkBn254Proof};
use super::*;
#[test]
fn test_plonk_proof_bytes() {
let plonk_proof = SP1ProofWithPublicValues {
proof: SP1Proof::Plonk(PlonkBn254Proof {
encoded_proof: "ab".to_string(),
plonk_vkey_hash: [0; 32],
public_inputs: [
String::new(),
String::new(),
String::new(),
String::new(),
String::new(),
],
raw_proof: String::new(),
}),
public_values: SP1PublicValues::new(),
sp1_version: String::new(),
tee_proof: None,
};
let expected_bytes = [vec![0, 0, 0, 0], hex::decode("ab").unwrap()].concat();
assert_eq!(plonk_proof.bytes(), expected_bytes);
}
#[test]
fn test_groth16_proof_bytes() {
let groth16_proof = SP1ProofWithPublicValues {
proof: SP1Proof::Groth16(Groth16Bn254Proof {
encoded_proof: "ab".to_string(),
groth16_vkey_hash: [0; 32],
public_inputs: [
String::new(),
String::new(),
String::new(),
String::new(),
String::new(),
],
raw_proof: String::new(),
}),
public_values: SP1PublicValues::new(),
sp1_version: String::new(),
tee_proof: None,
};
let expected_bytes = [vec![0, 0, 0, 0], hex::decode("ab").unwrap()].concat();
assert_eq!(groth16_proof.bytes(), expected_bytes);
}
#[test]
fn test_mock_plonk_proof_bytes() {
let mock_plonk_proof = SP1ProofWithPublicValues {
proof: SP1Proof::Plonk(PlonkBn254Proof {
encoded_proof: String::new(),
plonk_vkey_hash: [0; 32],
public_inputs: [
String::new(),
String::new(),
String::new(),
String::new(),
String::new(),
],
raw_proof: String::new(),
}),
public_values: SP1PublicValues::new(),
sp1_version: String::new(),
tee_proof: None,
};
assert_eq!(mock_plonk_proof.bytes(), Vec::<u8>::new());
}
#[test]
fn test_mock_groth16_proof_bytes() {
let mock_groth16_proof = SP1ProofWithPublicValues {
proof: SP1Proof::Groth16(Groth16Bn254Proof {
encoded_proof: String::new(),
groth16_vkey_hash: [0; 32],
public_inputs: [
String::new(),
String::new(),
String::new(),
String::new(),
String::new(),
],
raw_proof: String::new(),
}),
public_values: SP1PublicValues::new(),
sp1_version: String::new(),
tee_proof: None,
};
assert_eq!(mock_groth16_proof.bytes(), Vec::<u8>::new());
}
#[test]
#[should_panic(
expected = "Proof type Core is not supported for onchain verification. Only Plonk and Groth16 proofs are verifiable onchain"
)]
fn test_core_proof_bytes_unimplemented() {
let core_proof = SP1ProofWithPublicValues {
proof: SP1Proof::Core(vec![]),
public_values: SP1PublicValues::new(),
sp1_version: String::new(),
tee_proof: None,
};
println!("{:?}", core_proof.bytes());
}
#[test]
fn test_deser_backwards_compat() {
let round_trip = SP1ProofWithPublicValues {
proof: SP1Proof::Core(vec![]),
public_values: SP1PublicValues::new(),
sp1_version: String::new(),
tee_proof: None,
};
let round_trip_bytes = bincode::serialize(&round_trip).unwrap();
bincode::deserialize::<SP1ProofWithPublicValues>(&round_trip_bytes).unwrap();
let _ = ProofFromNetwork {
proof: SP1Proof::Core(vec![]),
public_values: SP1PublicValues::new(),
sp1_version: String::new(),
};
let _ = bincode::deserialize::<ProofFromNetwork>(&round_trip_bytes).unwrap();
}
#[tokio::test]
#[cfg(feature = "slow-tests")]
async fn test_round_trip_proof_save_load() {
use crate::{ProveRequest, Prover};
let prover = crate::CpuProver::new().await;
let pk = prover.setup(test_artifacts::FIBONACCI_BLAKE3_ELF).await.unwrap();
let proof = prover.prove(&pk, crate::SP1Stdin::new()).compressed().await.unwrap();
// Verify the original proof
prover.verify(&proof, &pk.vk, None).unwrap();
let temp_dir = tempfile::tempdir().unwrap();
let path = temp_dir.path().join("proof.bin");
std::fs::File::create(&path).unwrap();
proof.save(&path).unwrap();
let proof_loaded = SP1ProofWithPublicValues::load(&path).unwrap();
// Verify the loaded proof
prover.verify(&proof_loaded, &pk.vk, None).unwrap();
}
}