123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- mod utils;
- use wasm_bindgen::prelude::*;
- use spiral_rs::{params::*, util::*, client::*, discrete_gaussian::*};
- const UUID_V4_LEN: usize = 36;
- // console_log! macro
- #[wasm_bindgen]
- extern "C" {
- #[wasm_bindgen(js_namespace = console)]
- fn log(s: &str);
- }
- macro_rules! console_log {
- ($($t:tt)*) => (log(&format_args!($($t)*).to_string()))
- }
- // Container class for a static lifetime Client
- // Avoids a lifetime in the return signature of bound Rust functions
- #[wasm_bindgen]
- pub struct WrappedClient {
- client: Client<'static>
- }
- // Unsafe global with a static lifetime
- // Accessed unsafely only once, at load / setup
- static mut PARAMS: Params = get_empty_params();
- // Very simply test to ensure random generation is not obviously biased.
- fn dg_seems_okay() {
- let params = get_test_params();
- let mut dg = DiscreteGaussian::init(¶ms);
- let mut v = Vec::new();
- let trials = 10000;
- let mut sum = 0;
- for _ in 0..trials {
- let val = dg.sample();
- v.push(val);
- sum += val;
- }
- let mean = sum as f64 / trials as f64;
- let std_dev = params.noise_width / f64::sqrt(2f64 * std::f64::consts::PI);
- let std_dev_of_mean = std_dev / f64::sqrt(trials as f64);
- assert!(f64::abs(mean) < std_dev_of_mean * 5f64);
- }
- // Initializes a client; can optionally take in a set of parameters
- #[wasm_bindgen]
- pub fn initialize(json_params: Option<String>) -> WrappedClient {
- dg_seems_okay();
- // spiral_rs::ntt::test::ntt_correct();
- let cfg = r#"
- {'kinda_direct_upload': 1,
- 'n': 5,
- 'nu_1': 11,
- 'nu_2': 3,
- 'p': 65536,
- 'q_prime_bits': 27,
- 's_e': 57.793748020122216,
- 't_GSW': 3,
- 't_conv': 56,
- 't_exp': 56,
- 't_exp_right': 56}
- "#;
- let mut cfg = cfg.replace("'", "\"");
- if json_params.is_some() {
- cfg = json_params.unwrap();
- }
- let client;
- // this minimal unsafe operation is need to initialize state
- unsafe {
- PARAMS = params_from_json(&cfg);
- client = Client::init(&PARAMS);
- }
-
- WrappedClient { client }
- }
- #[wasm_bindgen]
- pub fn generate_public_parameters(c: &mut WrappedClient) -> Box<[u8]> {
- c.client.generate_keys().serialize().into_boxed_slice()
- }
- #[wasm_bindgen]
- pub fn generate_query(c: &mut WrappedClient, id: &str, idx_target: usize) -> Box<[u8]> {
- assert_eq!(id.len(), UUID_V4_LEN);
- let query = c.client.generate_query(idx_target);
- let mut query_buf = query.serialize();
- let mut full_query_buf = id.as_bytes().to_vec();
- full_query_buf.append(&mut query_buf);
- full_query_buf.into_boxed_slice()
- }
- #[wasm_bindgen]
- pub fn decode_response(c: &mut WrappedClient, data: Box<[u8]>) -> Box<[u8]> {
- c.client.decode_response(&*data).into_boxed_slice()
- }
|