Samir Menon 3 gadi atpakaļ
vecāks
revīzija
e0be0c13c5

+ 1 - 1
client/LICENSE_MIT → LICENSE

@@ -1,4 +1,4 @@
-Copyright (c) 2018 Samir Menon <menon.samir@gmail.com>
+Copyright (c) 2022 Samir Menon <menon.samir@gmail.com>
 
 Permission is hereby granted, free of charge, to any
 person obtaining a copy of this software and associated

+ 0 - 11
client/.appveyor.yml

@@ -1,11 +0,0 @@
-install:
-  - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe
-  - if not defined RUSTFLAGS rustup-init.exe -y --default-host x86_64-pc-windows-msvc --default-toolchain nightly
-  - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin
-  - rustc -V
-  - cargo -V
-
-build: false
-
-test_script:
-  - cargo test --locked

+ 0 - 69
client/.travis.yml

@@ -1,69 +0,0 @@
-language: rust
-sudo: false
-
-cache: cargo
-
-matrix:
-  include:
-
-  # Builds with wasm-pack.
-  - rust: beta
-    env: RUST_BACKTRACE=1
-    addons:
-      firefox: latest
-      chrome: stable
-    before_script:
-      - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update)
-      - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate)
-      - cargo install-update -a
-      - curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh -s -- -f
-    script:
-      - cargo generate --git . --name testing
-      # Having a broken Cargo.toml (in that it has curlies in fields) anywhere
-      # in any of our parent dirs is problematic.
-      - mv Cargo.toml Cargo.toml.tmpl
-      - cd testing
-      - wasm-pack build
-      - wasm-pack test --chrome --firefox --headless
-
-  # Builds on nightly.
-  - rust: nightly
-    env: RUST_BACKTRACE=1
-    before_script:
-      - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update)
-      - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate)
-      - cargo install-update -a
-      - rustup target add wasm32-unknown-unknown
-    script:
-      - cargo generate --git . --name testing
-      - mv Cargo.toml Cargo.toml.tmpl
-      - cd testing
-      - cargo check
-      - cargo check --target wasm32-unknown-unknown
-      - cargo check                                 --no-default-features
-      - cargo check --target wasm32-unknown-unknown --no-default-features
-      - cargo check                                 --no-default-features --features console_error_panic_hook
-      - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook
-      - cargo check                                 --no-default-features --features "console_error_panic_hook wee_alloc"
-      - cargo check --target wasm32-unknown-unknown --no-default-features --features "console_error_panic_hook wee_alloc"
-
-  # Builds on beta.
-  - rust: beta
-    env: RUST_BACKTRACE=1
-    before_script:
-      - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update)
-      - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate)
-      - cargo install-update -a
-      - rustup target add wasm32-unknown-unknown
-    script:
-      - cargo generate --git . --name testing
-      - mv Cargo.toml Cargo.toml.tmpl
-      - cd testing
-      - cargo check
-      - cargo check --target wasm32-unknown-unknown
-      - cargo check                                 --no-default-features
-      - cargo check --target wasm32-unknown-unknown --no-default-features
-      - cargo check                                 --no-default-features --features console_error_panic_hook
-      - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook
-      # Note: no enabling the `wee_alloc` feature here because it requires
-      # nightly for now.

+ 3 - 2
client/Cargo.toml

@@ -8,10 +8,11 @@ edition = "2018"
 crate-type = ["cdylib", "rlib"]
 
 [features]
-default = ["console_error_panic_hook"]
+default = []
 
 [dependencies]
-wasm-bindgen = "0.2.63"
+spiral-rs = { path = "../spiral-rs" }
+wasm-bindgen = "0.2.74"
 
 # The `console_error_panic_hook` crate provides better debugging of panics by
 # logging them with `console.error`. This is great for development, but requires

+ 0 - 176
client/LICENSE_APACHE

