Skip to content

Commit

Permalink
try wasm-pack tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
vivianjeng committed Nov 26, 2024
1 parent ce30b43 commit dabc9e4
Show file tree
Hide file tree
Showing 8 changed files with 137 additions and 2 deletions.
17 changes: 17 additions & 0 deletions .github/workflows/build-and-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,23 @@ jobs:
override: true
- name: Run ffi ashlang tests
run: cd mopro-ffi && cargo test --features ashlang --no-default-features
test-wasm-halo2-nodejs:
runs-on: ubuntu-latest
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
steps:
- uses: actions/checkout@v4
- name: Install Rust toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Install wasm-pack
run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
- name: Run wasm halo2 tests
run: |
cd mopro-ffi
wasm-pack build --target nodejs
node test.mjs
test-wasm-halo2:
runs-on: ubuntu-latest
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
Expand Down
5 changes: 5 additions & 0 deletions Cargo.lock

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

16 changes: 14 additions & 2 deletions mopro-ffi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ exclude = ["target/*"]

[lib]
name = "mopro_ffi"
crate-type = ["cdylib", "rlib"]

[[bin]]
name = "uniffi-bindgen"
path = "src/uniffi-bindgen.rs"

[features]
default = []
default = ["halo2", "console_error_panic_hook"]

ashlang = ["dep:ashlang"]
halo2 = []
Expand All @@ -40,6 +41,11 @@ circom = [
[dependencies]
uniffi = { version = "=0.28.0", features = ["cli", "build"] }
serde = { version = "1.0", features = ["derive"] }
console_error_panic_hook = { version = "0.1.7", optional = true }
plonk-fibonacci = { package = "plonk-fibonacci", branch = "supporting-wasm", git = "https://github.com/sifnoc/plonkish-fibonacci-sample.git" }
serde-wasm-bindgen = "0.6.5"
getrandom = { version = "0.2.15", features = ["js"] }
wasm-bindgen = "0.2.84"

# Error handling
thiserror = "=1.0.39"
Expand Down Expand Up @@ -77,14 +83,16 @@ num-traits = { version = "0.2.0", optional = true }
anyhow = "1.0.86"
bincode = "1.3.3"


[build-dependencies]
rust-witness = "0.1.0"
rust-witness = { version = "0.1.0", optional = true }
uniffi = { version = "=0.28.0", features = ["build"] }

[dev-dependencies]
uniffi = { version = "=0.28.0", features = ["bindgen-tests"] }
# Circom test dependency
ark-bn254 = { version = "=0.4.0" }
wasm-bindgen-test = "0.3.34"

color-eyre = "0.6"
serde = { version = "1.0", features = ["derive"] }
Expand All @@ -94,3 +102,7 @@ serde_derive = "1.0"
plonk-fibonacci = { workspace = true }
hyperplonk-fibonacci = { workspace = true }
gemini-fibonacci = { workspace = true }

[profile.release]
# Tell `rustc` to optimize for small code size.
opt-level = "s"
1 change: 1 addition & 0 deletions mopro-ffi/build.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
fn main() {
#[cfg(feature = "circom")]
if std::env::var("MOPRO_FFI_LINK_TEST_WITNESS").unwrap_or_default() != "" {
rust_witness::transpile::transpile_wasm("../test-vectors/circom".to_string());
}
Expand Down
3 changes: 3 additions & 0 deletions mopro-ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ mod circom;
#[cfg(feature = "halo2")]
mod halo2;

mod utils;
mod wasm;

#[cfg(feature = "circom")]
pub use circom::{
generate_circom_proof_wtns, serialization::to_ethereum_inputs,
Expand Down
10 changes: 10 additions & 0 deletions mopro-ffi/src/utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
pub fn set_panic_hook() {
// When the `console_error_panic_hook` feature is enabled, we can call the
// `set_panic_hook` function at least once during initialization, and then
// we will get better error messages if our code ever panics.
//
// For more details see
// https://github.com/rustwasm/console_error_panic_hook#readme
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
}
50 changes: 50 additions & 0 deletions mopro-ffi/src/wasm.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
use crate::utils;
use std::collections::HashMap;

use plonk_fibonacci;
use wasm_bindgen::prelude::*;

use serde_wasm_bindgen::{from_value, to_value};

#[wasm_bindgen]
extern "C" {
// fn alert(s: &str);
}

#[wasm_bindgen]
pub fn generate_proof(
srs_key: &[u8],
proving_key: &[u8],
input: JsValue,
) -> Result<JsValue, JsValue> {
let input: HashMap<String, Vec<String>> = from_value(input)
.map_err(|e| JsValue::from_str(&format!("Failed to parse input: {}", e)))?;

// Generate proof
let (proof, public_input) = plonk_fibonacci::prove(srs_key, proving_key, input)
.map_err(|e| JsValue::from_str(&format!("Proof generation failed: {}", e)))?;

// Serialize the output back into JsValue
to_value(&(proof, public_input))
.map_err(|e| JsValue::from_str(&format!("Serialization failed: {}", e)))
}

#[wasm_bindgen]
pub fn verify_proof(
srs_key: &[u8],
verifying_key: &[u8],
proof: JsValue,
public_inputs: JsValue,
) -> Result<JsValue, JsValue> {
let proof: Vec<u8> = from_value(proof)
.map_err(|e| JsValue::from_str(&format!("Failed to parse proof: {}", e)))?;
let public_inputs: Vec<u8> = from_value(public_inputs)
.map_err(|e| JsValue::from_str(&format!("Failed to parse public_inputs: {}", e)))?;

// Verify proof
let is_valid = plonk_fibonacci::verify(srs_key, verifying_key, proof, public_inputs)
.map_err(|e| JsValue::from_str(&format!("Proof verification failed: {}", e)))?;

// Convert result to JsValue
to_value(&is_valid).map_err(|e| JsValue::from_str(&format!("Serialization failed: {}", e)))
}
37 changes: 37 additions & 0 deletions mopro-ffi/test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { generate_proof, verify_proof } from "./pkg/mopro_ffi.js";
import fs from "fs";
// Function to convert file content at a path to Uint8Array
function pathToUint8Array(filePath) {
const buffer = fs.readFileSync(filePath); // Read the file as a Buffer
return new Uint8Array(buffer); // Convert the Buffer to a Uint8Array
}

async function run() {
const srs = "../test-vectors/halo2/plonk_fibonacci_srs.bin";
const pk = "../test-vectors/halo2/plonk_fibonacci_pk.bin";
const vk = "../test-vectors/halo2/plonk_fibonacci_vk.bin";
const input = {
out: ["55"],
};
const start = Date.now();
const output = generate_proof(
pathToUint8Array(srs),
pathToUint8Array(pk),
input
);
const end = Date.now();
console.log(`Proof time: ${end - start} ms`);
const proof = output[0];
const publicInputs = output[1];

const valid = verify_proof(
pathToUint8Array(srs),
pathToUint8Array(vk),
proof,
publicInputs
);

return valid;
}

run().then((t) => console.log(t));

0 comments on commit dabc9e4

Please sign in to comment.