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
//! # 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::{fmt::Debug, fs::File, path::Path};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use sp1_hypercube::create_dummy_recursion_proof;
use sp1_primitives::io::SP1PublicValues;
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};
/// 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();
}
}