@@ -1,176 +0,0 @@
-                              Apache License
-                        Version 2.0, January 2004
-                     http://www.apache.org/licenses/
-
-TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-1. Definitions.
-
-   "License" shall mean the terms and conditions for use, reproduction,
-   and distribution as defined by Sections 1 through 9 of this document.
-
-   "Licensor" shall mean the copyright owner or entity authorized by
-   the copyright owner that is granting the License.
-
-   "Legal Entity" shall mean the union of the acting entity and all
-   other entities that control, are controlled by, or are under common
-   control with that entity. For the purposes of this definition,
-   "control" means (i) the power, direct or indirect, to cause the
-   direction or management of such entity, whether by contract or
-   otherwise, or (ii) ownership of fifty percent (50%) or more of the
-   outstanding shares, or (iii) beneficial ownership of such entity.
-
-   "You" (or "Your") shall mean an individual or Legal Entity
-   exercising permissions granted by this License.
-
-   "Source" form shall mean the preferred form for making modifications,
-   including but not limited to software source code, documentation
-   source, and configuration files.
-
-   "Object" form shall mean any form resulting from mechanical
-   transformation or translation of a Source form, including but
-   not limited to compiled object code, generated documentation,
-   and conversions to other media types.
-
-   "Work" shall mean the work of authorship, whether in Source or
-   Object form, made available under the License, as indicated by a
-   copyright notice that is included in or attached to the work
-   (an example is provided in the Appendix below).
-
-   "Derivative Works" shall mean any work, whether in Source or Object
-   form, that is based on (or derived from) the Work and for which the
-   editorial revisions, annotations, elaborations, or other modifications
-   represent, as a whole, an original work of authorship. For the purposes
-   of this License, Derivative Works shall not include works that remain
-   separable from, or merely link (or bind by name) to the interfaces of,
-   the Work and Derivative Works thereof.
-
-   "Contribution" shall mean any work of authorship, including
-   the original version of the Work and any modifications or additions
-   to that Work or Derivative Works thereof, that is intentionally
-   submitted to Licensor for inclusion in the Work by the copyright owner
-   or by an individual or Legal Entity authorized to submit on behalf of
-   the copyright owner. For the purposes of this definition, "submitted"
-   means any form of electronic, verbal, or written communication sent
-   to the Licensor or its representatives, including but not limited to
-   communication on electronic mailing lists, source code control systems,
-   and issue tracking systems that are managed by, or on behalf of, the
-   Licensor for the purpose of discussing and improving the Work, but
-   excluding communication that is conspicuously marked or otherwise
-   designated in writing by the copyright owner as "Not a Contribution."
-
-   "Contributor" shall mean Licensor and any individual or Legal Entity
-   on behalf of whom a Contribution has been received by Licensor and
-   subsequently incorporated within the Work.
-
-2. Grant of Copyright License. Subject to the terms and conditions of
-   this License, each Contributor hereby grants to You a perpetual,
-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-   copyright license to reproduce, prepare Derivative Works of,
-   publicly display, publicly perform, sublicense, and distribute the
-   Work and such Derivative Works in Source or Object form.
-
-3. Grant of Patent License. Subject to the terms and conditions of
-   this License, each Contributor hereby grants to You a perpetual,
-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-   (except as stated in this section) patent license to make, have made,
-   use, offer to sell, sell, import, and otherwise transfer the Work,
-   where such license applies only to those patent claims licensable
-   by such Contributor that are necessarily infringed by their
-   Contribution(s) alone or by combination of their Contribution(s)
-   with the Work to which such Contribution(s) was submitted. If You
-   institute patent litigation against any entity (including a
-   cross-claim or counterclaim in a lawsuit) alleging that the Work
-   or a Contribution incorporated within the Work constitutes direct
-   or contributory patent infringement, then any patent licenses
-   granted to You under this License for that Work shall terminate
-   as of the date such litigation is filed.
-
-4. Redistribution. You may reproduce and distribute copies of the
-   Work or Derivative Works thereof in any medium, with or without
-   modifications, and in Source or Object form, provided that You
-   meet the following conditions:
-
-   (a) You must give any other recipients of the Work or
-       Derivative Works a copy of this License; and
-
-   (b) You must cause any modified files to carry prominent notices
-       stating that You changed the files; and
-
-   (c) You must retain, in the Source form of any Derivative Works
-       that You distribute, all copyright, patent, trademark, and
-       attribution notices from the Source form of the Work,
-       excluding those notices that do not pertain to any part of
-       the Derivative Works; and
-
-   (d) If the Work includes a "NOTICE" text file as part of its
-       distribution, then any Derivative Works that You distribute must
-       include a readable copy of the attribution notices contained
-       within such NOTICE file, excluding those notices that do not
-       pertain to any part of the Derivative Works, in at least one
-       of the following places: within a NOTICE text file distributed
-       as part of the Derivative Works; within the Source form or
-       documentation, if provided along with the Derivative Works; or,
-       within a display generated by the Derivative Works, if and
-       wherever such third-party notices normally appear. The contents
-       of the NOTICE file are for informational purposes only and
-       do not modify the License. You may add Your own attribution
-       notices within Derivative Works that You distribute, alongside
-       or as an addendum to the NOTICE text from the Work, provided
-       that such additional attribution notices cannot be construed
-       as modifying the License.
-
-   You may add Your own copyright statement to Your modifications and
-   may provide additional or different license terms and conditions
-   for use, reproduction, or distribution of Your modifications, or
-   for any such Derivative Works as a whole, provided Your use,
-   reproduction, and distribution of the Work otherwise complies with
-   the conditions stated in this License.
-
-5. Submission of Contributions. Unless You explicitly state otherwise,
-   any Contribution intentionally submitted for inclusion in the Work
-   by You to the Licensor shall be under the terms and conditions of
-   this License, without any additional terms or conditions.
-   Notwithstanding the above, nothing herein shall supersede or modify
-   the terms of any separate license agreement you may have executed
-   with Licensor regarding such Contributions.
-
-6. Trademarks. This License does not grant permission to use the trade
-   names, trademarks, service marks, or product names of the Licensor,
-   except as required for reasonable and customary use in describing the
-   origin of the Work and reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty. Unless required by applicable law or
-   agreed to in writing, Licensor provides the Work (and each
-   Contributor provides its Contributions) on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-   implied, including, without limitation, any warranties or conditions
-   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-   PARTICULAR PURPOSE. You are solely responsible for determining the
-   appropriateness of using or redistributing the Work and assume any
-   risks associated with Your exercise of permissions under this License.
-
-8. Limitation of Liability. In no event and under no legal theory,
-   whether in tort (including negligence), contract, or otherwise,
-   unless required by applicable law (such as deliberate and grossly
-   negligent acts) or agreed to in writing, shall any Contributor be
-   liable to You for damages, including any direct, indirect, special,
-   incidental, or consequential damages of any character arising as a
-   result of this License or out of the use or inability to use the
-   Work (including but not limited to damages for loss of goodwill,
-   work stoppage, computer failure or malfunction, or any and all
-   other commercial damages or losses), even if such Contributor
-   has been advised of the possibility of such damages.
-
-9. Accepting Warranty or Additional Liability. While redistributing
-   the Work or Derivative Works thereof, You may choose to offer,
-   and charge a fee for, acceptance of support, warranty, indemnity,
-   or other liability obligations and/or rights consistent with this
-   License. However, in accepting such obligations, You may act only
-   on Your own behalf and on Your sole responsibility, not on behalf
-   of any other Contributor, and only if You agree to indemnify,
-   defend, and hold each Contributor harmless for any liability
-   incurred by, or claims asserted against, such Contributor by reason
-   of your accepting any such warranty or additional liability.
-
-END OF TERMS AND CONDITIONS

