UNPKG

mina-zkml

Version:

Zero-knowledge machine learning for Mina Protocol

101 lines 3.25 kB
import { wasm_init, wasm_main, WasmProverSystem, WasmVerifierSystem } from '../pkg/mina_zkml.js'; import { readFile } from 'fs/promises'; import { isAbsolute, resolve } from 'path'; // WASM environment setup const wasmEnv = { memory: new WebAssembly.Memory({ initial: 256 }), now: () => BigInt(Date.now()), seed: () => BigInt(Date.now()), abort: () => { throw new Error('abort called'); }, process_exit: (code) => { if (code !== 0) { throw new Error(`process.exit(${code})`); } } }; // Make wasmEnv globally available globalThis.env = wasmEnv; export class ZKML { constructor(proofSystem) { this.proofSystem = proofSystem; } static async initialize() { if (!ZKML.initialized) { if (!ZKML.initPromise) { ZKML.initPromise = Promise.all([ Promise.resolve().then(() => { wasm_init(); wasm_main(); }) ]).then(() => { ZKML.initialized = true; }); } await ZKML.initPromise; } } static async loadModelBytes(modelPath) { const path = isAbsolute(modelPath) ? modelPath : resolve(process.cwd(), modelPath); const buffer = await readFile(path); return new Uint8Array(buffer); } static async create(modelPath, runArgs = { variables: { batch_size: 1 } }, visibility = { input: "Private", output: "Private" }) { await ZKML.initialize(); const modelBytes = await ZKML.loadModelBytes(modelPath); const proofSystem = new WasmProverSystem(modelBytes, runArgs, { input: visibility.input, output: visibility.output }); return new ZKML(proofSystem); } async prove(inputs) { const result = await this.proofSystem.prove(inputs); return result; } async exportVerifier() { const verifier = this.proofSystem.verifier(); return verifier; } async serializeVerifier() { try { const verifier = await this.exportVerifier(); const serialized = verifier.serialize(); return serialized; } catch (error) { throw error; } } static async deserializeVerifier(serialized) { try { await ZKML.initialize(); const verifier = WasmVerifierSystem.deserialize(serialized); return verifier; } catch (error) { throw error; } } static async verify(proof, verifier, publicInputs, publicOutputs) { await ZKML.initialize(); try { // Validate inputs if (!proof) throw new Error("Proof string is empty"); if (!verifier) throw new Error("Verifier is not provided"); // Verify the proof const result = await verifier.verify(proof, publicInputs || null, publicOutputs || null); return result; } catch (error) { return false; } } } ZKML.initialized = false; ZKML.initPromise = null; //# sourceMappingURL=zkml.js.map