Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Bonsai pay example to 1.0 #29

Closed
austinabell opened this issue Jun 19, 2024 · 1 comment
Closed

Update Bonsai pay example to 1.0 #29

austinabell opened this issue Jun 19, 2024 · 1 comment

Comments

@austinabell
Copy link
Contributor

A dev from Discord was asking, I got half of the way there, but realized it was more of an effort to update contracts and APIs around it, since those have changed a lot.

Here is the diff so far:

diff --git a/bonsai-pay/Cargo.toml b/bonsai-pay/Cargo.toml
index 4beb377..3d351ff 100644
--- a/bonsai-pay/Cargo.toml
+++ b/bonsai-pay/Cargo.toml
@@ -12,18 +12,17 @@ alloy-primitives = { version = "0.6", default-features = false, features = ["rlp
 alloy-sol-types = { version = "0.6" }
 anyhow = { version = "1.0.75" }
 bincode = { version = "1.3" }
-bonsai-sdk = { version = "0.7" }
 bytemuck = { version = "1.14" }
 ethers = { version = "2.0" }
 hex = { version = "0.4" }
 log = { version = "0.4" }
 methods = { path = "./methods" }
 oidc-validator = { path = "./oidc-validator" }
-risc0-build = { version = "0.21", features = ["docker"] }
-risc0-build-ethereum = { git = "https://github.com/risc0/risc0-ethereum", branch = "release-0.8" }
-risc0-ethereum-contracts = { git = "https://github.com/risc0/risc0-ethereum", branch = "release-0.8" }
-risc0-zkvm = { version = "0.21", default-features = false }
-risc0-zkp = { version = "0.21", default-features = false }
+risc0-build = { version = "1.0.1", features = ["docker"] }
+risc0-build-ethereum = { git = "https://github.com/risc0/risc0-ethereum", branch = "release-1.0" }
+risc0-ethereum-contracts = { git = "https://github.com/risc0/risc0-ethereum", branch = "release-1.0" }
+risc0-zkvm = { version = "1.0.1", default-features = false }
+risc0-zkp = { version = "1.0.1", default-features = false }
 serde = { version = "1.0", features = ["derive", "std"] }
 
 [profile.release]
diff --git a/bonsai-pay/apps/Cargo.toml b/bonsai-pay/apps/Cargo.toml
index 5fce08e..3e76657 100644
--- a/bonsai-pay/apps/Cargo.toml
+++ b/bonsai-pay/apps/Cargo.toml
@@ -8,7 +8,6 @@ alloy-primitives = { workspace = true }
 alloy-sol-types = { workspace = true }
 anyhow = { workspace = true }
 bincode = { workspace = true }
-bonsai-sdk = { workspace = true }
 bytemuck = { workspace = true }
 clap = { version = "4.0", features = ["derive", "env"] }
 env_logger = { version = "0.10" }
diff --git a/bonsai-pay/apps/src/bin/pubsub.rs b/bonsai-pay/apps/src/bin/pubsub.rs
index d1a59a8..3e685e0 100644
--- a/bonsai-pay/apps/src/bin/pubsub.rs
+++ b/bonsai-pay/apps/src/bin/pubsub.rs
@@ -15,10 +15,12 @@
 use alloy_primitives::{FixedBytes, U256};
 use alloy_sol_types::{sol, SolInterface, SolValue};
 use anyhow::Context;
-use apps::{BonsaiProver, TxSender};
+use apps::TxSender;
 use clap::Parser;
 use log::info;
 use methods::JWT_VALIDATOR_ELF;
+use risc0_ethereum_contracts::groth16;
+use risc0_zkvm::{default_prover, ExecutorEnv, ProverOpts, VerifierContext};
 use tokio::sync::oneshot;
 use warp::Filter;
 
@@ -92,11 +94,24 @@ fn prove_and_send_transaction(
         jwt: token,
     };
 
-    let (journal, post_state_digest, seal) =
-        BonsaiProver::prove(JWT_VALIDATOR_ELF, &input.abi_encode())
-            .expect("failed to prove on bonsai");
-
-    let seal_clone = seal.clone();
+    let env = ExecutorEnv::builder()
+        .write_slice(&input.abi_encode())
+        .build()
+        .unwrap();
+    let receipt = default_prover()
+        .prove_with_ctx(
+            env,
+            &VerifierContext::default(),
+            JWT_VALIDATOR_ELF,
+            &ProverOpts::groth16(),
+        )
+        .unwrap()
+        .receipt;
+    // let (journal, post_state_digest, seal) =
+    //     BonsaiProver::prove(JWT_VALIDATOR_ELF, &input.abi_encode())
+    //         .expect("failed to prove on bonsai");
+
+    let seal = groth16::encode(receipt.inner.groth16().unwrap().seal.clone()).unwrap();
 
     let tx_sender = TxSender::new(
         args.chain_id,
@@ -106,7 +121,7 @@ fn prove_and_send_transaction(
     )
     .expect("failed to create tx sender");
 
-    let claims = ClaimsData::abi_decode(&journal, true)
+    let claims = ClaimsData::abi_decode(&receipt.journal.bytes, true)
         .context("decoding journal data")
         .expect("failed to decode");
 
@@ -116,8 +131,9 @@ fn prove_and_send_transaction(
     let calldata = IBonsaiPay::IBonsaiPayCalls::claim(IBonsaiPay::claimCall {
         to: claims.msg_sender,
         claim_id: claims.claim_id,
-        post_state_digest,
-        seal: seal_clone,
+        // TODO this isn't used by new verifier
+        post_state_digest: todo!(),
+        seal: seal.clone(),
     })
     .abi_encode();
 
@@ -127,8 +143,9 @@ fn prove_and_send_transaction(
         .block_on(tx_sender.send(calldata))
         .expect("failed to send tx");
 
-    tx.send((journal, post_state_digest, seal))
-        .expect("failed to send over channel");
+    // TODO fix this
+    // tx.send((journal, post_state_digest, seal))
+    //     .expect("failed to send over channel");
 }
 
 fn jwt_authentication_filter() -> impl Filter<Extract = ((),), Error = warp::Rejection> + Clone {
diff --git a/bonsai-pay/apps/src/lib.rs b/bonsai-pay/apps/src/lib.rs
index 8949ed3..b2a8498 100644
--- a/bonsai-pay/apps/src/lib.rs
+++ b/bonsai-pay/apps/src/lib.rs
@@ -20,14 +20,10 @@
 // under active development. As such, this library might change to adapt to
 // the upstream changes.
 
-use std::time::Duration;
-
 use alloy_primitives::FixedBytes;
-use anyhow::{Context, Result};
-use bonsai_sdk::alpha as bonsai_sdk;
+use anyhow::Result;
 use ethers::prelude::*;
-use risc0_ethereum_contracts::groth16::Seal;
-use risc0_zkvm::{compute_image_id, Receipt};
+use risc0_zkvm::{default_prover, ExecutorEnv, ProverOpts, VerifierContext};
 
 /// Wrapper of a `SignerMiddleware` client to send transactions to the given
 /// contract's `Address`.
@@ -69,92 +65,3 @@ impl TxSender {
         Ok(tx)
     }
 }
-
-/// An implementation of a Prover that runs on Bonsai.
-pub struct BonsaiProver {}
-impl BonsaiProver {
-    /// Generates a snark proof as a triplet (`Vec<u8>`, `FixedBytes<32>`,
-    /// `Vec<u8>) for the given elf and input.
-    pub fn prove(elf: &[u8], input: &[u8]) -> Result<(Vec<u8>, FixedBytes<32>, Vec<u8>)> {
-        let client = bonsai_sdk::Client::from_env(risc0_zkvm::VERSION)?;
-
-        // Compute the image_id, then upload the ELF with the image_id as its key.
-        let image_id = compute_image_id(elf)?;
-        let image_id_hex = image_id.to_string();
-        client.upload_img(&image_id_hex, elf.to_vec())?;
-        log::info!("Image ID: 0x{}", image_id_hex);
-
-        // Prepare input data and upload it.
-        let input_id = client.upload_input(input.to_vec())?;
-
-        // Start a session running the prover.
-        let session = client.create_session(image_id_hex, input_id, vec![])?;
-        log::info!("Created session: {}", session.uuid);
-        let _receipt = loop {
-            let res = session.status(&client)?;
-            if res.status == "RUNNING" {
-                log::info!(
-                    "Current status: {} - state: {} - continue polling...",
-                    res.status,
-                    res.state.unwrap_or_default()
-                );
-                std::thread::sleep(Duration::from_secs(15));
-                continue;
-            }
-            if res.status == "SUCCEEDED" {
-                // Download the receipt, containing the output.
-                let receipt_url = res
-                    .receipt_url
-                    .context("API error, missing receipt on completed session")?;
-
-                let receipt_buf = client.download(&receipt_url)?;
-                let receipt: Receipt = bincode::deserialize(&receipt_buf)?;
-
-                break receipt;
-            }
-
-            panic!(
-                "Workflow exited: {} - | err: {}",
-                res.status,
-                res.error_msg.unwrap_or_default()
-            );
-        };
-
-        // Fetch the snark.
-        let snark_session = client.create_snark(session.uuid)?;
-        log::info!("Created snark session: {}", snark_session.uuid);
-        let snark_receipt = loop {
-            let res = snark_session.status(&client)?;
-            match res.status.as_str() {
-                "RUNNING" => {
-                    log::info!("Current status: {} - continue polling...", res.status,);
-                    std::thread::sleep(Duration::from_secs(15));
-                    continue;
-                }
-                "SUCCEEDED" => {
-                    break res.output.context("No snark generated :(")?;
-                }
-                _ => {
-                    panic!(
-                        "Workflow exited: {} err: {}",
-                        res.status,
-                        res.error_msg.unwrap_or_default()
-                    );
-                }
-            }
-        };
-
-        let snark = snark_receipt.snark;
-        log::debug!("Snark proof!: {snark:?}");
-
-        let seal = Seal::abi_encode(snark).context("Read seal")?;
-        let post_state_digest: FixedBytes<32> = snark_receipt
-            .post_state_digest
-            .as_slice()
-            .try_into()
-            .context("Read post_state_digest")?;
-        let journal = snark_receipt.journal;
-
-        Ok((journal, post_state_digest, seal))
-    }
-}
diff --git a/bonsai-pay/methods/guest/Cargo.toml b/bonsai-pay/methods/guest/Cargo.toml
index 9c06337..381bff4 100644
--- a/bonsai-pay/methods/guest/Cargo.toml
+++ b/bonsai-pay/methods/guest/Cargo.toml
@@ -12,7 +12,7 @@ path = "src/bin/jwt_validator.rs"
 [dependencies]
 alloy-primitives = { version = "0.6", default-features = false, features = ["rlp", "serde", "std"] }
 alloy-sol-types = { version = "0.6" }
-risc0-zkvm = {  version = "0.21", default-features = false, features = ['std'] }
+risc0-zkvm = {  version = "1.0.1", default-features = false, features = ['std'] }
 oidc-validator = { path = "../../oidc-validator" }
 
 [profile.release]

cc @hmrtn

@hmrtn
Copy link
Member

hmrtn commented Sep 10, 2024

Handled in #39

@hmrtn hmrtn closed this as completed Sep 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants