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

Pure JS fallback when WASM is not available #1356

Open
mzoliker opened this issue Jan 3, 2024 · 1 comment
Open

Pure JS fallback when WASM is not available #1356

mzoliker opened this issue Jan 3, 2024 · 1 comment

Comments

@mzoliker
Copy link

mzoliker commented Jan 3, 2024

Hi,

Thank you for this wonderful library. I have a suggestion to make it even more wonderful :-).

Would it be possible to add a pure javascript fallback when WebAssembly is not available? Right now the lib just crashes in lib/protocol/crypto.js when loading WASM located in lib/protocol/crypto/poly1305.js…

A few words about my context: installation on iOS (thus no native modules and no WASM) with npm install ssh2 —ignore-scripts —no-optional
I manually patched crypto.js to avoid the crash mentioned above, but I also lost the poly1305 functionality…

I believe it would be nicer to have this lib work with a "real" pure javascript implementation (performance is not an issue for me).

Thanks a lot for your help! With my best wishes.

Kind regards,
Maurice

@ljluestc
Copy link

const fs = require('fs');

function isWebAssemblySupported() {
  try {
    if (typeof WebAssembly === "object" && typeof WebAssembly.instantiate === "function") {
      const module = new WebAssembly.Module(Uint8Array.of(0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00));
      if (module instanceof WebAssembly.Module) return new WebAssembly.Instance(module) instanceof WebAssembly.Instance;
    }
  } catch (e) {
    console.error("WebAssembly support detection failed:", e);
  }
  return false;
}

let poly1305;
try {
  if (isWebAssemblySupported()) {
    const wasmModule = new WebAssembly.Module(fs.readFileSync('path/to/your/poly1305.wasm'));
    const wasmInstance = new WebAssembly.Instance(wasmModule);
    poly1305 = wasmInstance.exports;
  } else {
    throw new Error("WebAssembly not supported, using JS fallback.");
  }
} catch (error) {
  console.warn("Failed to initialize WebAssembly, using JS fallback:", error);
  poly1305 = require('./poly1305-js'); // Adjust the path to your JS fallback
}

module.exports = poly1305;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants