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

Fix compile errors for wasm build #22

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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
4 changes: 3 additions & 1 deletion phase2/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ phase1radix2m*
/*.json
/*.bin
/*.params
/verifier.sol
/verifier.sol
*.dat
*.r1cs
3 changes: 3 additions & 0 deletions phase2/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,6 @@ console_error_panic_hook = { version = "0.1.6", optional = true }
[features]
default = ["bellman_ce/multicore", "rust-crypto"]
wasm = ["wasm-bindgen", "js-sys", "web-sys", "console_error_panic_hook", "bellman_ce/wasm"]

[package.metadata.wasm-pack.profile.release]
wasm-opt = false
25 changes: 25 additions & 0 deletions phase2/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,31 @@ async function main() {
main().catch(console.error)
```

## Service Worker

Some differences are required to implement the module in a service worker.

Build wasm package using `wasm-pack build --target no-modules --release -- --no-default-features --features wasm`

Service workers can't do a dynamic import, as above. Instead load the shims using:
```js
self.importScripts(./pkg/phase2.js);
```

This will make wasm_bindgen available to the service worker.
Declare the `contribute` function like this:
```js
const { contribute } = wasm_bindgen;
```
Load the wasm binary like this:
```js
await wasm_bindgen('./pkg/phase2_bg.wasm');
```
and run `contribute` like this:
```js
const result = contribute(sourceParams, ...);
```

## [Documentation](https://docs.rs/phase2/)

## Security Warnings
Expand Down
2 changes: 1 addition & 1 deletion phase2/src/bin/contribute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ fn main() {
let mut params = MPCParameters::read(reader, disallow_points_at_infinity, true).expect("unable to read params");

println!("Contributing to {}...", in_params_filename);
let mut progress_update_interval: u32 = 0;
let mut progress_update_interval: u32 = 10000;
if print_progress {
let parsed = args[5].parse::<u32>();
if !parsed.is_err() {
Expand Down
11 changes: 8 additions & 3 deletions phase2/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,14 @@ cfg_if! {
Read,
Write,
};
use std::str;

macro_rules! log {
($($t:tt)*) => (web_sys::console::log_1(&format_args!($($t)*).to_string().into()))
}

#[wasm_bindgen]
pub fn contribute(params: Vec<u8>, entropy: Vec<u8>) -> Result<Vec<u8>, JsValue> {
pub fn contribute(params: Vec<u8>, entropy: Vec<u8>, report_progress: &js_sys::Function, set_hash: &js_sys::Function) -> Result<Vec<u8>, JsValue> {
console_error_panic_hook::set_once();
let disallow_points_at_infinity = false;

Expand Down Expand Up @@ -73,11 +74,15 @@ cfg_if! {
};

let mut params = MPCParameters::read(&*params, disallow_points_at_infinity, true).expect("unable to read params");
let mut progress_update_interval: u32 = 1000;

log!("Contributing...");
let zero: u32 = 0;
let hash = params.contribute(&mut rng, &zero);
let hash = params.contribute(&mut rng, &mut progress_update_interval, &report_progress);
log!("Contribution hash: 0x{:02x}", hash.iter().format(""));
log!("Sending hash...");
let this = JsValue::null();
let xhash = JsValue::from(format!("0x{:02x?}", &hash.iter().format("")));
let _ = set_hash.call1(&this, &xhash);

let mut output: Vec<u8> = vec![];
params.write(&mut output).expect("failed to write updated parameters");
Expand Down
33 changes: 28 additions & 5 deletions phase2/src/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ extern crate rand;
extern crate byteorder;
extern crate num_cpus;
extern crate crossbeam;
#[cfg(feature = "wasm")]
extern crate js_sys;

#[cfg(feature = "wasm")]
use bellman_ce::singlecore::Worker;

#[cfg(not(feature = "wasm"))]
use bellman_ce::multicore::Worker;

Expand Down Expand Up @@ -75,6 +78,7 @@ use super::keypair_assembly::*;
use super::keypair::*;
use super::utils::*;


/// MPC parameters are just like bellman `Parameters` except, when serialized,
/// they contain a transcript of contributions at the end, which can be verified.
#[derive(Clone)]
Expand Down Expand Up @@ -414,7 +418,9 @@ impl MPCParameters {
pub fn contribute<R: Rng>(
&mut self,
rng: &mut R,
progress_update_interval: &u32
progress_update_interval: &u32,
#[cfg(feature = "wasm")]
report_progress: &js_sys::Function
) -> [u8; 64]
{
// Generate a keypair
Expand Down Expand Up @@ -446,7 +452,7 @@ impl MPCParameters {
*projective = wnaf.base(base.into_projective(), 1).scalar(coeff);
count = count + 1;
if *progress_update_interval > 0 && count % *progress_update_interval == 0 {
println!("progress {} {}", *progress_update_interval, *total_exps)
println!("progress {} {}", *progress_update_interval, *total_exps);
}
}
});
Expand All @@ -469,20 +475,29 @@ impl MPCParameters {
}
}


#[cfg(feature = "wasm")]
fn batch_exp<C: CurveAffine>(bases: &mut [C], coeff: C::Scalar, progress_update_interval: &u32, total_exps: &u32) {
fn batch_exp<C: CurveAffine>(bases: &mut [C], coeff: C::Scalar, progress_update_interval: &u32, total_exps: &u32, report_progress: &js_sys::Function, start_count: &u32) {
use web_sys::console;
use wasm_bindgen::prelude::*;
//use std::{thread, time};

let coeff = coeff.into_repr();

let mut projective = vec![C::Projective::zero(); bases.len()];

// Perform wNAF, placing results into `projective`.
let mut wnaf = Wnaf::new();
let mut count = 0;
let mut count = *start_count;
for (base, projective) in bases.iter_mut().zip(projective.iter_mut()) {
*projective = wnaf.base(base.into_projective(), 1).scalar(coeff);
count = count + 1;
if *progress_update_interval > 0 && count % *progress_update_interval == 0 {
println!("progress {} {}", *progress_update_interval, *total_exps)
console::log_1(&format!("progress {} of {}", count, *total_exps).into());
let this = JsValue::null();
let pcount: JsValue = JsValue::from(count);
let exp_count = JsValue::from(*total_exps);
let _ = report_progress.call2(&this, &pcount, &exp_count);
}
}

Expand All @@ -499,7 +514,15 @@ impl MPCParameters {
let mut l = (&self.params.l[..]).to_vec();
let mut h = (&self.params.h[..]).to_vec();
let total_exps = (l.len() + h.len()) as u32;
let mut start_count: u32 = 0;
#[cfg(feature = "wasm")]
batch_exp(&mut l, delta_inv, &progress_update_interval, &total_exps, &report_progress, &start_count);
#[cfg(not(feature = "wasm"))]
batch_exp(&mut l, delta_inv, &progress_update_interval, &total_exps);
start_count = l.len() as u32;
#[cfg(feature = "wasm")]
batch_exp(&mut h, delta_inv, &progress_update_interval, &total_exps, &report_progress, &start_count);
#[cfg(not(feature = "wasm"))]
batch_exp(&mut h, delta_inv, &progress_update_interval, &total_exps);
self.params.l = Arc::new(l);
self.params.h = Arc::new(h);
Expand Down
2 changes: 1 addition & 1 deletion phase2/test.sh
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ cp ../powersoftau/phase1radix* .
npm install

# compile circuit
npx circom circuit.circom -o circuit.json && npx snarkjs info -c circuit.json
npx circom circuit.circom -c circuit.json # && npx snarkjs info -c circuit.json
# npx snarkjs info -c circuit.json

# initialize ceremony
Expand Down
2 changes: 1 addition & 1 deletion powersoftau/test.sh
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ rm tmp_*

set -e

SIZE=10
SIZE=15
BATCH=256

cargo run --release --bin new_constrained challenge1 $SIZE $BATCH
Expand Down