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

Working WASM build of parcnet-pod #37

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
resolver = "2"
members = [
"parcnet-pod",
"parcnet-pod-wasm",
"parcnet",
"chat",
"pex",
Expand All @@ -16,6 +17,7 @@ pathfinder_simd = { git = "https://github.com/theoparis/pathfinder/" }
[workspace.dependencies]
assets = { path = "assets" }
parcnet-pod = { path = "parcnet-pod" }
parcnet-pod-wasm = { path = "parcnet-pod-wasm" }
pod2 = { path = "pod2" }
constants = { path = "constants" }
anyhow = "1.0.86"
Expand Down
6 changes: 6 additions & 0 deletions parcnet-pod-wasm/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/target
**/*.rs.bk
Cargo.lock
bin/
pkg/
wasm-pack.log
34 changes: 34 additions & 0 deletions parcnet-pod-wasm/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
[package]
name = "parcnet-pod-wasm"
version = "0.1.0"
edition = "2018"

[lib]
crate-type = ["cdylib"]

[features]
default = ["console_error_panic_hook"]

[dependencies]
babyjubjub-ark = { git = "https://github.com/robknight/babyjubjub-ark", features = ["wasm"] }
getrandom = { version = "0.2.15", features = ["js"] }
getrandom_03 = { package = "getrandom", version = "0.3.1", features = ["wasm_js"] }
parcnet-pod = { path = "../parcnet-pod", default-features = false, features = ["wasm"] }
serde = { version = "1.0.210", features = ["derive"] }
serde_json = { version = "1.0.128", features = ["preserve_order"] }
wasm-bindgen = "0.2.84"

# The `console_error_panic_hook` crate provides better debugging of panics by
# logging them with `console.error`. This is great for development, but requires
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
# code size when deploying.
console_error_panic_hook = { version = "0.1.7", optional = true }

[dev-dependencies]
wasm-bindgen-test = "0.3.34"

[profile.release]
lto = true
# Tell `rustc` to optimize for small code size.
opt-level = "z"
codegen-units = 1
79 changes: 79 additions & 0 deletions parcnet-pod-wasm/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
</head>
<body>
<!-- Note the usage of `type=module` here as this is an ES6 module -->
<script type="module">
import * as pod from "https://esm.sh/@pcd/pod";
import * as uint8arrayExtras from "https://esm.sh/uint8array-extras";
import { Bench } from "https://esm.sh/tinybench";

// Use ES module import syntax to import functionality from the module
// that we have compiled.
//
// Note that the `default` import is an initialization function which
// will "boot" the module and make it ready to use. Currently browsers
// don't support natively imported WebAssembly as an ES module, but
// eventually the manual initialization won't be required!
import init, { sign_pod } from './pkg/parcnet_pod_wasm.js';

export async function run() {
// First up we need to actually load the Wasm file, so we use the
// default export to inform it where the Wasm file is located on the
// server, and then we wait on the returned promise to wait for the
// Wasm to be loaded.
//
// It may look like this: `await init('./pkg/without_a_bundler_bg.wasm');`,
// but there is also a handy default inside `init` function, which uses
// `import.meta` to locate the Wasm file relatively to js file.
//
// Note that instead of a string you can also pass in any of the
// following things:
//
// * `WebAssembly.Module`
//
// * `ArrayBuffer`
//
// * `Response`
//
// * `Promise` which returns any of the above, e.g. `fetch("./path/to/wasm")`
//
// This gives you complete control over how the module is loaded
// and compiled.
//
// Also note that the promise, when resolved, yields the Wasm module's
// exports which is the same as importing the `*_bg` module in other
// modes
await init();

// A key for signing PODs
const keyHex = "0001020304050607080900010203040506070809000102030405060708090001";
const key = uint8arrayExtras.hexToUint8Array(keyHex);

// A POD with two entries
const serializedEntries = `{"foo": {"string": "bar"}, "baz": {"string": "qux"}}`;

const bench = new Bench({ time: 100 });
bench.add("WASM signing", async () => {
console.log("WASM signing");
const result = await sign_pod(serializedEntries, key);
});

bench.add("JS signing", () => {
console.log("JS signing");
const entries = pod.podEntriesFromJSON(JSON.parse(serializedEntries));
const result = pod.POD.sign(entries, keyHex);
});

await bench.run();
const results = bench.table();
console.table(results);

}

document.getElementById("runButton").addEventListener("click", run);
</script>
<button id="runButton">Run</button>
</body>
</html>
59 changes: 59 additions & 0 deletions parcnet-pod-wasm/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
mod utils;

use wasm_bindgen::prelude::*;
use parcnet_pod::pod::Pod;
use parcnet_pod::pod::PodEntries;
use babyjubjub_ark::PrivateKey;

#[wasm_bindgen]
pub fn sign_pod(entries: String, private_key: &[u8]) -> Result<String, JsValue> {
let entries: PodEntries = serde_json::from_str(&entries)
.map_err(|e| JsValue::from(e.to_string()))?;
let private_key = PrivateKey::import(private_key.to_vec())?;
let pod = Pod::sign(entries.into_iter().map(|(k, v)| (k.to_string(), v)).collect(), private_key);
match pod {
Ok(pod) => Ok(serde_json::to_string(&pod).unwrap()),
Err(e) => Err(e.to_string().into())
}
}

#[cfg(test)]
mod tests {

#[test]
#[cfg(target_arch = "wasm32")]
fn test_sign_pod() {
// Create a sample private key (32 bytes)
let private_key = vec![1u8; 32];

// Create a sample pod entries
let mut entries = HashMap::new();
entries.insert("name".to_string(), "Alice".to_string());
entries.insert("age".to_string(), "30".to_string());

// Convert entries to JSON string
let entries_json = serde_json::to_string(&entries).unwrap();

// Sign the pod
let result = sign_pod(entries_json, &private_key);

// Assert the result is Ok and contains a valid JSON string
assert!(result.is_ok());

// Parse the result back to verify it's valid JSON
let pod_json = result.unwrap();
let pod: Pod = serde_json::from_str(&pod_json).unwrap();

// Verify the pod contains our entries
assert_eq!(pod.entries().get("name").unwrap(), &"Alice".into());
assert_eq!(pod.entries().get("age").unwrap(), &"30".into());
}

#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_sign_pod() {
// Skip test on non-wasm targets
println!("Skipping test on non-wasm target");
}
}

10 changes: 10 additions & 0 deletions parcnet-pod-wasm/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();
}
13 changes: 13 additions & 0 deletions parcnet-pod-wasm/tests/web.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
//! Test suite for the Web and headless browsers.

#![cfg(target_arch = "wasm32")]

extern crate wasm_bindgen_test;
use wasm_bindgen_test::*;

wasm_bindgen_test_configure!(run_in_browser);

#[wasm_bindgen_test]
fn pass() {
assert_eq!(1 + 1, 2);
}
17 changes: 13 additions & 4 deletions parcnet-pod/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,28 @@ edition = "2021"
name = "parcnet_pod"
path = "src/lib.rs"

# Force-disable aarch64 when building for WASM
[features]
wasm = [
"babyjubjub-ark/wasm", # Explicit WASM feature
"getrandom/js",
"getrandom_03/wasm_js",
]

[dependencies]
ark-bn254 = "0.4.0"
ark-ff = "0.4.0"
ark-std = "0.4.0"
babyjubjub-ark = { git = "https://github.com/ax0/babyjubjub-ark", features = ["aarch64"] }
babyjubjub-ark = { git = "https://github.com/robknight/babyjubjub-ark" }
base64 = "0.22.1"
getrandom = { version = "0.2.15" }
getrandom_03 = { package = "getrandom", version = "0.3.1" }
hex = "0.4.3"
indexmap = { version = "2.5.0", features = ["rayon", "serde"] }
lazy_static = "1.5.0"
num-bigint = { version = "0.4.6", features = ["serde"] }
num-traits = "0.2.19"
poseidon-ark = { git = "https://github.com/arnaucube/poseidon-ark", version = "0.0.1" }
poseidon-rs = "0.0.10"
poseidon-ark = { git = "https://github.com/robknight/poseidon-ark", default-features = false, features = ["poseidon-1", "poseidon-2"], version = "0.0.1" }
rand = "0.8.5"
rayon = "1.10.0"
serde = { version = "1.0.210", features = ["derive"] }
Expand All @@ -36,7 +45,7 @@ thiserror = "1.0.64"
time = {version = "0.3.36", features = ["macros", "serde"]}
url = "2.5.2"
urlencoding = "2.1.3"
uuid = { version = "1.10.0", features = ["v4", "serde"] }
uuid = { version = "1.10.0", features = ["v4", "serde", "rng-getrandom"] }

[dev-dependencies]
criterion = "0.5.1"
Expand Down
Loading