dop-wallet-v6 1.3.34 → 1.3.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/.eslintrc.js +1 -11
  2. package/README.md +9 -367
  3. package/dist/services/dop/core/index.d.ts +0 -4
  4. package/dist/services/dop/core/index.js +0 -5
  5. package/dist/services/dop/core/index.js.map +1 -1
  6. package/dist/services/dop/core/prover.js +50 -1
  7. package/dist/services/dop/core/prover.js.map +1 -1
  8. package/dist/services/dop/core/react-native-init.js +1 -28
  9. package/dist/services/dop/core/react-native-init.js.map +1 -1
  10. package/dist/services/dop/crypto/custom-prover.d.ts +78 -0
  11. package/dist/services/dop/crypto/custom-prover.js +78 -0
  12. package/dist/services/dop/crypto/custom-prover.js.map +1 -0
  13. package/dist/services/dop/crypto/index.d.ts +1 -0
  14. package/dist/services/dop/crypto/index.js +18 -0
  15. package/dist/services/dop/crypto/index.js.map +1 -0
  16. package/dist/services/dop/index.d.ts +1 -0
  17. package/dist/services/dop/index.js +1 -0
  18. package/dist/services/dop/index.js.map +1 -1
  19. package/package.json +1 -1
  20. package/react-native.js +1 -13
  21. package/dist/services/dop/core/react-native-prover-setup.d.ts +0 -51
  22. package/dist/services/dop/core/react-native-prover-setup.js +0 -227
  23. package/dist/services/dop/core/react-native-prover-setup.js.map +0 -1
  24. package/dist/services/dop/crypto/mopro-circuit-loader.d.ts +0 -103
  25. package/dist/services/dop/crypto/mopro-circuit-loader.js +0 -308
  26. package/dist/services/dop/crypto/mopro-circuit-loader.js.map +0 -1
  27. package/dist/services/dop/crypto/mopro-prover-adapter.d.ts +0 -117
  28. package/dist/services/dop/crypto/mopro-prover-adapter.js +0 -243
  29. package/dist/services/dop/crypto/mopro-prover-adapter.js.map +0 -1
  30. package/dist/services/dop/crypto/user-rapidsnark-adapter.d.ts +0 -98
  31. package/dist/services/dop/crypto/user-rapidsnark-adapter.js +0 -226
  32. package/dist/services/dop/crypto/user-rapidsnark-adapter.js.map +0 -1
  33. package/dist/services/transactions/tx-encrypt-relayer.d.ts +0 -6
  34. package/dist/services/transactions/tx-encrypt-relayer.js +0 -80
  35. package/dist/services/transactions/tx-encrypt-relayer.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"mopro-circuit-loader.js","sourceRoot":"","sources":["../../../../src/services/dop/crypto/mopro-circuit-loader.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;GAaG;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,6CAAgD;AA0BhD,IAAI,UAAU,GAAyB,IAAI,CAAC;AAE5C;;GAEG;AACI,MAAM,cAAc,GAAG,KAAK,IAAsB,EAAE;;IACzD,IAAI,CAAC,uBAAa,EAAE;QAClB,OAAO,KAAK,CAAC;KACd;IAED,IAAI;QACF,MAAM,UAAU,GAAG,iBAAiB,CAAC;QACrC,MAAM,UAAU,GAAG,YAAa,UAAU,0DAAC,CAAC;QAC5C,UAAU,GAAG,CAAC,UAAU,CAAC,OAAO,IAAI,UAAU,CAAkB,CAAC;QAEjE,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;QAC9C,OAAO,IAAI,CAAC;KACb;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,CAAC,IAAI,CAAC,mCAAmC,EAAE,KAAK,CAAC,CAAC;QACzD,OAAO,CAAC,GAAG,CAAC,yDAAyD,CAAC,CAAC;QACvE,OAAO,KAAK,CAAC;KACd;AACH,CAAC,CAAC;AAjBW,QAAA,cAAc,kBAiBzB;AAEF;;GAEG;AACI,MAAM,eAAe,GAAG,GAAY,EAAE;IAC3C,OAAO,uBAAa,IAAI,UAAU,KAAK,IAAI,CAAC;AAC9C,CAAC,CAAC;AAFW,QAAA,eAAe,mBAE1B;AAEF;;;;GAIG;AACH,MAAa,kBAAkB;IACrB,YAAY,GAA6B,IAAI,GAAG,EAAE,CAAC;IACnD,WAAW,CAAS;IACpB,WAAW,GAAG,KAAK,CAAC;IAE5B;QACE,IAAI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ACD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;IACtB,CAAC;IAED;;OAEG;IACK,MAAM,CAAC,cAAc,CAAC,KAAa;QACzC,IAAI,KAAK,GAAG,IAAI,EAAE;YAChB,OAAO,GAAG,KAAK,IAAI,CAAC;SACrB;QACD,IAAI,KAAK,GAAG,IAAI,GAAG,IAAI,EAAE;YACvB,OAAO,GAAG,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC;SAC1C;QACD,OAAO,GAAG,CAAC,KAAK,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC;IACpD,CAAC;CACF;AAhQD,gDAgQC;AAED;;;GAGG;AACI,MAAM,mBAAmB,GAAG,KAAK,IAAiC,EAAE;IACzE,IAAI,CAAC,IAAA,uBAAe,GAAE,EAAE;QACtB,MAAM,WAAW,GAAG,MAAM,IAAA,sBAAc,GAAE,CAAC;QAC3C,IAAI,CAAC,WAAW,EAAE;YAChB,MAAM,IAAI,KAAK,CACb,sFAAsF,CACvF,CAAC;SACH;KACF;IAED,MAAM,MAAM,GAAG,IAAI,kBAAkB,EAAE,CAAC;IACxC,MAAM,MAAM,CAAC,UAAU,EAAE,CAAC;IAC1B,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AAbW,QAAA,mBAAmB,uBAa9B","sourcesContent":["/**\n * Mopro Circuit Loader for React Native\n * \n * This module handles loading and caching DOP circuit files (zkey) on\n * the React Native device filesystem. Circuit files are downloaded from\n * IPFS by the artifact downloader and then saved to the app's document\n * directory for use by Mopro's native proof generation.\n * \n * Features:\n * - Caches circuit file paths to avoid repeated file operations\n * - Handles circuit file compression (brotli)\n * - Preloads circuits at app startup for faster proof generation\n * - Manages cleanup of old circuit files\n */\n\nimport { isReactNative } from '../util/runtime';\n\n/**\n * Circuit file information\n */\ninterface CircuitInfo {\n circuitId: string;\n zkeyPath: string;\n fileSize: number;\n loadedAt: number;\n}\n\n/**\n * React Native filesystem interface (react-native-fs)\n * Declared as interface to avoid compilation errors when not installed\n */\ninterface ReactNativeFS {\n DocumentDirectoryPath: string;\n mkdir: (path: string, options?: { NSURLIsExcludedFromBackupKey?: boolean }) => Promise<void>;\n writeFile: (path: string, contents: string, encoding?: string) => Promise<void>;\n readFile: (path: string, encoding?: string) => Promise<string>;\n exists: (path: string) => Promise<boolean>;\n unlink: (path: string) => Promise<void>;\n stat: (path: string) => Promise<{ size: number }>;\n}\n\nlet rnfsModule: ReactNativeFS | null = null;\n\n/**\n * Initialize React Native filesystem module\n */\nexport const initializeRNFS = async (): Promise<boolean> => {\n if (!isReactNative) {\n return false;\n }\n\n try {\n const moduleName = 'react-native-fs';\n const rnfsImport = await import(moduleName);\n rnfsModule = (rnfsImport.default ?? rnfsImport) as ReactNativeFS;\n \n console.log('📁 React Native FS initialized');\n return true;\n } catch (error) {\n console.warn('⚠️ react-native-fs not available:', error);\n console.log('💡 Install react-native-fs: npm install react-native-fs');\n return false;\n }\n};\n\n/**\n * Check if RNFS is available\n */\nexport const isRNFSAvailable = (): boolean => {\n return isReactNative && rnfsModule !== null;\n};\n\n/**\n * Mopro Circuit Loader Class\n * \n * Manages circuit files on the React Native filesystem\n */\nexport class MoproCircuitLoader {\n private circuitCache: Map<string, CircuitInfo> = new Map();\n private circuitsDir: string;\n private initialized = false;\n\n constructor() {\n if (!isRNFSAvailable() || !rnfsModule) {\n throw new Error(\n 'react-native-fs not available. Install it with: npm install react-native-fs'\n );\n }\n \n this.circuitsDir = `${rnfsModule.DocumentDirectoryPath}/dop-circuits`;\n }\n\n /**\n * Initialize the circuit loader\n * Creates the circuits directory if it doesn't exist\n */\n async initialize(): Promise<void> {\n if (this.initialized || !rnfsModule) {\n return;\n }\n\n try {\n console.log('📂 Initializing Mopro circuit loader...');\n console.log(` Circuits directory: ${this.circuitsDir}`);\n\n // Create circuits directory\n await rnfsModule.mkdir(this.circuitsDir, {\n NSURLIsExcludedFromBackupKey: true // Don't backup to iCloud\n });\n\n this.initialized = true;\n console.log('✅ Circuit loader initialized');\n } catch (error) {\n // Directory might already exist, that's okay\n if (error instanceof Error && error.message.includes('already exists')) {\n this.initialized = true;\n console.log('✅ Circuit loader initialized (directory exists)');\n } else {\n console.error('❌ Failed to initialize circuit loader:', error);\n throw error;\n }\n }\n }\n\n /**\n * Load a circuit file from buffer and save to filesystem\n * \n * @param circuitId - Circuit identifier (e.g., '1x2', '2x2')\n * @param zkeyBuffer - The zkey file buffer\n * @returns Path to the saved zkey file\n */\n async loadCircuit(\n circuitId: string,\n zkeyBuffer: Uint8Array\n ): Promise<string> {\n if (!rnfsModule) {\n throw new Error('react-native-fs not initialized');\n }\n\n await this.initialize();\n\n // Check if circuit is already cached\n const cached = this.circuitCache.get(circuitId);\n if (cached) {\n // Verify file still exists\n const exists = await rnfsModule.exists(cached.zkeyPath);\n if (exists) {\n console.log(`📦 Using cached circuit: ${circuitId}`);\n return cached.zkeyPath;\n }\n // File was deleted, remove from cache\n this.circuitCache.delete(circuitId);\n }\n\n try {\n console.log(`💾 Loading circuit to filesystem: ${circuitId}`);\n const startTime = Date.now();\n\n // Generate file path\n const zkeyPath = `${this.circuitsDir}/${circuitId}.zkey`;\n\n // Convert buffer to base64 for react-native-fs\n const base64Data = MoproCircuitLoader.bufferToBase64(zkeyBuffer);\n\n // Write to file\n await rnfsModule.writeFile(zkeyPath, base64Data, 'base64');\n\n // Verify file was written\n const stat = await rnfsModule.stat(zkeyPath);\n const fileSize = stat.size;\n\n // Cache the circuit info\n const circuitInfo: CircuitInfo = {\n circuitId,\n zkeyPath,\n fileSize,\n loadedAt: Date.now()\n };\n this.circuitCache.set(circuitId, circuitInfo);\n\n const elapsedTime = Date.now() - startTime;\n console.log(`✅ Circuit loaded successfully in ${elapsedTime}ms`);\n // eslint-disable-next-line no-console\n console.log(` File size: ${MoproCircuitLoader.formatFileSize(fileSize)}`);\n // eslint-disable-next-line no-console\n console.log(` Path: ${zkeyPath}`);\n\n return zkeyPath;\n\n } catch (error) {\n console.error(`❌ Failed to load circuit ${circuitId}:`, error);\n throw new Error(\n `Circuit loading failed: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * Preload multiple circuits at app startup\n * This prevents delays during first proof generation\n * \n * @param circuits - Map of circuitId to zkeyBuffer\n */\n async preloadCircuits(\n circuits: Map<string, Uint8Array>\n ): Promise<void> {\n console.log(`🚀 Preloading ${circuits.size} circuits...`);\n const startTime = Date.now();\n\n const loadPromises = Array.from(circuits.entries()).map(\n ([circuitId, zkeyBuffer]) => this.loadCircuit(circuitId, zkeyBuffer)\n );\n\n try {\n await Promise.all(loadPromises);\n const elapsedTime = Date.now() - startTime;\n console.log(`✅ Preloaded ${circuits.size} circuits in ${elapsedTime}ms`);\n } catch (error) {\n console.error('❌ Failed to preload circuits:', error);\n throw error;\n }\n }\n\n /**\n * Get cached circuit info\n */\n getCircuitInfo(circuitId: string): CircuitInfo | undefined {\n return this.circuitCache.get(circuitId);\n }\n\n /**\n * Clear all cached circuits from memory\n * (Files remain on disk)\n */\n clearCache(): void {\n console.log(`🗑️ Clearing circuit cache (${this.circuitCache.size} entries)`);\n this.circuitCache.clear();\n }\n\n /**\n * Delete circuit files from filesystem\n * \n * @param circuitIds - Array of circuit IDs to delete, or empty to delete all\n */\n async deleteCircuits(circuitIds?: string[]): Promise<void> {\n if (!rnfsModule) {\n throw new Error('react-native-fs not initialized');\n }\n\n const toDelete = circuitIds || Array.from(this.circuitCache.keys());\n // eslint-disable-next-line no-console\n console.log(`🗑️ Deleting ${toDelete.length} circuit files...`);\n\n const rnfs = rnfsModule; // Capture for use in async callbacks\n const deletePromises = toDelete.map(async (circuitId) => {\n try {\n const cached = this.circuitCache.get(circuitId);\n if (cached) {\n const exists = await rnfs.exists(cached.zkeyPath);\n if (exists) {\n await rnfs.unlink(cached.zkeyPath);\n // eslint-disable-next-line no-console\n console.log(` Deleted: ${circuitId}`);\n }\n this.circuitCache.delete(circuitId);\n }\n } catch (error) {\n // eslint-disable-next-line no-console\n console.warn(` Failed to delete ${circuitId}:`, error);\n }\n });\n \n await Promise.all(deletePromises);\n\n // eslint-disable-next-line no-console\n console.log('✅ Circuit deletion complete');\n }\n\n /**\n * Get total size of cached circuits\n */\n getTotalCacheSize(): number {\n let totalSize = 0;\n for (const info of this.circuitCache.values()) {\n totalSize += info.fileSize;\n }\n return totalSize;\n }\n\n /**\n * Get cache statistics\n */\n getCacheStats(): {\n circuitCount: number;\n totalSize: string;\n circuits: CircuitInfo[];\n } {\n const circuits = Array.from(this.circuitCache.values());\n return {\n circuitCount: circuits.length,\n totalSize: MoproCircuitLoader.formatFileSize(this.getTotalCacheSize()),\n circuits\n };\n }\n\n /**\n * Convert Uint8Array to base64 string\n */\n private static bufferToBase64(buffer: Uint8Array): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(buffer).toString('base64');\n }\n\n // Fallback for environments without Buffer\n let binary = '';\n for (let i = 0; i < buffer.length; i += 1) {\n binary += String.fromCharCode(buffer[i]);\n }\n return btoa(binary);\n }\n\n /**\n * Format file size for human readability\n */\n private static formatFileSize(bytes: number): string {\n if (bytes < 1024) {\n return `${bytes} B`;\n }\n if (bytes < 1024 * 1024) {\n return `${(bytes / 1024).toFixed(2)} KB`;\n }\n return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;\n }\n}\n\n/**\n * Create a circuit loader instance\n * Automatically initializes RNFS if not already done\n */\nexport const createCircuitLoader = async (): Promise<MoproCircuitLoader> => {\n if (!isRNFSAvailable()) {\n const initialized = await initializeRNFS();\n if (!initialized) {\n throw new Error(\n 'Failed to initialize react-native-fs. Make sure it is installed and linked properly.'\n );\n }\n }\n\n const loader = new MoproCircuitLoader();\n await loader.initialize();\n return loader;\n};\n"]}