+ 0 - 69
client/README.md

@@ -1,69 +0,0 @@
-<div align="center">
-
-  <h1><code>wasm-pack-template</code></h1>
-
-  <strong>A template for kick starting a Rust and WebAssembly project using <a href="https://github.com/rustwasm/wasm-pack">wasm-pack</a>.</strong>
-
-  <p>
-    <a href="https://travis-ci.org/rustwasm/wasm-pack-template"><img src="https://img.shields.io/travis/rustwasm/wasm-pack-template.svg?style=flat-square" alt="Build Status" /></a>
-  </p>
-
-  <h3>
-    <a href="https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/index.html">Tutorial</a>
-    <span> | </span>
-    <a href="https://discordapp.com/channels/442252698964721669/443151097398296587">Chat</a>
-  </h3>
-
-  <sub>Built with 🦀🕸 by <a href="https://rustwasm.github.io/">The Rust and WebAssembly Working Group</a></sub>
-</div>
-
-## About
-
-[**📚 Read this template tutorial! 📚**][template-docs]
-
-This template is designed for compiling Rust libraries into WebAssembly and
-publishing the resulting package to NPM.
-
-Be sure to check out [other `wasm-pack` tutorials online][tutorials] for other
-templates and usages of `wasm-pack`.
-
-[tutorials]: https://rustwasm.github.io/docs/wasm-pack/tutorials/index.html
-[template-docs]: https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/index.html
-
-## 🚴 Usage
-
-### 🐑 Use `cargo generate` to Clone this Template
-
-[Learn more about `cargo generate` here.](https://github.com/ashleygwilliams/cargo-generate)
-
-```
-cargo generate --git https://github.com/rustwasm/wasm-pack-template.git --name my-project
-cd my-project
-```
-
-### 🛠️ Build with `wasm-pack build`
-
-```
-wasm-pack build
-```
-
-### 🔬 Test in Headless Browsers with `wasm-pack test`
-
-```
-wasm-pack test --headless --firefox
-```
-
-### 🎁 Publish to NPM with `wasm-pack publish`
-
-```
-wasm-pack publish
-```
-
-## 🔋 Batteries Included
-
-* [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) for communicating
-  between WebAssembly and JavaScript.
-* [`console_error_panic_hook`](https://github.com/rustwasm/console_error_panic_hook)
-  for logging panic messages to the developer console.
-* [`wee_alloc`](https://github.com/rustwasm/wee_alloc), an allocator optimized
-  for small code size.

+ 30 - 0
client/THIRD-PARTY-NOTICES.TXT

@@ -0,0 +1,30 @@
+The attached notices are provided for information only.
+
+License notice for wasm-bindgen
+-------------------------------
+
+Copyright (c) 2014 Alex Crichton
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.

+ 14 - 0
client/index.html

@@ -0,0 +1,14 @@
+<html>
+  <head>
+    <meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
+  </head>
+  <body>
+    <h1>Spiral Demo</h1>
+    <input id="query_idx" type="text" />
+    <input id="make_query" type="button" value="&gt;" />
+
+    <pre id="output"></pre>
+
+    <script type="module" src="main.js"></script>
+  </body>
+</html>

+ 121 - 0
client/main.js

@@ -0,0 +1,121 @@
+// 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, { 
+    initialize,
+    generate_public_parameters,
+    generate_query,
+    decode_response
+} from './pkg/client.js';
+
+const API_URL = "https://spiralwiki.com:8088";
+const SETUP_URL = "/setup";
+const QUERY_URL = "/query";
+
+async function postData(url = '', data = {}, json = false) {
+    const response = await fetch(url, {
+      method: 'POST',
+      mode: 'cors',
+      cache: 'no-cache',
+      credentials: 'omit',
+      headers: { 'Content-Type': 'application/octet-stream' },
+      redirect: 'follow',
+      referrerPolicy: 'no-referrer',
+      body: data
+    });
+    if (json) {
+        return response.json();
+    } else {
+        let data = await response.arrayBuffer();
+        return new Uint8Array(data);
+    }
+  }
+
+const api = {
+    setup: async (data) => postData(API_URL + SETUP_URL, data, true),
+    query: async (data) => postData(API_URL + QUERY_URL, data, false)
+}
+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();
+
+    let make_query_btn = document.getElementById("make_query");
+    let output_area = document.getElementById("output");
+
+    let has_set_up = false;
+    let id = "";
+    let client = null;
+
+    make_query_btn.onclick = async () => {
+        make_query_btn.disabled = true;
+
+        if (!has_set_up) {
+            console.log("Initializing...");
+            client = initialize();
+            console.log("done");
+            console.log("Generating public parameters...");
+            let publicParameters = generate_public_parameters(client);
+            console.log(`done (${publicParameters.length} bytes)`);
+            console.log("Sending public parameters...");
+            let setup_resp = await api.setup(publicParameters);
+            console.log("sent.");
+            console.log(setup_resp);
+            id = setup_resp["id"];
+            has_set_up = true;
+        }
+
+        let targetIdx = parseInt(document.getElementById("query_idx").value, 10);
+        if (targetIdx === NaN) targetIdx = 7;
+
+        console.log("Generating query...");
+        let query = generate_query(client, id, targetIdx);
+        console.log(`done (${query.length} bytes)`);
+
+        console.log("Sending query...");
+        let response = await api.query(query);
+        console.log("sent.");
+
+        console.log(`done, got (${response.length} bytes)`);
+        console.log(response);
+
+        console.log("Decoding result...");
+        let result = decode_response(client, response)
+        console.log("done.")
+        console.log("Final result:")
+        console.log(result);
+
+        output_area.innerHTML = result.map (b => b.toString(10)).join(" ");
+
+        make_query_btn.disabled = false;
+    }
+}
+run();

+ 88 - 9
client/src/lib.rs

@@ -1,19 +1,98 @@
 mod utils;
 
 use wasm_bindgen::prelude::*;
+use spiral_rs::{params::*, util::*, client::*, discrete_gaussian::*};
 
-// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
-// allocator.
-#[cfg(feature = "wee_alloc")]
-#[global_allocator]
-static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
+const UUID_V4_LEN: usize = 36;
 
+// console_log! macro
 #[wasm_bindgen]
-extern {
-    fn alert(s: &str);
+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(&params);
+    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#"
+        {'n': 2,
+        'nu_1': 9,
+        'nu_2': 6,
+        'p': 256,
+        'q_prime_bits': 20,
+        's_e': 87.62938774292914,
+        't_GSW': 8,
+        't_conv': 4,
+        't_exp': 8,
+        '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 greet() {
-    alert("Hello, client!");
+pub fn decode_response(c: &mut WrappedClient, data: Box<[u8]>) -> Box<[u8]> {
+    c.client.decode_response(&*data).into_boxed_slice()
 }

+ 1 - 1
client/src/utils.rs

@@ -1,3 +1,4 @@
+#[cfg(feature = "console_error_panic_hook")]
 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
@@ -5,6 +6,5 @@ pub fn set_panic_hook() {
     //
     // 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();
 }

+ 3 - 0
spiral-rs/Cargo.lock

@@ -315,8 +315,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "418d37c8b1d42553c93648be529cb70f920d3baf8ef469b74b9638df426e0b4c"
 dependencies = [
  "cfg-if",
+ "js-sys",
  "libc",
  "wasi 0.10.2+wasi-snapshot-preview1",
+ "wasm-bindgen",
 ]
 
 [[package]]
@@ -1004,6 +1006,7 @@ name = "spiral-rs"
 version = "0.1.0"
 dependencies = [
  "criterion",
+ "getrandom",
  "rand",
  "reqwest",
  "serde_json",

+ 2 - 1
spiral-rs/Cargo.toml

@@ -4,7 +4,8 @@ version = "0.1.0"
 edition = "2021"
 
 [dependencies]
-rand = "0.8.5"
+getrandom = { features = ["js"] }
+rand = { version = "0.8.5" }
 reqwest = { version = "0.11", features = ["blocking"] }
 serde_json = "1.0"
 

+ 5 - 1
spiral-rs/src/arith.rs

@@ -9,7 +9,11 @@ pub const fn log2(a: u64) -> u64 {
     std::mem::size_of::<u64>() as u64 * 8 - a.leading_zeros() as u64 - 1
 }
 
-pub fn log2_ceil(a: usize) -> usize {
+pub fn log2_ceil(a: u64) -> u64 {
+    f64::ceil(f64::log2(a as f64)) as u64
+}
+
+pub fn log2_ceil_usize(a: usize) -> usize {
     f64::ceil(f64::log2(a as f64)) as usize
 }
 

+ 5 - 5
spiral-rs/src/client.rs

@@ -113,8 +113,8 @@ impl<'a> Client<'a> {
         let further_dims = params.db_dim_2;
         let num_expanded = 1usize << params.db_dim_1;
         let num_bits_to_gen = params.t_gsw * further_dims + num_expanded;
-        let g = log2_ceil(num_bits_to_gen);
-        let stop_round = log2_ceil(params.t_gsw * further_dims);
+        let g = log2_ceil_usize(num_bits_to_gen);
+        let stop_round = log2_ceil_usize(params.t_gsw * further_dims);
         Self {
             params,
             sk_gsw,
@@ -290,9 +290,9 @@ impl<'a> Client<'a> {
         */
         let params = self.params;
         let p = params.pt_modulus;
-        let p_bits = log2_ceil(params.pt_modulus as usize);
+        let p_bits = log2_ceil(params.pt_modulus);
         let q1 = 4 * params.pt_modulus;
-        let q1_bits = log2_ceil(q1 as usize);
+        let q1_bits = log2_ceil(q1) as usize;
         let q2 = Q2_VALUES[params.q2_bits as usize];
         let q2_bits = params.q2_bits as usize;
 
@@ -351,6 +351,6 @@ impl<'a> Client<'a> {
         }
         println!("{:?}", result.data);
         
-        result.to_vec(p_bits)
+        result.to_vec(p_bits as usize)
     }
 }

+ 1 - 1
spiral-rs/src/params.rs

@@ -104,7 +104,7 @@ impl Params {
         for m in moduli {
             modulus *= m;
         }
-        let modulus_log2 = log2_ceil(modulus as usize) as u64;
+        let modulus_log2 = log2_ceil(modulus);
         Self {
             poly_len,
             poly_len_log2,

+ 24 - 0
spiral-rs/src/util.rs

@@ -29,6 +29,30 @@ pub fn get_test_params() -> Params {
     )
 }
 
+pub const fn get_empty_params() -> Params {
+    Params { 
+        poly_len: 0, 
+        poly_len_log2: 0, 
+        ntt_tables: Vec::new(), 
+        scratch: Vec::new(), 
+        crt_count: 0, 
+        moduli: Vec::new(), 
+        modulus: 0, 
+        modulus_log2: 0, 
+        noise_width: 0f64, 
+        n: 0, 
+        pt_modulus: 0, 
+        q2_bits: 0, 
+        t_conv: 0, 
+        t_exp_left: 0, 
+        t_exp_right: 0, 
+        t_gsw: 0, 
+        expand_queries: false, 
+        db_dim_1: 0, 
+        db_dim_2: 0 
+    }
+}
+
 pub fn params_from_json(cfg: &str) -> Params {
     let v: Value = serde_json::from_str(cfg).unwrap();
     let n = v["n"].as_u64().unwrap() as usize;