Skip to content

Commit

Permalink
refactor(provers): clean up imports and errors (#315)
Browse files Browse the repository at this point in the history
* refactor(provers): clean up imports and errors

* fix(sgx): clippy fixes

* fix(risc0): fix return type

* fix(sp1): add tracing and fix typo

* fix(sp1): add tracing to enabled crates

* refactor(risc0): rename variable
  • Loading branch information
petarvujovic98 authored Jul 9, 2024
1 parent ae8858c commit 65c1758
Show file tree
Hide file tree
Showing 18 changed files with 73 additions and 159 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 8 additions & 7 deletions provers/risc0/driver/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
#![cfg(feature = "enable")]
use std::fmt::Debug;

use alloy_primitives::B256;

use hex::ToHex;

use raiko_lib::{
input::{GuestInput, GuestOutput},
prover::{to_proof, Proof, Prover, ProverConfig, ProverResult},
prover::{to_proof, Proof, Prover, ProverConfig, ProverError, ProverResult},
};
use risc0_zkvm::{serde::to_vec, sha::Digest};
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use tracing::info as traicing_info;
use std::fmt::Debug;
use tracing::{debug, info as traicing_info};

use crate::{
methods::risc0_guest::{RISC0_GUEST_ELF, RISC0_GUEST_ID},
snarks::verify_groth16_snark,
};

pub use bonsai::*;

pub mod bonsai;
Expand Down Expand Up @@ -47,7 +46,7 @@ impl Prover for Risc0Prover {
) -> ProverResult<Proof> {
let config = Risc0Param::deserialize(config.get("risc0").unwrap()).unwrap();

println!("elf code length: {}", RISC0_GUEST_ELF.len());
debug!("elf code length: {}", RISC0_GUEST_ELF.len());
let encoded_input = to_vec(&input).expect("Could not serialize proving input!");

let result = maybe_prove::<GuestInput, B256>(
Expand All @@ -64,7 +63,9 @@ impl Prover for Risc0Prover {
// Create/verify Groth16 SNARK
if config.snark {
let Some((stark_uuid, stark_receipt)) = result else {
panic!("No STARK data to snarkify!");
return Err(ProverError::GuestError(
"No STARK data to snarkify!".to_owned(),
));
};
let image_id = Digest::from(RISC0_GUEST_ID);
let (snark_uuid, snark_receipt) =
Expand Down
4 changes: 2 additions & 2 deletions provers/risc0/guest/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions provers/risc0/guest/src/benchmark/sha256.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
#![no_main]
harness::entrypoint!(main);
use revm_precompile::zk_op::ZkvmOperator;
use risc0_zkvm::guest::env;
use std::hint::black_box;

use revm_precompile::zk_op::ZkvmOperator;
use zk_op::Risc0Operator;

fn main() {
Expand Down
9 changes: 3 additions & 6 deletions provers/risc0/guest/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
#![no_main]
harness::entrypoint!(main, tests, zk_op::tests);
use risc0_zkvm::guest::env;

use raiko_lib::protocol_instance::ProtocolInstance;
use raiko_lib::{
consts::VerifierType,
builder::calculate_block_header,
input::GuestInput,
builder::calculate_block_header, consts::VerifierType, input::GuestInput,
protocol_instance::ProtocolInstance,
};
use revm_precompile::zk_op::ZkOperation;
use risc0_zkvm::guest::env;
use zk_op::Risc0Operator;

pub mod mem;
Expand Down
2 changes: 1 addition & 1 deletion provers/risc0/guest/src/zk_op.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ harness::zk_suits!(
for v in test_ves.iter() {
let (input, expected) = *v;
let result: [u8; 32] = Sha256::digest(input.as_bytes()).into();
assert!(result == expected);
assert_eq!(result, expected);
}
}
}
Expand Down
17 changes: 10 additions & 7 deletions provers/sgx/guest/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
mod app_args;
mod one_shot;
mod signature;

extern crate rand;
extern crate secp256k1;

use anyhow::{anyhow, Result};
use app_args::{App, Command};
use clap::Parser;
use one_shot::{bootstrap, load_bootstrap, one_shot};

use crate::{
app_args::{App, Command},
one_shot::{bootstrap, load_bootstrap, one_shot},
};

mod app_args;
mod one_shot;
mod signature;

#[tokio::main]
pub async fn main() -> Result<()> {
Expand All @@ -26,7 +29,7 @@ pub async fn main() -> Result<()> {
Command::Check => {
println!("Checking if bootstrap is readable");
load_bootstrap(&args.global_opts.secrets_dir)
.map_err(|err| anyhow!("check booststrap failed: {}", err))?;
.map_err(|err| anyhow!("check booststrap failed: {err}"))?;
}
}

Expand Down
85 changes: 0 additions & 85 deletions provers/sgx/guest/src/setup_bootstrap.rs

This file was deleted.

6 changes: 3 additions & 3 deletions provers/sgx/prover/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#![cfg(feature = "enable")]

use std::{
env,
fs::{copy, create_dir_all, remove_file},
Expand Down Expand Up @@ -277,8 +278,7 @@ async fn prove(
Ok(parse_sgx_result(output.stdout)?)
}
(Err(i), output_success) => Err(ProverError::GuestError(format!(
"Can not serialize input for SGX {}, output is {:?}",
i, output_success
"Can not serialize input for SGX {i}, output is {output_success:?}"
))),
(Ok(_), Err(output_err)) => Err(ProverError::GuestError(
handle_gramine_error("Could not run SGX guest prover", output_err).to_string(),
Expand Down Expand Up @@ -315,7 +315,7 @@ fn parse_sgx_result(output: Vec<u8>) -> ProverResult<SgxResponse, String> {

fn handle_gramine_error(context: &str, err: std::io::Error) -> String {
if let std::io::ErrorKind::NotFound = err.kind() {
format!("gramine could not be found, please install gramine first. ({err})",)
format!("gramine could not be found, please install gramine first. ({err})")
} else {
format!("{context}: {err}")
}
Expand Down
24 changes: 9 additions & 15 deletions provers/sgx/prover/src/sgx_register_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,11 @@ const REGISTERED_FILE: &str = "registered";

pub fn get_instance_id(dir: &Path) -> Result<Option<u64>> {
let file = dir.join(REGISTERED_FILE);
let id = match fs::read_to_string(file) {
Ok(t) => Some(t.parse()?),
Err(e) => {
if e.kind() == io::ErrorKind::NotFound {
None
} else {
return Err(e.into());
}
}
};
Ok(id)
match fs::read_to_string(file) {
Ok(t) => Ok(Some(t.parse()?)),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}

pub fn set_instance_id(dir: &Path, id: u64) -> io::Result<()> {
Expand Down Expand Up @@ -276,7 +270,7 @@ pub async fn register_sgx_instance(
let sender_priv_key = env::var("SENDER_PRIV_KEY").expect("SENDER_PRIV_KEY is not set");
let mut wallet: PrivateKeySigner = sender_priv_key.as_str().parse().unwrap();
wallet.set_chain_id(Some(chain_id));
println!("wallet: {:?}", wallet);
println!("wallet: {wallet:?}");

// init rpc conn
let http = Http::new(Url::parse(l1_rpc_url).expect("invalid rpc url"));
Expand Down Expand Up @@ -321,7 +315,7 @@ pub async fn register_sgx_instance(

let log = tx_receipt.inner.as_receipt().unwrap().logs.first().unwrap();
let sgx_id: u64 = u64::from_be_bytes(log.topics()[1].0[24..].try_into().unwrap());
println!("register sgx instance id: {:?}", sgx_id);
println!("register sgx instance id: {sgx_id:?}");

Ok(sgx_id)
}
Expand All @@ -341,7 +335,7 @@ mod test {
#[test]
fn test_parse_quote() {
let parsed_quote = parse_quote(SAMPLE_QUOTE[1]);
println!("{:?}", parsed_quote);
println!("{parsed_quote:?}");
}

#[ignore = "anvil test"]
Expand All @@ -351,7 +345,7 @@ mod test {
let res = rt
.block_on(simple_test_register_sgx_instance(SAMPLE_QUOTE[0]))
.unwrap();
println!("test_tx_call_register {:?}", res);
println!("test_tx_call_register {res:?}");
}

async fn simple_test_register_sgx_instance(
Expand Down
15 changes: 9 additions & 6 deletions provers/sgx/setup/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
mod app_args;
mod setup_bootstrap;

use anyhow::Result;
use app_args::{App, Command};
use clap::Parser;
use setup_bootstrap::setup_bootstrap;

use crate::{
app_args::{App, Command},
setup_bootstrap::setup_bootstrap,
};

mod app_args;
mod setup_bootstrap;

#[tokio::main]
pub async fn main() -> Result<()> {
let args = App::parse();

match args.command {
Command::Bootstrap(sgx_bootstrap_args) => {
println!("Setup bootstrapping: {:?}", sgx_bootstrap_args);
println!("Setup bootstrapping: {sgx_bootstrap_args:?}");
setup_bootstrap(
args.global_opts.secrets_dir,
args.global_opts.config_dir,
Expand Down
11 changes: 6 additions & 5 deletions provers/sgx/setup/src/setup_bootstrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@ use std::{
fs::{self, File},
io::BufReader,
path::PathBuf,
process::Command,
};

use crate::app_args::BootstrapArgs;
use anyhow::{anyhow, Context, Result};
use raiko_lib::consts::{SupportedChainSpecs, VerifierType};
use serde_json::{Number, Value};
use sgx_prover::{
bootstrap, check_bootstrap, get_instance_id, register_sgx_instance, remove_instance_id,
set_instance_id, ELF_NAME,
};
use std::process::Command;

use crate::app_args::BootstrapArgs;

pub(crate) async fn setup_bootstrap(
secret_dir: PathBuf,
Expand Down Expand Up @@ -46,13 +47,13 @@ pub(crate) async fn setup_bootstrap(
let need_init = check_bootstrap(secret_dir.clone(), gramine_cmd())
.await
.map_err(|e| {
println!("Error checking bootstrap: {:?}", e);
println!("Error checking bootstrap: {e:?}");
e
})
.is_err()
|| instance_id.is_none();

println!("Instance ID: {:?}", instance_id);
println!("Instance ID: {instance_id:?}");

if need_init {
// clean check file
Expand All @@ -70,7 +71,7 @@ pub(crate) async fn setup_bootstrap(
)
.await
.map_err(|e| anyhow::Error::msg(e.to_string()))?;
println!("Saving instance id {}", register_id,);
println!("Saving instance id {register_id}");
// set check file
set_instance_id(&config_dir, register_id)?;

Expand Down
Loading

0 comments on commit 65c1758

Please sign in to comment.