@@ -1,117 +0,0 @@
1
- /**
2
- * Mopro Prover Adapter for React Native
3
- *
4
- * This adapter enables fully on-device zero-knowledge proof generation
5
- * using the Mopro (Mobile Prover) toolkit, eliminating the need for
6
- * backend witness generation services.
7
- *
8
- * Mopro provides native witness calculation and proof generation through
9
- * Rust FFI bindings, bypassing React Native's WebAssembly limitations.
10
- *
11
- * Performance Benefits:
12
- * - Witness generation: 2-29x faster than browser SnarkJS
13
- * - Proof generation: 8-15x faster than browser SnarkJS
14
- * - Native iOS/Android performance
15
- * - No network calls required
16
- *
17
- * @see https://zkmopro.org/docs/intro
18
- */
19
- import type { FormattedCircuitInputsDop, Proof } from 'dop-engine-v3';
20
- /**
21
- * Mopro CircomProofResult structure
22
- * This is the proof format returned by mopro's generateCircomProof
23
- */
24
- interface MoproCircomProofResult {
25
- proof: {
26
- a: string[];
27
- b: string[][];
28
- c: string[];
29
- };
30
- pub_signals: string[];
31
- }
32
- /**
33
- * Mopro ProofLib enum for selecting proof backend
34
- */
35
- declare enum ProofLib {
36
- Arkworks = "Arkworks",
37
- Rapidsnark = "Rapidsnark"
38
- }
39
- /**
40
- * Initialize Mopro module
41
- * Dynamically imports mopro-ffi to avoid compilation errors when not installed
42
- */
43
- export declare const initializeMopro: () => Promise<boolean>;
44
- /**
45
- * Check if Mopro is available and initialized
46
- */
47
- export declare const isMoproAvailable: () => boolean;
48
- /**
49
- * Mopro Prover Adapter Class
50
- *
51
- * Provides a unified interface for generating proofs with Mopro
52
- * that is compatible with DOP Engine's proof format.
53
- */
54
- export declare class MoproProverAdapter {
55
- private proofLib;
56
- constructor(proofLib?: ProofLib);
57
- /**
58
- * Generate a zero-knowledge proof using Mopro
59
- *
60
- * @param circuitId - Circuit identifier for logging/debugging
61
- * @param zkeyPath - Path to the zkey file on device filesystem
62
- * @param jsonInputs - Circuit inputs in JSON format
63
- * @param progressCallback - Optional progress callback (0-100)
64
- * @returns DOP Engine compatible proof object
65
- */
66
- generateProof(circuitId: string, zkeyPath: string, jsonInputs: FormattedCircuitInputsDop, progressCallback?: (progress: number) => void): Promise<Proof>;
67
- /**
68
- * Verify a proof using Mopro (optional, for debugging)
69
- *
70
- * @param zkeyPath - Path to the zkey file
71
- * @param proof - The proof to verify
72
- * @returns true if proof is valid
73
- */
74
- verifyProof(zkeyPath: string, proof: MoproCircomProofResult): Promise<boolean>;
75
- /**
76
- * Convert Mopro proof format to DOP Engine format
77
- *
78
- * Mopro format:
79
- * {
80
- * proof: { a: [string, string], b: [[string, string], [string, string]], c: [string, string] },
81
- * pub_signals: string[]
82
- * }
83
- *
84
- * DOP Engine format:
85
- * {
86
- * pi_a: [string, string],
87
- * pi_b: [[string, string], [string, string]],
88
- * pi_c: [string, string]
89
- * }
90
- *
91
- * Note: Public signals are handled separately by DOP Engine
92
- */
93
- private static convertMoproProofToDopFormat;
94
- /**
95
- * Get public signals from Mopro proof result
96
- * DOP Engine may need these separately
97
- */
98
- static getPublicSignals(moproResult: MoproCircomProofResult): string[];
99
- /**
100
- * Set the proof backend (Arkworks or Rapidsnark)
101
- *
102
- * Arkworks: Pure Rust implementation, consistent performance
103
- * Rapidsnark: C++ optimized, potentially faster on some devices
104
- */
105
- setProofLib(proofLib: ProofLib): void;
106
- }
107
- /**
108
- * Export ProofLib enum for external use
109
- */
110
- export { ProofLib };
111
- /**
112
- * Create a configured Mopro prover adapter
113
- *
114
- * @param useRapidsnark - Use Rapidsnark backend instead of Arkworks
115
- * @returns Configured MoproProverAdapter instance
116
- */
117
- export declare const createMoproProver: (useRapidsnark?: boolean) => MoproProverAdapter;
@@ -1,243 +0,0 @@
1
- "use strict";
2
- /**
3
- * Mopro Prover Adapter for React Native
4
- *
5
- * This adapter enables fully on-device zero-knowledge proof generation
6
- * using the Mopro (Mobile Prover) toolkit, eliminating the need for
7
- * backend witness generation services.
8
- *
9
- * Mopro provides native witness calculation and proof generation through
10
- * Rust FFI bindings, bypassing React Native's WebAssembly limitations.
11
- *
12
- * Performance Benefits:
13
- * - Witness generation: 2-29x faster than browser SnarkJS
14
- * - Proof generation: 8-15x faster than browser SnarkJS
15
- * - Native iOS/Android performance
16
- * - No network calls required
17
- *
18
- * @see https://zkmopro.org/docs/intro
19
- */
20
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
21
- if (k2 === undefined) k2 = k;
22
- var desc = Object.getOwnPropertyDescriptor(m, k);
23
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
24
- desc = { enumerable: true, get: function() { return m[k]; } };
25
- }
26
- Object.defineProperty(o, k2, desc);
27
- }) : (function(o, m, k, k2) {
28
- if (k2 === undefined) k2 = k;
29
- o[k2] = m[k];
30
- }));
31
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
32
- Object.defineProperty(o, "default", { enumerable: true, value: v });
33
- }) : function(o, v) {
34
- o["default"] = v;
35
- });
36
- var __importStar = (this && this.__importStar) || function (mod) {
37
- if (mod && mod.__esModule) return mod;
38
- var result = {};
39
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
40
- __setModuleDefault(result, mod);
41
- return result;
42
- };
43
- Object.defineProperty(exports, "__esModule", { value: true });
44
- exports.createMoproProver = exports.ProofLib = exports.MoproProverAdapter = exports.isMoproAvailable = exports.initializeMopro = void 0;
45
- const runtime_1 = require("../util/runtime");
46
- /**
47
- * Mopro ProofLib enum for selecting proof backend
48
- */
49
- var ProofLib;
50
- (function (ProofLib) {
51
- ProofLib["Arkworks"] = "Arkworks";
52
- ProofLib["Rapidsnark"] = "Rapidsnark";
53
- })(ProofLib || (ProofLib = {}));
54
- exports.ProofLib = ProofLib;
55
- let moproModule = null;
56
- /**
57
- * Initialize Mopro module
58
- * Dynamically imports mopro-ffi to avoid compilation errors when not installed
59
- */
60
- const initializeMopro = async () => {
61
- var _a;
62
- if (!runtime_1.isReactNative) {
63
- console.log('🖥️ Not in React Native environment, skipping mopro initialization');
64
- return false;
65
- }
66
- try {
67
- console.log('📱 Initializing Mopro for React Native...');
68
- // Dynamic import to avoid errors when mopro-ffi is not installed
69
- let moproImport;
70
- try {
71
- const moduleName = 'mopro-ffi';
72
- moproImport = await (_a = moduleName, Promise.resolve().then(() => __importStar(require(_a))));
73
- }
74
- catch (importError) {
75
- console.log('📝 mopro-ffi not available:', String(importError));
76
- console.log('💡 Install mopro-ffi for on-device proof generation:');
77
- console.log(' npm install mopro-ffi');
78
- console.log(' Follow setup guide: https://zkmopro.org/docs/setup/react-native-setup');
79
- return false;
80
- }
81
- const { generateCircomProof, verifyCircomProof } = moproImport;
82
- moproModule = {
83
- generateCircomProof,
84
- verifyCircomProof
85
- };
86
- console.log('✅ Mopro initialized successfully');
87
- console.log('🚀 Fully on-device proof generation enabled');
88
- return true;
89
- }
90
- catch (error) {
91
- console.warn('⚠️ Mopro initialization failed:', error);
92
- return false;
93
- }
94
- };
95
- exports.initializeMopro = initializeMopro;
96
- /**
97
- * Check if Mopro is available and initialized
98
- */
99
- const isMoproAvailable = () => {
100
- return runtime_1.isReactNative && moproModule !== null;
101
- };
102
- exports.isMoproAvailable = isMoproAvailable;
103
- /**
104
- * Mopro Prover Adapter Class
105
- *
106
- * Provides a unified interface for generating proofs with Mopro
107
- * that is compatible with DOP Engine's proof format.
108
- */
109
- class MoproProverAdapter {
110
- proofLib;
111
- constructor(proofLib = ProofLib.Arkworks) {
112
- this.proofLib = proofLib;
113
- if (!(0, exports.isMoproAvailable)()) {
114
- throw new Error('Mopro is not initialized. Call initializeMopro() first.');
115
- }
116
- }
117
- /**
118
- * Generate a zero-knowledge proof using Mopro
119
- *
120
- * @param circuitId - Circuit identifier for logging/debugging
121
- * @param zkeyPath - Path to the zkey file on device filesystem
122
- * @param jsonInputs - Circuit inputs in JSON format
123
- * @param progressCallback - Optional progress callback (0-100)
124
- * @returns DOP Engine compatible proof object
125
- */
126
- async generateProof(circuitId, zkeyPath, jsonInputs, progressCallback) {
127
- if (!moproModule) {
128
- throw new Error('Mopro module not initialized');
129
- }
130
- try {
131
- console.log(`🔐 Generating proof with Mopro for circuit: ${circuitId}`);
132
- const startTime = Date.now();
133
- if (progressCallback) {
134
- progressCallback(10);
135
- }
136
- // Convert circuit inputs to JSON string
137
- const circuitInputsJson = JSON.stringify(jsonInputs);
138
- // Remove 'file://' prefix if present
139
- const cleanZkeyPath = zkeyPath.replace('file://', '');
140
- if (progressCallback) {
141
- progressCallback(20);
142
- }
143
- // Generate proof using Mopro
144
- console.log(` Using proof backend: ${this.proofLib}`);
145
- const moproResult = moproModule.generateCircomProof(cleanZkeyPath, circuitInputsJson, this.proofLib);
146
- if (progressCallback) {
147
- progressCallback(90);
148
- }
149
- // Convert Mopro proof format to DOP Engine format
150
- const dopProof = MoproProverAdapter.convertMoproProofToDopFormat(moproResult);
151
- const elapsedTime = Date.now() - startTime;
152
- console.log(`✅ Proof generated successfully in ${elapsedTime}ms`);
153
- if (progressCallback) {
154
- progressCallback(100);
155
- }
156
- return dopProof;
157
- }
158
- catch (error) {
159
- console.error(`❌ Mopro proof generation failed for ${circuitId}:`, error);
160
- throw new Error(`Mopro proof generation failed: ${error instanceof Error ? error.message : String(error)}`);
161
- }
162
- }
163
- /**
164
- * Verify a proof using Mopro (optional, for debugging)
165
- *
166
- * @param zkeyPath - Path to the zkey file
167
- * @param proof - The proof to verify
168
- * @returns true if proof is valid
169
- */
170
- async verifyProof(zkeyPath, proof) {
171
- if (!moproModule) {
172
- throw new Error('Mopro module not initialized');
173
- }
174
- try {
175
- const cleanZkeyPath = zkeyPath.replace('file://', '');
176
- const isValid = moproModule.verifyCircomProof(cleanZkeyPath, proof, this.proofLib);
177
- console.log(`🔍 Proof verification result: ${isValid ? '✅ Valid' : '❌ Invalid'}`);
178
- return isValid;
179
- }
180
- catch (error) {
181
- console.error('❌ Proof verification failed:', error);
182
- return false;
183
- }
184
- }
185
- /**
186
- * Convert Mopro proof format to DOP Engine format
187
- *
188
- * Mopro format:
189
- * {
190
- * proof: { a: [string, string], b: [[string, string], [string, string]], c: [string, string] },
191
- * pub_signals: string[]
192
- * }
193
- *
194
- * DOP Engine format:
195
- * {
196
- * pi_a: [string, string],
197
- * pi_b: [[string, string], [string, string]],
198
- * pi_c: [string, string]
199
- * }
200
- *
201
- * Note: Public signals are handled separately by DOP Engine
202
- */
203
- static convertMoproProofToDopFormat(moproResult) {
204
- return {
205
- pi_a: [moproResult.proof.a[0], moproResult.proof.a[1]],
206
- pi_b: [
207
- [moproResult.proof.b[0][0], moproResult.proof.b[0][1]],
208
- [moproResult.proof.b[1][0], moproResult.proof.b[1][1]]
209
- ],
210
- pi_c: [moproResult.proof.c[0], moproResult.proof.c[1]]
211
- };
212
- }
213
- /**
214
- * Get public signals from Mopro proof result
215
- * DOP Engine may need these separately
216
- */
217
- static getPublicSignals(moproResult) {
218
- return moproResult.pub_signals;
219
- }
220
- /**
221
- * Set the proof backend (Arkworks or Rapidsnark)
222
- *
223
- * Arkworks: Pure Rust implementation, consistent performance
224
- * Rapidsnark: C++ optimized, potentially faster on some devices
225
- */
226
- setProofLib(proofLib) {
227
- this.proofLib = proofLib;
228
- console.log(`📝 Mopro proof backend set to: ${proofLib}`);
229
- }
230
- }
231
- exports.MoproProverAdapter = MoproProverAdapter;
232
- /**
233
- * Create a configured Mopro prover adapter
234
- *
235
- * @param useRapidsnark - Use Rapidsnark backend instead of Arkworks
236
- * @returns Configured MoproProverAdapter instance
237
- */
238
- const createMoproProver = (useRapidsnark = false) => {
239
- const proofLib = useRapidsnark ? ProofLib.Rapidsnark : ProofLib.Arkworks;
240
- return new MoproProverAdapter(proofLib);
241
- };
242
- exports.createMoproProver = createMoproProver;
243
- //# sourceMappingURL=mopro-prover-adapter.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"mopro-prover-adapter.js","sourceRoot":"","sources":["../../../../src/services/dop/crypto/mopro-prover-adapter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,6CAAgD;AAgBhD;;GAEG;AACH,IAAK,QAGJ;AAHD,WAAK,QAAQ;IACX,iCAAqB,CAAA;IACrB,qCAAyB,CAAA;AAC3B,CAAC,EAHI,QAAQ,KA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5B","sourcesContent":["/**\n * Mopro Prover Adapter for React Native\n * \n * This adapter enables fully on-device zero-knowledge proof generation\n * using the Mopro (Mobile Prover) toolkit, eliminating the need for\n * backend witness generation services.\n * \n * Mopro provides native witness calculation and proof generation through\n * Rust FFI bindings, bypassing React Native's WebAssembly limitations.\n * \n * Performance Benefits:\n * - Witness generation: 2-29x faster than browser SnarkJS\n * - Proof generation: 8-15x faster than browser SnarkJS\n * - Native iOS/Android performance\n * - No network calls required\n * \n * @see https://zkmopro.org/docs/intro\n */\n\nimport { isReactNative } from '../util/runtime';\nimport type { FormattedCircuitInputsDop, Proof } from 'dop-engine-v3';\n\n/**\n * Mopro CircomProofResult structure\n * This is the proof format returned by mopro's generateCircomProof\n */\ninterface MoproCircomProofResult {\n proof: {\n a: string[];\n b: string[][];\n c: string[];\n };\n pub_signals: string[];\n}\n\n/**\n * Mopro ProofLib enum for selecting proof backend\n */\nenum ProofLib {\n Arkworks = 'Arkworks',\n Rapidsnark = 'Rapidsnark'\n}\n\n/**\n * Mopro FFI interface (dynamically imported)\n */\ninterface MoproFFI {\n generateCircomProof: (\n zkeyPath: string,\n circuitInputsJson: string,\n proofLib: ProofLib\n ) => MoproCircomProofResult;\n \n verifyCircomProof: (\n zkeyPath: string,\n proof: MoproCircomProofResult,\n proofLib: ProofLib\n ) => boolean;\n}\n\nlet moproModule: MoproFFI | null = null;\n\n/**\n * Initialize Mopro module\n * Dynamically imports mopro-ffi to avoid compilation errors when not installed\n */\nexport const initializeMopro = async (): Promise<boolean> => {\n if (!isReactNative) {\n console.log('🖥️ Not in React Native environment, skipping mopro initialization');\n return false;\n }\n\n try {\n console.log('📱 Initializing Mopro for React Native...');\n \n // Dynamic import to avoid errors when mopro-ffi is not installed\n let moproImport: unknown;\n try {\n const moduleName = 'mopro-ffi';\n moproImport = await import(moduleName);\n } catch (importError) {\n console.log('📝 mopro-ffi not available:', String(importError));\n console.log('💡 Install mopro-ffi for on-device proof generation:');\n console.log(' npm install mopro-ffi');\n console.log(' Follow setup guide: https://zkmopro.org/docs/setup/react-native-setup');\n return false;\n }\n \n const { generateCircomProof, verifyCircomProof } = moproImport as {\n generateCircomProof: MoproFFI['generateCircomProof'];\n verifyCircomProof: MoproFFI['verifyCircomProof'];\n };\n \n moproModule = {\n generateCircomProof,\n verifyCircomProof\n };\n \n console.log('✅ Mopro initialized successfully');\n console.log('🚀 Fully on-device proof generation enabled');\n return true;\n \n } catch (error) {\n console.warn('⚠️ Mopro initialization failed:', error);\n return false;\n }\n};\n\n/**\n * Check if Mopro is available and initialized\n */\nexport const isMoproAvailable = (): boolean => {\n return isReactNative && moproModule !== null;\n};\n\n/**\n * Mopro Prover Adapter Class\n * \n * Provides a unified interface for generating proofs with Mopro\n * that is compatible with DOP Engine's proof format.\n */\nexport class MoproProverAdapter {\n private proofLib: ProofLib;\n\n constructor(proofLib: ProofLib = ProofLib.Arkworks) {\n this.proofLib = proofLib;\n \n if (!isMoproAvailable()) {\n throw new Error(\n 'Mopro is not initialized. Call initializeMopro() first.'\n );\n }\n }\n\n /**\n * Generate a zero-knowledge proof using Mopro\n * \n * @param circuitId - Circuit identifier for logging/debugging\n * @param zkeyPath - Path to the zkey file on device filesystem\n * @param jsonInputs - Circuit inputs in JSON format\n * @param progressCallback - Optional progress callback (0-100)\n * @returns DOP Engine compatible proof object\n */\n async generateProof(\n circuitId: string,\n zkeyPath: string,\n jsonInputs: FormattedCircuitInputsDop,\n progressCallback?: (progress: number) => void\n ): Promise<Proof> {\n if (!moproModule) {\n throw new Error('Mopro module not initialized');\n }\n\n try {\n console.log(`🔐 Generating proof with Mopro for circuit: ${circuitId}`);\n const startTime = Date.now();\n\n if (progressCallback) {\n progressCallback(10);\n }\n\n // Convert circuit inputs to JSON string\n const circuitInputsJson = JSON.stringify(jsonInputs);\n \n // Remove 'file://' prefix if present\n const cleanZkeyPath = zkeyPath.replace('file://', '');\n\n if (progressCallback) {\n progressCallback(20);\n }\n\n // Generate proof using Mopro\n console.log(` Using proof backend: ${this.proofLib}`);\n const moproResult: MoproCircomProofResult = moproModule.generateCircomProof(\n cleanZkeyPath,\n circuitInputsJson,\n this.proofLib\n );\n\n if (progressCallback) {\n progressCallback(90);\n }\n\n // Convert Mopro proof format to DOP Engine format\n const dopProof: Proof = MoproProverAdapter.convertMoproProofToDopFormat(moproResult);\n\n const elapsedTime = Date.now() - startTime;\n console.log(`✅ Proof generated successfully in ${elapsedTime}ms`);\n\n if (progressCallback) {\n progressCallback(100);\n }\n\n return dopProof;\n\n } catch (error) {\n console.error(`❌ Mopro proof generation failed for ${circuitId}:`, error);\n throw new Error(\n `Mopro proof generation failed: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * Verify a proof using Mopro (optional, for debugging)\n * \n * @param zkeyPath - Path to the zkey file\n * @param proof - The proof to verify\n * @returns true if proof is valid\n */\n async verifyProof(\n zkeyPath: string,\n proof: MoproCircomProofResult\n ): Promise<boolean> {\n if (!moproModule) {\n throw new Error('Mopro module not initialized');\n }\n\n try {\n const cleanZkeyPath = zkeyPath.replace('file://', '');\n const isValid = moproModule.verifyCircomProof(\n cleanZkeyPath,\n proof,\n this.proofLib\n );\n \n console.log(`🔍 Proof verification result: ${isValid ? '✅ Valid' : '❌ Invalid'}`);\n return isValid;\n\n } catch (error) {\n console.error('❌ Proof verification failed:', error);\n return false;\n }\n }\n\n /**\n * Convert Mopro proof format to DOP Engine format\n * \n * Mopro format:\n * {\n * proof: { a: [string, string], b: [[string, string], [string, string]], c: [string, string] },\n * pub_signals: string[]\n * }\n * \n * DOP Engine format:\n * {\n * pi_a: [string, string],\n * pi_b: [[string, string], [string, string]],\n * pi_c: [string, string]\n * }\n * \n * Note: Public signals are handled separately by DOP Engine\n */\n private static convertMoproProofToDopFormat(moproResult: MoproCircomProofResult): Proof {\n return {\n pi_a: [moproResult.proof.a[0], moproResult.proof.a[1]],\n pi_b: [\n [moproResult.proof.b[0][0], moproResult.proof.b[0][1]],\n [moproResult.proof.b[1][0], moproResult.proof.b[1][1]]\n ],\n pi_c: [moproResult.proof.c[0], moproResult.proof.c[1]]\n };\n }\n\n /**\n * Get public signals from Mopro proof result\n * DOP Engine may need these separately\n */\n static getPublicSignals(moproResult: MoproCircomProofResult): string[] {\n return moproResult.pub_signals;\n }\n\n /**\n * Set the proof backend (Arkworks or Rapidsnark)\n * \n * Arkworks: Pure Rust implementation, consistent performance\n * Rapidsnark: C++ optimized, potentially faster on some devices\n */\n setProofLib(proofLib: ProofLib): void {\n this.proofLib = proofLib;\n console.log(`📝 Mopro proof backend set to: ${proofLib}`);\n }\n}\n\n/**\n * Export ProofLib enum for external use\n */\nexport { ProofLib };\n\n/**\n * Create a configured Mopro prover adapter\n * \n * @param useRapidsnark - Use Rapidsnark backend instead of Arkworks\n * @returns Configured MoproProverAdapter instance\n */\nexport const createMoproProver = (useRapidsnark = false): MoproProverAdapter => {\n const proofLib = useRapidsnark ? ProofLib.Rapidsnark : ProofLib.Arkworks;\n return new MoproProverAdapter(proofLib);\n};\n"]}
@@ -1,98 +0,0 @@
1
- /**
2
- * User-Configurable Rapidsnark Adapter for React Native
3
- *
4
- * This module provides a way for React Native developers to configure
5
- * their own Rapidsnark prover implementation, bypassing SDK limitations.
6
- *
7
- * The user is responsible for:
8
- * 1. Installing @iden3/react-native-rapidsnark
9
- * 2. Managing circuit files (.zkey files)
10
- * 3. Implementing witness generation
11
- * 4. Calling setCustomRapidsnarkProver() after engine initialization
12
- */
13
- import type { FormattedCircuitInputsDop, Proof } from 'dop-engine-v3';
14
- /**
15
- * Interface that users must implement for their Rapidsnark prover
16
- */
17
- export interface UserRapidsnarkProver {
18
- /**
19
- * Generate a zero-knowledge proof using Rapidsnark
20
- *
21
- * @param circuitId - The circuit identifier (e.g., 'dop', 'decrypt', 'nullify')
22
- * @param zkeyBuffer - The zkey file buffer (or path to zkey file in user's implementation)
23
- * @param jsonInputs - The circuit inputs as JSON object
24
- * @param progressCallback - Optional callback for progress updates
25
- * @returns Promise containing the generated proof
26
- */
27
- generateProof(circuitId: string, zkeyBuffer: Uint8Array, jsonInputs: FormattedCircuitInputsDop, progressCallback?: (progress: number) => void): Promise<Proof>;
28
- }
29
- /**
30
- * Helper function to convert Uint8Array to base64 string
31
- */
32
- export declare const uint8ArrayToBase64: (buffer: Uint8Array) => string;
33
- /**
34
- * Helper function to save buffer to file system (React Native)
35
- * Users should implement their own version using react-native-fs or similar
36
- */
37
- export declare const saveBufferToFile: (_buffer: Uint8Array, _filename: string) => Promise<string>;
38
- /**
39
- * Set a custom Rapidsnark prover implementation
40
- *
41
- * This function allows React Native developers to provide their own
42
- * Rapidsnark implementation, giving them full control over proof generation.
43
- *
44
- * @example
45
- * ```typescript
46
- * import { setCustomRapidsnarkProver } from 'dop-wallet-v6';
47
- * import { groth16Prove } from '@iden3/react-native-rapidsnark';
48
- * import RNFS from 'react-native-fs';
49
- *
50
- * // Implement your own prover adapter
51
- * const myRapidsnarkAdapter = {
52
- * async generateProof(circuitId, zkeyBuffer, jsonInputs, progressCallback) {
53
- * // 1. Save zkey to file
54
- * const zkeyPath = `${RNFS.DocumentDirectoryPath}/${circuitId}.zkey`;
55
- * await RNFS.writeFile(zkeyPath, uint8ArrayToBase64(zkeyBuffer), 'base64');
56
- *
57
- * // 2. Generate witness (implement your own witness generation)
58
- * const witnessBase64 = await generateWitness(circuitId, jsonInputs);
59
- *
60
- * // 3. Generate proof with Rapidsnark
61
- * const rapidsnarkProof = await groth16Prove(zkeyPath, witnessBase64);
62
- *
63
- * // 4. Convert to DOP Engine proof format
64
- * return {
65
- * pi_a: rapidsnarkProof.proof.a,
66
- * pi_b: rapidsnarkProof.proof.b,
67
- * pi_c: rapidsnarkProof.proof.c,
68
- * publicSignals: rapidsnarkProof.pub_signals
69
- * };
70
- * }
71
- * };
72
- *
73
- * // Set it after engine initialization
74
- * await startDopEngineReactNative(...);
75
- * setCustomRapidsnarkProver(myRapidsnarkAdapter);
76
- * ```
77
- */
78
- /**
79
- * Circuit ID mapping for DOP Engine
80
- * These IDs are used internally by DOP Engine's native prover interface
81
- */
82
- export declare const CIRCUIT_IDS: {
83
- readonly dop: 0;
84
- readonly decrypt: 1;
85
- readonly nullify: 2;
86
- };
87
- export declare const setCustomRapidsnarkProver: (userProver: UserRapidsnarkProver) => void;
88
- /**
89
- * Remove custom prover and revert to default behavior
90
- */
91
- export declare const clearCustomRapidsnarkProver: () => void;
92
- /**
93
- * Example implementation template for users to customize
94
- *
95
- * This is a reference implementation that users should copy and modify
96
- * according to their specific needs and file system setup.
97
- */
98
- export declare const createRapidsnarkProverTemplate: () => string;